├── README.md
├── application
├── .htaccess
├── command.php
├── common.php
├── config.php
├── database.php
├── index
│ ├── controller
│ │ ├── Index.php
│ │ └── News.php
│ └── model
│ │ └── News.php
└── route.php
├── build.php
├── client
├── ApiClient.php
└── client.php
├── composer.json
├── doc
├── tprestful.sql
└── 详细说明.doc
├── extend
└── .gitignore
├── public
├── .htaccess
├── favicon.ico
├── index.php
├── robots.txt
├── router.php
└── static
│ └── .gitignore
├── runtime
└── .gitignore
├── think
└── thinkphp
├── .gitignore
├── .htaccess
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE.txt
├── README.md
├── base.php
├── codecov.yml
├── composer.json
├── console.php
├── convention.php
├── helper.php
├── lang
└── zh-cn.php
├── library
├── think
│ ├── App.php
│ ├── Build.php
│ ├── Cache.php
│ ├── Collection.php
│ ├── Config.php
│ ├── Console.php
│ ├── Controller.php
│ ├── Cookie.php
│ ├── Db.php
│ ├── Debug.php
│ ├── Error.php
│ ├── Exception.php
│ ├── File.php
│ ├── Hook.php
│ ├── Lang.php
│ ├── Loader.php
│ ├── Log.php
│ ├── Model.php
│ ├── Paginator.php
│ ├── Process.php
│ ├── Request.php
│ ├── Response.php
│ ├── Route.php
│ ├── Session.php
│ ├── Template.php
│ ├── Url.php
│ ├── Validate.php
│ ├── View.php
│ ├── cache
│ │ ├── Driver.php
│ │ └── driver
│ │ │ ├── File.php
│ │ │ ├── Lite.php
│ │ │ ├── Memcache.php
│ │ │ ├── Memcached.php
│ │ │ ├── Redis.php
│ │ │ ├── Sqlite.php
│ │ │ ├── Wincache.php
│ │ │ └── Xcache.php
│ ├── config
│ │ └── driver
│ │ │ ├── Ini.php
│ │ │ ├── Json.php
│ │ │ └── Xml.php
│ ├── console
│ │ ├── Command.php
│ │ ├── Input.php
│ │ ├── LICENSE
│ │ ├── Output.php
│ │ ├── bin
│ │ │ └── README.md
│ │ ├── command
│ │ │ ├── Build.php
│ │ │ ├── Clear.php
│ │ │ ├── Help.php
│ │ │ ├── Lists.php
│ │ │ ├── Make.php
│ │ │ ├── make
│ │ │ │ ├── Controller.php
│ │ │ │ ├── Model.php
│ │ │ │ └── stubs
│ │ │ │ │ ├── controller.plain.stub
│ │ │ │ │ ├── controller.stub
│ │ │ │ │ └── model.stub
│ │ │ └── optimize
│ │ │ │ ├── Autoload.php
│ │ │ │ ├── Config.php
│ │ │ │ └── Route.php
│ │ ├── input
│ │ │ ├── Argument.php
│ │ │ ├── Definition.php
│ │ │ └── Option.php
│ │ └── output
│ │ │ ├── Ask.php
│ │ │ ├── Descriptor.php
│ │ │ ├── Formatter.php
│ │ │ ├── Question.php
│ │ │ ├── descriptor
│ │ │ └── Console.php
│ │ │ ├── driver
│ │ │ ├── Buffer.php
│ │ │ ├── Console.php
│ │ │ └── Nothing.php
│ │ │ ├── formatter
│ │ │ ├── Stack.php
│ │ │ └── Style.php
│ │ │ └── question
│ │ │ ├── Choice.php
│ │ │ └── Confirmation.php
│ ├── controller
│ │ ├── Rest.php
│ │ └── Yar.php
│ ├── db
│ │ ├── Builder.php
│ │ ├── Connection.php
│ │ ├── Query.php
│ │ ├── builder
│ │ │ ├── Mysql.php
│ │ │ ├── Pgsql.php
│ │ │ ├── Sqlite.php
│ │ │ └── Sqlsrv.php
│ │ ├── connector
│ │ │ ├── Mysql.php
│ │ │ ├── Pgsql.php
│ │ │ ├── Sqlite.php
│ │ │ ├── Sqlsrv.php
│ │ │ └── pgsql.sql
│ │ └── exception
│ │ │ ├── BindParamException.php
│ │ │ ├── DataNotFoundException.php
│ │ │ └── ModelNotFoundException.php
│ ├── debug
│ │ ├── Console.php
│ │ └── Html.php
│ ├── exception
│ │ ├── ClassNotFoundException.php
│ │ ├── DbException.php
│ │ ├── ErrorException.php
│ │ ├── Handle.php
│ │ ├── HttpException.php
│ │ ├── HttpResponseException.php
│ │ ├── PDOException.php
│ │ ├── TemplateNotFoundException.php
│ │ ├── ThrowableError.php
│ │ └── ValidateException.php
│ ├── log
│ │ └── driver
│ │ │ ├── File.php
│ │ │ ├── Socket.php
│ │ │ └── Test.php
│ ├── model
│ │ ├── Merge.php
│ │ ├── Pivot.php
│ │ └── Relation.php
│ ├── paginator
│ │ ├── Collection.php
│ │ └── driver
│ │ │ └── Bootstrap.php
│ ├── process
│ │ ├── Builder.php
│ │ ├── Utils.php
│ │ ├── exception
│ │ │ ├── Faild.php
│ │ │ └── Timeout.php
│ │ └── pipes
│ │ │ ├── Pipes.php
│ │ │ ├── Unix.php
│ │ │ └── Windows.php
│ ├── response
│ │ ├── Json.php
│ │ ├── Jsonp.php
│ │ ├── Redirect.php
│ │ ├── View.php
│ │ └── Xml.php
│ ├── session
│ │ └── driver
│ │ │ ├── Memcache.php
│ │ │ ├── Memcached.php
│ │ │ └── Redis.php
│ ├── template
│ │ ├── TagLib.php
│ │ ├── driver
│ │ │ └── File.php
│ │ └── taglib
│ │ │ └── Cx.php
│ └── view
│ │ └── driver
│ │ ├── Php.php
│ │ └── Think.php
└── traits
│ ├── controller
│ └── Jump.php
│ ├── model
│ └── SoftDelete.php
│ └── think
│ └── Instance.php
├── logo.png
├── phpunit.xml
├── start.php
└── tpl
├── default_index.tpl
├── dispatch_jump.tpl
├── page_trace.tpl
└── think_exception.tpl
/README.md:
--------------------------------------------------------------------------------
1 | "# tp5-restful"
2 |
3 | > tp5-restful的运行环境要求PHP5.4以上。
4 |
5 | 详细开发文档参考 目录doc下的详细说明.doc文档
6 |
7 | ## 目录结构
8 |
9 | 初始的目录结构如下:
10 |
11 | ~~~
12 | www WEB部署目录(或者子目录)
13 | ├─composer.json composer定义文件
14 | ├─README.md README文件
15 | ├─LICENSE.txt 授权说明文件
16 | ├─think 命令行入口文件
17 | ├─application 应用目录
18 | │ ├─common 公共模块目录(可以更改)
19 | │ ├─runtime 应用的运行时目录(可写,可定制)
20 | │ ├─module_name 模块目录
21 | │ │ ├─config.php 模块配置文件
22 | │ │ ├─common.php 模块函数文件
23 | │ │ ├─controller 控制器目录
24 | │ │ ├─model 模型目录
25 | │ │ ├─view 视图目录
26 | │ │ └─ ... 更多类库目录
27 | │ │
28 | │ ├─common.php 公共函数文件
29 | │ ├─config.php 公共配置文件
30 | │ ├─route.php 路由配置文件
31 | │ └─database.php 数据库配置文件
32 | │
33 | ├─public WEB目录(对外访问目录)
34 | │ ├─index.php 入口文件
35 | │ └─.htaccess 用于apache的重写
36 | │
37 | ├─thinkphp 框架系统目录
38 | │ ├─lang 语言文件目录
39 | │ ├─library 框架类库目录
40 | │ │ ├─think Think类库包目录
41 | │ │ └─traits 系统Trait目录
42 | │ │
43 | │ ├─mode 应用模式目录
44 | │ ├─tpl 系统模板目录
45 | │ ├─tests 单元测试文件目录
46 | │ ├─base.php 基础定义文件
47 | │ ├─console.php 控制台入口文件
48 | │ ├─convention.php 框架惯例配置文件
49 | │ ├─helper.php 助手函数文件
50 | │ ├─phpunit.xml phpunit配置文件
51 | │ └─start.php 框架入口文件
52 | │
53 | ├─extend 扩展类库目录
54 | ├─vendor 第三方类库目录(Composer依赖库)
55 | ~~~
56 |
57 | > router.php用于php自带webserver支持,可用于快速测试
58 | > 切换到public目录后,启动命令:php -S localhost:8888 router.php
59 | > 上面的目录结构和名称是可以改变的,这取决于你的入口文件和配置参数。
60 |
61 | ## 命名规范
62 |
63 | `ThinkPHP5`遵循PSR-2命名规范和PSR-4自动加载规范,并且注意如下规范:
64 |
65 | ### 目录和文件
66 |
67 | * 目录不强制规范,驼峰和小写+下划线模式均支持;
68 | * 类库、函数文件统一以`.php`为后缀;
69 | * 类的文件名均以命名空间定义,并且命名空间的路径和类库文件所在路径一致;
70 | * 类名和类文件名保持一致,统一采用驼峰法命名(首字母大写);
71 |
72 | ### 函数和类、属性命名
73 | * 类的命名采用驼峰法,并且首字母大写,例如 `User`、`UserType`,默认不需要添加后缀,例如`UserController`应该直接命名为`User`;
74 | * 函数的命名使用小写字母和下划线(小写字母开头)的方式,例如 `get_client_ip`;
75 | * 方法的命名使用驼峰法,并且首字母小写,例如 `getUserName`;
76 | * 属性的命名使用驼峰法,并且首字母小写,例如 `tableName`、`instance`;
77 | * 以双下划线“__”打头的函数或方法作为魔法方法,例如 `__call` 和 `__autoload`;
78 |
79 | ### 常量和配置
80 | * 常量以大写字母和下划线命名,例如 `APP_PATH`和 `THINK_PATH`;
81 | * 配置参数以小写字母和下划线命名,例如 `url_route_on` 和`url_convert`;
82 |
83 | ### 数据表和字段
84 | * 数据表和字段采用小写加下划线方式命名,并注意字段名不要以下划线开头,例如 `think_user` 表和 `user_name`字段,不建议使用驼峰和中文作为数据表字段命名。
85 |
86 |
--------------------------------------------------------------------------------
/application/.htaccess:
--------------------------------------------------------------------------------
1 | deny from all
--------------------------------------------------------------------------------
/application/command.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | return [];
--------------------------------------------------------------------------------
/application/common.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | // 应用公共文件
13 |
--------------------------------------------------------------------------------
/application/database.php:
--------------------------------------------------------------------------------
1 | 'mysql',
5 | // 服务器地址
6 | 'hostname' => '127.0.0.1',
7 | // 数据库名
8 | 'database' => 'tprestful',
9 | // 用户名
10 | 'username' => 'root',
11 | // 密码
12 | 'password' => '123456',
13 | // 端口
14 | 'hostport' => '',
15 | // 连接dsn
16 | 'dsn' => '',
17 | // 数据库连接参数
18 | 'params' => [],
19 | // 数据库编码默认采用utf8
20 | 'charset' => 'utf8',
21 | // 数据库表前缀
22 | 'prefix' => '',
23 | // 数据库调试模式
24 | 'debug' => true,
25 | // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
26 | 'deploy' => 0,
27 | // 数据库读写是否分离 主从式有效
28 | 'rw_separate' => false,
29 | // 读写分离后 主服务器数量
30 | 'master_num' => 1,
31 | // 指定从服务器序号
32 | 'slave_no' => '',
33 | // 是否严格检查字段是否存在
34 | 'fields_strict' => true,
35 | // 数据集返回类型 array 数组 collection Collection对象
36 | 'resultset_type' => 'array',
37 | // 是否自动写入时间戳字段
38 | 'auto_timestamp' => false,
39 | // 是否需要进行SQL性能分析
40 | 'sql_explain' => false,
41 | ];
42 |
--------------------------------------------------------------------------------
/application/index/controller/Index.php:
--------------------------------------------------------------------------------
1 | *{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }
:)
ThinkPHP V5
十年磨一剑 - 为API开发设计的高性能框架
[ V5.0 版本由 七牛云 独家赞助发布 ] ';
9 | }
10 | function hello(){
11 | echo 11;
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/application/index/controller/News.php:
--------------------------------------------------------------------------------
1 | method){
9 | case 'get': //查询
10 | $this->read($id);
11 | break;
12 | case 'post': //新增
13 | $this->add();
14 | break;
15 | case 'put': //修改
16 | $this->update($id);
17 | break;
18 | case 'delete': //删除
19 | $this->delete($id);
20 | break;
21 |
22 | }
23 | }
24 | public function read($id){
25 | $model = model('News');
26 | //$data = $model::get($id)->getData();
27 | //$model = new NewsModel();
28 | $data=$model->where('id', $id)->find();// 查询单个数据
29 | return json($data);
30 | }
31 |
32 | public function add(){
33 | $model = model('News');
34 | $param=Request::instance()->param();//获取当前请求的所有变量(经过过滤)
35 | if($model->save($param)){
36 | return json(["status"=>1]);
37 | }else{
38 | return json(["status"=>0]);
39 | }
40 | }
41 | public function update($id){
42 | $model = model('News');
43 | $param=Request::instance()->param();
44 | if($model->where("id",$id)->update($param)){
45 | return json(["status"=>1]);
46 | }else{
47 | return json(["status"=>0]);
48 | }
49 | }
50 | public function delete($id){
51 |
52 | $model = model('News');
53 | $rs=$model::get($id)->delete();
54 | if($rs){
55 | return json(["status"=>1]);
56 | }else{
57 | return json(["status"=>0]);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/application/index/model/News.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | return [
13 | // 生成应用公共文件
14 | '__file__' => ['common.php', 'config.php', 'database.php'],
15 |
16 | // 定义demo模块的自动生成 (按照实际定义的文件名生成)
17 | 'demo' => [
18 | '__file__' => ['common.php'],
19 | '__dir__' => ['behavior', 'controller', 'model', 'view'],
20 | 'controller' => ['Index', 'Test', 'UserType'],
21 | 'model' => ['User', 'UserType'],
22 | 'view' => ['index/index'],
23 | ],
24 | // 其他更多的模块定义
25 | ];
26 |
--------------------------------------------------------------------------------
/client/ApiClient.php:
--------------------------------------------------------------------------------
1 | requestType = strtolower($requestType);
48 | $paramUrl = '';
49 | // PATHINFO模式
50 | if (!empty($data)) {
51 | foreach ($data as $key => $value) {
52 | $paramUrl.= $key . '=' . $value.'&';
53 | }
54 | $url = $url .'?'. $paramUrl;
55 | }
56 |
57 | //初始化类中的数据
58 | $this->url = $url;
59 |
60 | $this->data = $data;
61 | try{
62 | if(!$this->curl = curl_init()){
63 | throw new Exception('curl初始化错误:');
64 | };
65 | }catch (Exception $e){
66 | echo '';
67 | print_r($e->getMessage());
68 | echo '
';
69 | }
70 |
71 | curl_setopt($this->curl, CURLOPT_URL, $this->url);
72 | curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
73 | //curl_setopt($this->curl, CURLOPT_HEADER, 1);
74 | }
75 |
76 | /**
77 | * [_post 设置get请求的参数]
78 | * @return [type] [description]
79 | */
80 | public function _get() {
81 |
82 | }
83 |
84 | /**
85 | * [_post 设置post请求的参数]
86 | * post 新增资源
87 | * @return [type] [description]
88 | */
89 | public function _post() {
90 |
91 | curl_setopt($this->curl, CURLOPT_POST, 1);
92 |
93 | curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
94 |
95 | }
96 |
97 | /**
98 | * [_put 设置put请求]
99 | * put 更新资源
100 | * @return [type] [description]
101 | */
102 | public function _put() {
103 |
104 | curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
105 | }
106 |
107 | /**
108 | * [_delete 删除资源]
109 | * delete 删除资源
110 | * @return [type] [description]
111 | */
112 | public function _delete() {
113 | curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
114 |
115 | }
116 |
117 | /**
118 | * [doRequest 执行发送请求]
119 | * @return [type] [description]
120 | */
121 | public function doRequest() {
122 | //发送给服务端验证信息
123 | if((null !== self::token) && self::token){
124 | $this->headers = array(
125 | 'Client-Token:'.self::token,//此处不能用下划线
126 | 'Client-Code:'.$this->setAuthorization()
127 | );
128 | }
129 |
130 | //发送头部信息
131 | $this->setHeader();
132 |
133 | //发送请求方式
134 | switch ($this->requestType) {
135 | case 'post':
136 | $this->_post();
137 | break;
138 |
139 | case 'put':
140 | $this->_put();
141 | break;
142 |
143 | case 'delete':
144 | $this->_delete();
145 | break;
146 |
147 | default:
148 | curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);
149 | break;
150 | }
151 | //执行curl请求
152 | $info = curl_exec($this->curl);
153 |
154 | //获取curl执行状态信息
155 | $this->status = $this->getInfo();
156 | return $info;
157 | }
158 |
159 | /**
160 | * 设置发送的头部信息
161 | */
162 | private function setHeader(){
163 | curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
164 | }
165 |
166 | /**
167 | * 生成授权码
168 | * @return string 授权码
169 | */
170 | private function setAuthorization(){
171 | $authorization = md5(substr(md5(self::token), 8, 24).self::token);
172 | return $authorization;
173 | }
174 | /**
175 | * 获取curl中的状态信息
176 | */
177 | public function getInfo(){
178 | return curl_getinfo($this->curl);
179 | }
180 |
181 | /**
182 | * 关闭curl连接
183 | */
184 | public function __destruct(){
185 | curl_close($this->curl);
186 | }
187 | }
--------------------------------------------------------------------------------
/client/client.php:
--------------------------------------------------------------------------------
1 | '房价又涨了',
6 | 'content' => '据新华社消息:上海均价环比上涨5%'
7 | );
8 | $api_url = 'http://www.tp5-restful.com/news/4';
9 | $rest = new restClient($api_url, $param, 'get');
10 | $info = $rest->doRequest();
11 | //$status = $rest->status;//获取curl中的状态信息
12 |
13 |
14 | $api_url = 'http://www.tp5-restful.com/news';
15 | $rest = new restClient($api_url, $param, 'post');
16 | $info = $rest->doRequest();
17 |
18 | $api_url = 'http://www.tp5-restful.com/news/4';
19 | $rest = new restClient($api_url, $param, 'put');
20 | $info = $rest->doRequest();
21 |
22 | echo '';
23 | print_r($info);exit;
24 |
25 | $api_url = 'http://www.tp5-restful.com/news/4';
26 | $rest = new restClient($api_url, $param, 'delete');
27 | $info = $rest->doRequest();
28 |
29 |
30 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "topthink/think",
3 | "description": "the new thinkphp framework",
4 | "type": "project",
5 | "keywords": [
6 | "framework",
7 | "thinkphp",
8 | "ORM"
9 | ],
10 | "homepage": "http://thinkphp.cn/",
11 | "license": "Apache-2.0",
12 | "authors": [
13 | {
14 | "name": "liu21st",
15 | "email": "liu21st@gmail.com"
16 | }
17 | ],
18 | "require": {
19 | "php": ">=5.4.0",
20 | "topthink/framework": "*"
21 | },
22 | "extra": {
23 | "think-path": "thinkphp"
24 | },
25 | "minimum-stability": "dev",
26 | "config": {
27 | "preferred-install": "dist"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/doc/tprestful.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phper-hard/tp5-restful/e9a7bc6635f0f3cff5a215464cf674ea1100c958/doc/tprestful.sql
--------------------------------------------------------------------------------
/doc/详细说明.doc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phper-hard/tp5-restful/e9a7bc6635f0f3cff5a215464cf674ea1100c958/doc/详细说明.doc
--------------------------------------------------------------------------------
/extend/.gitignore:
--------------------------------------------------------------------------------
1 | /composer.lock
2 | /vendor
3 | .idea
4 | .DS_Store
5 |
--------------------------------------------------------------------------------
/public/.htaccess:
--------------------------------------------------------------------------------
1 |
2 | Options +FollowSymlinks -Multiviews
3 | RewriteEngine on
4 |
5 | RewriteCond %{REQUEST_FILENAME} !-d
6 | RewriteCond %{REQUEST_FILENAME} !-f
7 | RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
8 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phper-hard/tp5-restful/e9a7bc6635f0f3cff5a215464cf674ea1100c958/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | // [ 应用入口文件 ]
13 |
14 | // 定义应用目录
15 | define('APP_PATH', __DIR__ . '/../application/');
16 | // 加载框架引导文件
17 | require __DIR__ . '/../thinkphp/start.php';
18 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
3 |
--------------------------------------------------------------------------------
/public/router.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | // $Id$
12 |
13 | if (is_file($_SERVER["DOCUMENT_ROOT"] . $_SERVER["REQUEST_URI"])) {
14 | return false;
15 | } else {
16 | require __DIR__ . "/index.php";
17 | }
18 |
--------------------------------------------------------------------------------
/public/static/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/runtime/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/think:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env php
2 |
11 | // +----------------------------------------------------------------------
12 |
13 | // 定义项目路径
14 | define('APP_PATH', './application/');
15 |
16 | // 加载框架引导文件
17 | require './thinkphp/console.php';
--------------------------------------------------------------------------------
/thinkphp/.gitignore:
--------------------------------------------------------------------------------
1 | /composer.lock
2 | /vendor
3 | .idea
4 | .DS_Store
5 |
--------------------------------------------------------------------------------
/thinkphp/.htaccess:
--------------------------------------------------------------------------------
1 | deny from all
--------------------------------------------------------------------------------
/thinkphp/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 |
3 | language: php
4 |
5 | services:
6 | - memcached
7 | - mongodb
8 | - mysql
9 | - postgresql
10 | - redis-server
11 |
12 | matrix:
13 | fast_finish: true
14 | include:
15 | - php: 5.4
16 | - php: 5.5
17 | - php: 5.6
18 | - php: 7.0
19 | - php: hhvm
20 | allow_failures:
21 | - php: hhvm
22 |
23 | cache:
24 | directories:
25 | - $HOME/.composer/cache
26 |
27 | before_install:
28 | - composer self-update
29 | - mysql -e "create database IF NOT EXISTS test;" -uroot
30 | - psql -c 'DROP DATABASE IF EXISTS test;' -U postgres
31 | - psql -c 'create database test;' -U postgres
32 |
33 | install:
34 | - ./tests/script/install.sh
35 |
36 | script:
37 | ## LINT
38 | - find . -path ./vendor -prune -o -type f -name \*.php -exec php -l {} \;
39 | ## PHP_CodeSniffer
40 | - vendor/bin/phpcs --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 --standard=PSR2 --ignore="vendor/*" ./
41 | ## PHP Copy/Paste Detector
42 | - vendor/bin/phpcpd --verbose --exclude vendor ./ || true
43 | ## PHPLOC
44 | - vendor/bin/phploc --exclude vendor ./
45 | ## PHPUNIT
46 | - vendor/bin/phpunit --coverage-clover=coverage.xml --configuration=phpunit.xml
47 |
48 | after_success:
49 | - bash <(curl -s https://codecov.io/bash)
50 |
--------------------------------------------------------------------------------
/thinkphp/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | 如何贡献我的源代码
2 | ===
3 |
4 | 此文档介绍了 ThinkPHP 团队的组成以及运转机制,您提交的代码将给 ThinkPHP 项目带来什么好处,以及如何才能加入我们的行列。
5 |
6 | ## 通过 Github 贡献代码
7 |
8 | ThinkPHP 目前使用 Git 来控制程序版本,如果你想为 ThinkPHP 贡献源代码,请先大致了解 Git 的使用方法。我们目前把项目托管在 GitHub 上,任何 GitHub 用户都可以向我们贡献代码。
9 |
10 | 参与的方式很简单,`fork`一份 ThinkPHP 的代码到你的仓库中,修改后提交,并向我们发起`pull request`申请,我们会及时对代码进行审查并处理你的申请并。审查通过后,你的代码将被`merge`进我们的仓库中,这样你就会自动出现在贡献者名单里了,非常方便。
11 |
12 | 我们希望你贡献的代码符合:
13 |
14 | * ThinkPHP 的编码规范
15 | * 适当的注释,能让其他人读懂
16 | * 遵循 Apache2 开源协议
17 |
18 | **如果想要了解更多细节或有任何疑问,请继续阅读下面的内容**
19 |
20 | ### 注意事项
21 |
22 | * 本项目代码格式化标准选用 [**PSR-2**](http://www.kancloud.cn/thinkphp/php-fig-psr/3141);
23 | * 类名和类文件名遵循 [**PSR-4**](http://www.kancloud.cn/thinkphp/php-fig-psr/3144);
24 | * 对于 Issues 的处理,请使用诸如 `fix #xxx(Issue ID)` 的 commit title 直接关闭 issue。
25 | * 系统会自动在 PHP 5.4 5.5 5.6 7.0 和 HHVM 上测试修改,其中 HHVM 下的测试容许报错,请确保你的修改符合 PHP 5.4 ~ 5.6 和 PHP 7.0 的语法规范;
26 | * 管理员不会合并造成 CI faild 的修改,若出现 CI faild 请检查自己的源代码或修改相应的[单元测试文件](thinkphp/tests);
27 |
28 | ## GitHub Issue
29 |
30 | GitHub 提供了 Issue 功能,该功能可以用于:
31 |
32 | * 提出 bug
33 | * 提出功能改进
34 | * 反馈使用体验
35 |
36 | 该功能不应该用于:
37 |
38 | * 提出修改意见(涉及代码署名和修订追溯问题)
39 | * 不友善的言论
40 |
41 | ## 快速修改
42 |
43 | **GitHub 提供了快速编辑文件的功能**
44 |
45 | 1. 登录 GitHub 帐号;
46 | 2. 浏览项目文件,找到要进行修改的文件;
47 | 3. 点击右上角铅笔图标进行修改;
48 | 4. 填写 `Commit changes` 相关内容(Title 必填);
49 | 5. 提交修改,等待 CI 验证和管理员合并。
50 |
51 | **若您需要一次提交大量修改,请继续阅读下面的内容**
52 |
53 | ## 完整流程
54 |
55 | 1. `fork`本项目;
56 | 2. 克隆(`clone`)你 `fork` 的项目到本地;
57 | 3. 新建分支(`branch`)并检出(`checkout`)新分支;
58 | 4. 添加本项目到你的本地 git 仓库作为上游(`upstream`);
59 | 5. 进行修改,若你的修改包含方法或函数的增减,请记得修改[单元测试文件](thinkphp/tests);
60 | 6. 变基(衍合 `rebase`)你的分支到上游 master 分支;
61 | 7. `push` 你的本地仓库到 GitHub;
62 | 8. 提交 `pull request`;
63 | 9. 等待 CI 验证(若不通过则重复 5~7,GitHub 会自动更新你的 `pull request`);
64 | 10. 等待管理员处理,并及时 `rebase` 你的分支到上游 master 分支(若上游 master 分支有修改)。
65 |
66 | *若有必要,可以 `git push -f` 强行推送 rebase 后的分支到自己的 GitHub `fork`*
67 |
68 | ### 注意事项
69 |
70 | * 若对上述流程有任何不清楚的地方,请查阅 GIT 教程,如 [这个](http://backlogtool.com/git-guide/cn/);
71 | * 对于代码**不同方面**的修改,请在自己 `fork` 的项目中**创建不同的分支**(原因参见`完整流程`第9条备注部分);
72 | * 变基及交互式变基操作参见 [Git 交互式变基](http://pakchoi.me/2015/03/17/git-interactive-rebase/)
73 |
74 | ## 推荐资源
75 |
76 | ### 开发环境
77 |
78 | * XAMPP for Windows 5.5.x
79 | * WampServer (for Windows)
80 | * upupw Apache PHP5.4 ( for Windows)
81 |
82 | 或自行安装
83 |
84 | - Apache / Nginx
85 | - PHP 5.4 ~ 5.6
86 | - MySQL / MariaDB
87 |
88 | *Windows 用户推荐添加 PHP bin 目录到 PATH,方便使用 composer*
89 |
90 | *Linux 用户自行配置环境, Mac 用户推荐使用内嵌 Apache 配合 Homebrew 安装 PHP 和 MariaDB*
91 |
92 | ### 编辑器
93 |
94 | Sublime Text 3 + phpfmt 插件
95 |
96 | phpfmt 插件参数
97 |
98 | ```json
99 | {
100 | "enable_auto_align": true,
101 | "indent_with_space": true,
102 | "psr1_naming": true,
103 | "psr2": true,
104 | "version": 1
105 | }
106 | ```
107 |
108 | 或其他 编辑器 / IDE 配合 PSR2 自动格式化工具
109 |
110 | ### Git GUI
111 |
112 | * SourceTree
113 | * GitHub Desktop
114 |
115 | 或其他 Git 图形界面客户端
116 |
--------------------------------------------------------------------------------
/thinkphp/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | ThinkPHP遵循Apache2开源协议发布,并提供免费使用。
3 | 版权所有Copyright © 2006-2016 by ThinkPHP (http://thinkphp.cn)
4 | All rights reserved。
5 | ThinkPHP® 商标和著作权所有者为上海顶想信息科技有限公司。
6 |
7 | Apache Licence是著名的非盈利开源组织Apache采用的协议。
8 | 该协议和BSD类似,鼓励代码共享和尊重原作者的著作权,
9 | 允许代码修改,再作为开源或商业软件发布。需要满足
10 | 的条件:
11 | 1. 需要给代码的用户一份Apache Licence ;
12 | 2. 如果你修改了代码,需要在被修改的文件中说明;
13 | 3. 在延伸的代码中(修改和有源代码衍生的代码中)需要
14 | 带有原来代码中的协议,商标,专利声明和其他原来作者规
15 | 定需要包含的说明;
16 | 4. 如果再发布的产品中包含一个Notice文件,则在Notice文
17 | 件中需要带有本协议内容。你可以在Notice中增加自己的
18 | 许可,但不可以表现为对Apache Licence构成更改。
19 | 具体的协议参考:http://www.apache.org/licenses/LICENSE-2.0
20 |
21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 | POSSIBILITY OF SUCH DAMAGE.
33 |
--------------------------------------------------------------------------------
/thinkphp/README.md:
--------------------------------------------------------------------------------
1 | ThinkPHP 5.0 RC4
2 | ===============
3 |
4 | [](https://travis-ci.org/top-think/framework)
5 | [](https://codecov.io/github/top-think/framework)
6 | [](https://github.com/top-think/framework/releases)
7 | [](https://github.com/top-think/framework/releases/latest)
8 | [](https://github.com/top-think/framework/releases/latest)
9 | [](https://packagist.org/packages/topthink/framework)
10 | [](https://packagist.org/packages/topthink/framework)
11 |
12 | ThinkPHP5在保持快速开发和大道至简的核心理念不变的同时,PHP版本要求提升到5.4,对已有的CBD模式做了更深的强化,优化核心,减少依赖,基于全新的架构思想和命名空间实现,是ThinkPHP突破原有框架思路的颠覆之作,其主要特性包括:
13 |
14 | + 基于命名空间和众多PHP新特性
15 | + 核心功能组件化
16 | + 强化路由功能
17 | + 更灵活的控制器
18 | + 重构的模型和数据库类
19 | + 配置文件可分离
20 | + 重写的自动验证和完成
21 | + 简化扩展机制
22 | + API支持完善
23 | + 改进的Log类
24 | + 命令行访问支持
25 | + REST支持
26 | + 引导文件支持
27 | + 方便的自动生成定义
28 | + 真正惰性加载
29 | + 分布式环境支持
30 | + 更多的社交类库
31 |
32 | > ThinkPHP5的运行环境要求PHP5.4以上。
33 |
34 | 详细开发文档参考 [ThinkPHP5完全开发手册](http://www.kancloud.cn/manual/thinkphp5)
35 |
36 | ## 目录结构
37 |
38 | 初始的目录结构如下:
39 |
40 | ~~~
41 | www WEB部署目录(或者子目录)
42 | ├─application 应用目录
43 | │ ├─common 公共模块目录(可以更改)
44 | │ ├─module_name 模块目录
45 | │ │ ├─config.php 模块配置文件
46 | │ │ ├─common.php 模块函数文件
47 | │ │ ├─controller 控制器目录
48 | │ │ ├─model 模型目录
49 | │ │ ├─view 视图目录
50 | │ │ └─ ... 更多类库目录
51 | │ │
52 | │ ├─command.php 命令行工具配置文件
53 | │ ├─common.php 公共函数文件
54 | │ ├─config.php 公共配置文件
55 | │ ├─route.php 路由配置文件
56 | │ └─database.php 数据库配置文件
57 | │
58 | ├─public WEB目录(对外访问目录)
59 | │ ├─index.php 入口文件
60 | │ ├─router.php 快速测试文件
61 | │ └─.htaccess 用于apache的重写
62 | │
63 | ├─thinkphp 框架系统目录
64 | │ ├─lang 语言文件目录
65 | │ ├─library 框架类库目录
66 | │ │ ├─think Think类库包目录
67 | │ │ └─traits 系统Trait目录
68 | │ │
69 | │ ├─tpl 系统模板目录
70 | │ ├─base.php 基础定义文件
71 | │ ├─console.php 控制台入口文件
72 | │ ├─convention.php 框架惯例配置文件
73 | │ ├─helper.php 助手函数文件
74 | │ ├─phpunit.xml phpunit配置文件
75 | │ └─start.php 框架入口文件
76 | │
77 | ├─extend 扩展类库目录
78 | ├─runtime 应用的运行时目录(可写,可定制)
79 | ├─vendor 第三方类库目录(Composer依赖库)
80 | ├─build.php 自动生成定义文件(参考)
81 | ├─composer.json composer 定义文件
82 | ├─LICENSE.txt 授权说明文件
83 | ├─README.md README 文件
84 | ├─think 命令行入口文件
85 | ~~~
86 |
87 | > router.php用于php自带webserver支持,可用于快速测试
88 | > 切换到public目录后,启动命令:php -S localhost:8888 router.php
89 | > 上面的目录结构和名称是可以改变的,这取决于你的入口文件和配置参数。
90 |
91 | ## 命名规范
92 |
93 | ThinkPHP5的命名规范遵循PSR-2规范以及PSR-4自动加载规范。
94 |
95 | ## 参与开发
96 | 注册并登录 Github 帐号, fork 本项目并进行改动。
97 |
98 | 更多细节参阅 [CONTRIBUTING.md](CONTRIBUTING.md)
99 |
100 | ## 版权信息
101 |
102 | ThinkPHP遵循Apache2开源协议发布,并提供免费使用。
103 |
104 | 本项目包含的第三方源码和二进制文件之版权信息另行标注。
105 |
106 | 版权所有Copyright © 2006-2016 by ThinkPHP (http://thinkphp.cn)
107 |
108 | All rights reserved。
109 |
110 | ThinkPHP® 商标和著作权所有者为上海顶想信息科技有限公司。
111 |
112 | 更多细节参阅 [LICENSE.txt](LICENSE.txt)
113 |
--------------------------------------------------------------------------------
/thinkphp/base.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | define('THINK_VERSION', '5.0.0 RC4');
13 | define('THINK_START_TIME', microtime(true));
14 | define('THINK_START_MEM', memory_get_usage());
15 | define('EXT', '.php');
16 | define('DS', DIRECTORY_SEPARATOR);
17 | defined('THINK_PATH') or define('THINK_PATH', __DIR__ . DS);
18 | define('LIB_PATH', THINK_PATH . 'library' . DS);
19 | define('CORE_PATH', LIB_PATH . 'think' . DS);
20 | define('TRAIT_PATH', LIB_PATH . 'traits' . DS);
21 | defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . DS);
22 | defined('ROOT_PATH') or define('ROOT_PATH', dirname(APP_PATH) . DS);
23 | defined('EXTEND_PATH') or define('EXTEND_PATH', ROOT_PATH . 'extend' . DS);
24 | defined('VENDOR_PATH') or define('VENDOR_PATH', ROOT_PATH . 'vendor' . DS);
25 | defined('RUNTIME_PATH') or define('RUNTIME_PATH', ROOT_PATH . 'runtime' . DS);
26 | defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH . 'log' . DS);
27 | defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH . 'cache' . DS);
28 | defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH . 'temp' . DS);
29 | defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录
30 | defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀
31 | defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀
32 |
33 | // 环境常量
34 | define('IS_CLI', PHP_SAPI == 'cli' ? true : false);
35 | define('IS_WIN', strpos(PHP_OS, 'WIN') !== false);
36 |
37 | // 载入Loader类
38 | require CORE_PATH . 'Loader.php';
39 |
40 | // 加载环境变量配置文件
41 | if (is_file(ROOT_PATH . 'env' . EXT)) {
42 | $env = include ROOT_PATH . 'env' . EXT;
43 | foreach ($env as $key => $val) {
44 | $name = ENV_PREFIX . strtoupper($key);
45 | if (is_bool($val)) {
46 | $val = $val ? 1 : 0;
47 | } elseif (!is_scalar($val)) {
48 | continue;
49 | }
50 | putenv("$name=$val");
51 | }
52 | }
53 |
54 | // 注册自动加载
55 | \think\Loader::register();
56 |
57 | // 注册错误和异常处理机制
58 | \think\Error::register();
59 |
60 | // 加载惯例配置文件
61 | \think\Config::set(include THINK_PATH . 'convention' . EXT);
62 |
--------------------------------------------------------------------------------
/thinkphp/codecov.yml:
--------------------------------------------------------------------------------
1 | comment:
2 | layout: header, changes, diff
3 | coverage:
4 | ignore:
5 | - base.php
6 | - helper.php
7 | - convention.php
8 | - lang/zh-cn.php
9 | - start.php
10 | - console.php
11 | status:
12 | patch: false
13 |
--------------------------------------------------------------------------------
/thinkphp/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "topthink/framework",
3 | "description": "the new thinkphp framework",
4 | "type": "think-framework",
5 | "keywords": [
6 | "framework",
7 | "thinkphp",
8 | "ORM"
9 | ],
10 | "homepage": "http://thinkphp.cn/",
11 | "license": "Apache-2.0",
12 | "authors": [
13 | {
14 | "name": "liu21st",
15 | "email": "liu21st@gmail.com"
16 | }
17 | ],
18 | "require": {
19 | "php": ">=5.4.0",
20 | "topthink/think-installer": "~1.0"
21 | },
22 | "require-dev": {
23 | "phpunit/phpunit": "4.8.*",
24 | "johnkary/phpunit-speedtrap": "^1.0",
25 | "mikey179/vfsStream": "~1.6",
26 | "phploc/phploc": "2.*",
27 | "sebastian/phpcpd": "2.*",
28 | "squizlabs/php_codesniffer": "2.*",
29 | "phpdocumentor/reflection-docblock": "^2.0"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/thinkphp/console.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think;
13 |
14 | // ThinkPHP 引导文件
15 | // 加载基础文件
16 | require __DIR__ . '/base.php';
17 |
18 | // 执行应用
19 | App::initCommon();
20 | Console::init();
--------------------------------------------------------------------------------
/thinkphp/lang/zh-cn.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | // 核心中文语言包
13 | return [
14 | // 系统错误提示
15 | 'Undefined variable' => '未定义变量',
16 | 'Undefined index' => '未定义索引',
17 | 'Parse error' => '语法解析错误',
18 | 'Type error' => '类型错误',
19 | 'Fatal error' => '致命错误',
20 | 'syntax error' => '语法错误',
21 |
22 | // 框架核心错误提示
23 | 'dispatch type not support' => '不支持的调度类型',
24 | 'method param miss' => '方法参数错误',
25 | 'method not exists' => '方法不存在',
26 | 'module not exists' => '模块不存在',
27 | 'controller not exists' => '控制器不存在',
28 | 'class not exists' => '类不存在',
29 | 'property not exists' => '类的属性不存在',
30 | 'template not exists' => '模板文件不存在',
31 | 'illegal controller name' => '非法的控制器名称',
32 | 'illegal action name' => '非法的操作名称',
33 | 'url suffix deny' => '禁止的URL后缀访问',
34 | 'Route Not Found' => '当前访问路由未定义',
35 | 'Underfined db type' => '未定义数据库类型',
36 | 'variable type error' => '变量类型错误',
37 | 'PSR-4 error' => 'PSR-4 规范错误',
38 | 'not support total' => '简洁模式下不能获取数据总数',
39 | 'not support last' => '简洁模式下不能获取最后一页',
40 | 'error session handler' => '错误的SESSION处理器类',
41 | 'not allow php tag' => '模板不允许使用PHP语法',
42 | 'not support' => '不支持',
43 | 'redisd master' => 'Redisd 主服务器错误',
44 | 'redisd slave' => 'Redisd 从服务器错误',
45 | 'must run at sae' => '必须在SAE运行',
46 | 'memcache init error' => '未开通Memcache服务,请在SAE管理平台初始化Memcache服务',
47 | 'KVDB init error' => '没有初始化KVDB,请在SAE管理平台初始化KVDB服务',
48 | 'fields not exists' => '数据表字段不存在',
49 | 'where express error' => '查询表达式错误',
50 | 'no data to update' => '没有任何数据需要更新',
51 | 'miss data to insert' => '缺少需要写入的数据',
52 | 'miss complex primary data' => '缺少复合主键数据',
53 | 'miss update condition' => '缺少更新条件',
54 | 'model data Not Found' => '模型数据不存在',
55 | 'table data not Found' => '表数据不存在',
56 | 'delete without condition' => '没有条件不会执行删除操作',
57 | 'miss relation data' => '缺少关联表数据',
58 | 'tag attr must' => '模板标签属性必须',
59 | 'tag error' => '模板标签错误',
60 | 'cache write error' => '缓存写入失败',
61 | 'sae mc write error' => 'SAE mc 写入错误',
62 | 'route name not exists' => '路由标识不存在(或参数不够)',
63 | ];
64 |
--------------------------------------------------------------------------------
/thinkphp/library/think/Error.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think;
13 |
14 | use think\console\Output as ConsoleOutput;
15 | use think\exception\ErrorException;
16 | use think\exception\Handle;
17 | use think\exception\ThrowableError;
18 |
19 | class Error
20 | {
21 | /**
22 | * 注册异常处理
23 | * @return void
24 | */
25 | public static function register()
26 | {
27 | error_reporting(E_ALL);
28 | set_error_handler([__CLASS__, 'appError']);
29 | set_exception_handler([__CLASS__, 'appException']);
30 | register_shutdown_function([__CLASS__, 'appShutdown']);
31 | }
32 |
33 | /**
34 | * Exception Handler
35 | * @param \Exception|\Throwable $e
36 | */
37 | public static function appException($e)
38 | {
39 | if (!$e instanceof \Exception) {
40 | $e = new ThrowableError($e);
41 | }
42 |
43 | self::getExceptionHandler()->report($e);
44 | if (IS_CLI) {
45 | self::getExceptionHandler()->renderForConsole(new ConsoleOutput, $e);
46 | } else {
47 | self::getExceptionHandler()->render($e)->send();
48 | }
49 | }
50 |
51 | /**
52 | * Error Handler
53 | * @param integer $errno 错误编号
54 | * @param integer $errstr 详细错误信息
55 | * @param string $errfile 出错的文件
56 | * @param integer $errline 出错行号
57 | * @param array $errcontext
58 | * @throws ErrorException
59 | */
60 | public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = [])
61 | {
62 | $exception = new ErrorException($errno, $errstr, $errfile, $errline, $errcontext);
63 | if (error_reporting() & $errno) {
64 | // 将错误信息托管至 think\exception\ErrorException
65 | throw $exception;
66 | } else {
67 | self::getExceptionHandler()->report($exception);
68 | }
69 | }
70 |
71 | /**
72 | * Shutdown Handler
73 | */
74 | public static function appShutdown()
75 | {
76 | if (!is_null($error = error_get_last()) && self::isFatal($error['type'])) {
77 | // 将错误信息托管至think\ErrorException
78 | $exception = new ErrorException($error['type'], $error['message'], $error['file'], $error['line']);
79 |
80 | self::appException($exception);
81 | }
82 |
83 | // 写入日志
84 | Log::save();
85 | }
86 |
87 | /**
88 | * 确定错误类型是否致命
89 | *
90 | * @param int $type
91 | * @return bool
92 | */
93 | protected static function isFatal($type)
94 | {
95 | return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]);
96 | }
97 |
98 | /**
99 | * Get an instance of the exception handler.
100 | *
101 | * @return Handle
102 | */
103 | public static function getExceptionHandler()
104 | {
105 | static $handle;
106 | if (!$handle) {
107 | // 异常处理handle
108 | $class = Config::get('exception_handle');
109 | if ($class && class_exists($class) && is_subclass_of($class, "\\think\\exception\\Handle")) {
110 | $handle = new $class;
111 | } else {
112 | $handle = new Handle;
113 | }
114 | }
115 | return $handle;
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/thinkphp/library/think/Exception.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think;
13 |
14 | class Exception extends \Exception
15 | {
16 |
17 | /**
18 | * 保存异常页面显示的额外Debug数据
19 | * @var array
20 | */
21 | protected $data = [];
22 |
23 | /**
24 | * 设置异常额外的Debug数据
25 | * 数据将会显示为下面的格式
26 | *
27 | * Exception Data
28 | * --------------------------------------------------
29 | * Label 1
30 | * key1 value1
31 | * key2 value2
32 | * Label 2
33 | * key1 value1
34 | * key2 value2
35 | *
36 | * @param string $label 数据分类,用于异常页面显示
37 | * @param array $data 需要显示的数据,必须为关联数组
38 | */
39 | final protected function setData($label, array $data)
40 | {
41 | $this->data[$label] = $data;
42 | }
43 |
44 | /**
45 | * 获取异常额外Debug数据
46 | * 主要用于输出到异常页面便于调试
47 | * @return array 由setData设置的Debug数据
48 | */
49 | final public function getData()
50 | {
51 | return $this->data;
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/thinkphp/library/think/cache/Driver.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\cache;
13 |
14 | /**
15 | * 缓存基础类
16 | */
17 | abstract class Driver
18 | {
19 | protected $options = [];
20 | protected $tag;
21 |
22 | /**
23 | * 判断缓存是否存在
24 | * @access public
25 | * @param string $name 缓存变量名
26 | * @return bool
27 | */
28 | abstract public function has($name);
29 |
30 | /**
31 | * 读取缓存
32 | * @access public
33 | * @param string $name 缓存变量名
34 | * @param mixed $default 默认值
35 | * @return mixed
36 | */
37 | abstract public function get($name, $default = false);
38 |
39 | /**
40 | * 写入缓存
41 | * @access public
42 | * @param string $name 缓存变量名
43 | * @param mixed $value 存储数据
44 | * @param int $expire 有效时间 0为永久
45 | * @return boolean
46 | */
47 | abstract public function set($name, $value, $expire = null);
48 |
49 | /**
50 | * 自增缓存(针对数值缓存)
51 | * @access public
52 | * @param string $name 缓存变量名
53 | * @param int $step 步长
54 | * @return false|int
55 | */
56 | abstract public function inc($name, $step = 1);
57 |
58 | /**
59 | * 自减缓存(针对数值缓存)
60 | * @access public
61 | * @param string $name 缓存变量名
62 | * @param int $step 步长
63 | * @return false|int
64 | */
65 | abstract public function dec($name, $step = 1);
66 |
67 | /**
68 | * 删除缓存
69 | * @access public
70 | * @param string $name 缓存变量名
71 | * @return boolean
72 | */
73 | abstract public function rm($name);
74 |
75 | /**
76 | * 清除缓存
77 | * @access public
78 | * @param string $tag 标签名
79 | * @return boolean
80 | */
81 | abstract public function clear($tag = null);
82 |
83 | /**
84 | * 获取实际的缓存标识
85 | * @access public
86 | * @param string $name 缓存名
87 | * @return string
88 | */
89 | protected function getCacheKey($name)
90 | {
91 | return $this->options['prefix'] . $name;
92 | }
93 |
94 | /**
95 | * 缓存标签
96 | * @access public
97 | * @param string $name 标签名
98 | * @param string|array $keys 缓存标识
99 | * @param bool $overlay 是否覆盖
100 | * @return $this
101 | */
102 | public function tag($name, $keys = null, $overlay = false)
103 | {
104 | if (is_null($keys)) {
105 | $this->tag = $name;
106 | } else {
107 | $key = 'tag_' . md5($name);
108 | if (is_string($keys)) {
109 | $keys = explode(',', $keys);
110 | }
111 | $keys = array_map([$this, 'getCacheKey'], $keys);
112 | if ($overlay) {
113 | $value = $keys;
114 | } else {
115 | $value = array_unique(array_merge($this->getTagItem($name), $keys));
116 | }
117 | $this->set($key, implode(',', $value));
118 | }
119 | return $this;
120 | }
121 |
122 | /**
123 | * 更新标签
124 | * @access public
125 | * @param string $name 缓存标识
126 | * @return void
127 | */
128 | protected function setTagItem($name)
129 | {
130 | if ($this->tag) {
131 | $key = 'tag_' . md5($this->tag);
132 | $this->tag = null;
133 | if ($this->has($key)) {
134 | $value = $this->get($key);
135 | $value .= ',' . $name;
136 | } else {
137 | $value = $name;
138 | }
139 | $this->set($key, $value);
140 | }
141 | }
142 |
143 | /**
144 | * 获取标签包含的缓存标识
145 | * @access public
146 | * @param string $tag 缓存标签
147 | * @return array
148 | */
149 | protected function getTagItem($tag)
150 | {
151 | $key = 'tag_' . md5($tag);
152 | $value = $this->get($key);
153 | if ($value) {
154 | return explode(',', $value);
155 | } else {
156 | return [];
157 | }
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/thinkphp/library/think/cache/driver/Wincache.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\cache\driver;
13 |
14 | use think\cache\Driver;
15 | use think\Exception;
16 |
17 | /**
18 | * Wincache缓存驱动
19 | * @author liu21st
20 | */
21 | class Wincache extends Driver
22 | {
23 | protected $options = [
24 | 'prefix' => '',
25 | 'expire' => 0,
26 | ];
27 |
28 | protected $tag;
29 |
30 | /**
31 | * 架构函数
32 | * @param array $options 缓存参数
33 | * @throws Exception
34 | * @access public
35 | */
36 | public function __construct($options = [])
37 | {
38 | if (!function_exists('wincache_ucache_info')) {
39 | throw new \BadFunctionCallException('not support: WinCache');
40 | }
41 | if (!empty($options)) {
42 | $this->options = array_merge($this->options, $options);
43 | }
44 | }
45 |
46 | /**
47 | * 判断缓存
48 | * @access public
49 | * @param string $name 缓存变量名
50 | * @return bool
51 | */
52 | public function has($name)
53 | {
54 | $key = $this->getCacheKey($name);
55 | return wincache_ucache_exists($key);
56 | }
57 |
58 | /**
59 | * 读取缓存
60 | * @access public
61 | * @param string $name 缓存变量名
62 | * @param mixed $default 默认值
63 | * @return mixed
64 | */
65 | public function get($name, $default = false)
66 | {
67 | $key = $this->getCacheKey($name);
68 | return wincache_ucache_exists($key) ? wincache_ucache_get($key) : $default;
69 | }
70 |
71 | /**
72 | * 写入缓存
73 | * @access public
74 | * @param string $name 缓存变量名
75 | * @param mixed $value 存储数据
76 | * @param integer $expire 有效时间(秒)
77 | * @return boolean
78 | */
79 | public function set($name, $value, $expire = null)
80 | {
81 | if (is_null($expire)) {
82 | $expire = $this->options['expire'];
83 | }
84 | $key = $this->getCacheKey($name);
85 | if ($this->tag && !$this->has($name)) {
86 | $first = true;
87 | }
88 | if (wincache_ucache_set($key, $value, $expire)) {
89 | isset($first) && $this->setTagItem($key);
90 | return true;
91 | }
92 | return false;
93 | }
94 |
95 | /**
96 | * 自增缓存(针对数值缓存)
97 | * @access public
98 | * @param string $name 缓存变量名
99 | * @param int $step 步长
100 | * @return false|int
101 | */
102 | public function inc($name, $step = 1)
103 | {
104 | $key = $this->getCacheKey($name);
105 | return wincache_ucache_inc($key, $step);
106 | }
107 |
108 | /**
109 | * 自减缓存(针对数值缓存)
110 | * @access public
111 | * @param string $name 缓存变量名
112 | * @param int $step 步长
113 | * @return false|int
114 | */
115 | public function dec($name, $step = 1)
116 | {
117 | $key = $this->getCacheKey($name);
118 | return wincache_ucache_dec($key, $step);
119 | }
120 |
121 | /**
122 | * 删除缓存
123 | * @access public
124 | * @param string $name 缓存变量名
125 | * @return boolean
126 | */
127 | public function rm($name)
128 | {
129 | return wincache_ucache_delete($this->getCacheKey($name));
130 | }
131 |
132 | /**
133 | * 清除缓存
134 | * @access public
135 | * @param string $tag 标签名
136 | * @return boolean
137 | */
138 | public function clear($tag = null)
139 | {
140 | if ($tag) {
141 | $keys = $this->getTagItem($tag);
142 | foreach ($keys as $key) {
143 | wincache_ucache_delete($key);
144 | }
145 | $this->rm('tag_' . md5($tag));
146 | return true;
147 | } else {
148 | return wincache_ucache_clear();
149 | }
150 | }
151 |
152 | }
153 |
--------------------------------------------------------------------------------
/thinkphp/library/think/cache/driver/Xcache.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\cache\driver;
13 |
14 | use think\cache\Driver;
15 | use think\Exception;
16 |
17 | /**
18 | * Xcache缓存驱动
19 | * @author liu21st
20 | */
21 | class Xcache extends Driver
22 | {
23 | protected $options = [
24 | 'prefix' => '',
25 | 'expire' => 0,
26 | ];
27 |
28 | /**
29 | * 架构函数
30 | * @param array $options 缓存参数
31 | * @access public
32 | * @throws \BadFunctionCallException
33 | */
34 | public function __construct($options = [])
35 | {
36 | if (!function_exists('xcache_info')) {
37 | throw new \BadFunctionCallException('not support: Xcache');
38 | }
39 | if (!empty($options)) {
40 | $this->options = array_merge($this->options, $options);
41 | }
42 | }
43 |
44 | /**
45 | * 判断缓存
46 | * @access public
47 | * @param string $name 缓存变量名
48 | * @return bool
49 | */
50 | public function has($name)
51 | {
52 | $key = $this->getCacheKey($name);
53 | return xcache_isset($key);
54 | }
55 |
56 | /**
57 | * 读取缓存
58 | * @access public
59 | * @param string $name 缓存变量名
60 | * @param mixed $default 默认值
61 | * @return mixed
62 | */
63 | public function get($name, $default = false)
64 | {
65 | $key = $this->getCacheKey($name);
66 | return xcache_isset($key) ? xcache_get($key) : $default;
67 | }
68 |
69 | /**
70 | * 写入缓存
71 | * @access public
72 | * @param string $name 缓存变量名
73 | * @param mixed $value 存储数据
74 | * @param integer $expire 有效时间(秒)
75 | * @return boolean
76 | */
77 | public function set($name, $value, $expire = null)
78 | {
79 | if (is_null($expire)) {
80 | $expire = $this->options['expire'];
81 | }
82 | if ($this->tag && !$this->has($name)) {
83 | $first = true;
84 | }
85 | $key = $this->getCacheKey($name);
86 | if (xcache_set($key, $value, $expire)) {
87 | isset($first) && $this->setTagItem($key);
88 | return true;
89 | }
90 | return false;
91 | }
92 |
93 | /**
94 | * 自增缓存(针对数值缓存)
95 | * @access public
96 | * @param string $name 缓存变量名
97 | * @param int $step 步长
98 | * @return false|int
99 | */
100 | public function inc($name, $step = 1)
101 | {
102 | $key = $this->getCacheKey($name);
103 | return xcache_inc($key, $step);
104 | }
105 |
106 | /**
107 | * 自减缓存(针对数值缓存)
108 | * @access public
109 | * @param string $name 缓存变量名
110 | * @param int $step 步长
111 | * @return false|int
112 | */
113 | public function dec($name, $step = 1)
114 | {
115 | $key = $this->getCacheKey($name);
116 | return xcache_dec($key, $step);
117 | }
118 |
119 | /**
120 | * 删除缓存
121 | * @access public
122 | * @param string $name 缓存变量名
123 | * @return boolean
124 | */
125 | public function rm($name)
126 | {
127 | return xcache_unset($this->getCacheKey($name));
128 | }
129 |
130 | /**
131 | * 清除缓存
132 | * @access public
133 | * @param string $tag 标签名
134 | * @return boolean
135 | */
136 | public function clear($tag = null)
137 | {
138 | if ($tag) {
139 | // 指定标签清除
140 | $keys = $this->getTagItem($tag);
141 | foreach ($keys as $key) {
142 | xcache_unset($key);
143 | }
144 | $this->rm('tag_' . md5($tag));
145 | return true;
146 | }
147 | if (function_exists('xcache_unset_by_prefix')) {
148 | return xcache_unset_by_prefix($this->options['prefix']);
149 | } else {
150 | return false;
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/thinkphp/library/think/config/driver/Ini.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\config\driver;
13 |
14 | class Ini
15 | {
16 | public function parse($config)
17 | {
18 | if (is_file($config)) {
19 | return parse_ini_file($config, true);
20 | } else {
21 | return parse_ini_string($config, true);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/thinkphp/library/think/config/driver/Json.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\config\driver;
13 |
14 | class Json
15 | {
16 | public function parse($config)
17 | {
18 | if (is_file($config)) {
19 | $config = file_get_contents($config);
20 | }
21 | $result = json_decode($config, true);
22 | return $result;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/thinkphp/library/think/config/driver/Xml.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\config\driver;
13 |
14 | class Xml
15 | {
16 | public function parse($config)
17 | {
18 | if (is_file($config)) {
19 | $content = simplexml_load_file($config);
20 | } else {
21 | $content = simplexml_load_string($config);
22 | }
23 | $result = (array) $content;
24 | foreach ($result as $key => $val) {
25 | if (is_object($val)) {
26 | $result[$key] = (array) $val;
27 | }
28 | }
29 | return $result;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2004-2016 Fabien Potencier
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is furnished
8 | to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
--------------------------------------------------------------------------------
/thinkphp/library/think/console/bin/README.md:
--------------------------------------------------------------------------------
1 | console 工具使用 hiddeninput.exe 在 windows 上隐藏密码输入,该二进制文件由第三方提供,相关源码和其他细节可以在 [Hidden Input](https://github.com/Seldaek/hidden-input) 找到。
2 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/Build.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command;
13 |
14 | use think\console\Command;
15 | use think\console\Input;
16 | use think\console\input\Option;
17 | use think\console\Output;
18 |
19 | class Build extends Command
20 | {
21 |
22 | /**
23 | * {@inheritdoc}
24 | */
25 | protected function configure()
26 | {
27 | $this->setName('build')
28 | ->setDefinition([
29 | new Option('config', null, Option::VALUE_OPTIONAL, "build.php path"),
30 | new Option('module', null, Option::VALUE_OPTIONAL, "module name"),
31 | ])
32 | ->setDescription('Build Application Dirs');
33 | }
34 |
35 | protected function execute(Input $input, Output $output)
36 | {
37 | if ($input->hasOption('module')) {
38 | \think\Build::module($input->getOption('module'));
39 | $output->writeln("Successed");
40 | return;
41 | }
42 |
43 | if ($input->hasOption('config')) {
44 | $build = include $input->getOption('config');
45 | } else {
46 | $build = include APP_PATH . 'build.php';
47 | }
48 | if (empty($build)) {
49 | $output->writeln("Build Config Is Empty");
50 | return;
51 | }
52 | \think\Build::run($build);
53 | $output->writeln("Successed");
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/Clear.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | namespace think\console\command;
12 |
13 | use think\console\Command;
14 | use think\console\Input;
15 | use think\console\input\Option;
16 | use think\console\Output;
17 |
18 | class Clear extends Command
19 | {
20 | protected function configure()
21 | {
22 | // 指令配置
23 | $this
24 | ->setName('clear')
25 | ->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to clear', null)
26 | ->setDescription('Clear runtime file');
27 | }
28 |
29 | protected function execute(Input $input, Output $output)
30 | {
31 | $path = $input->getOption('path') ?: RUNTIME_PATH;
32 | $files = scandir($path);
33 | if ($files) {
34 | foreach ($files as $file) {
35 | if ('.' != $file && '..' != $file && is_dir($path . $file)) {
36 | array_map('unlink', glob($path . $file . '/*.*'));
37 | } elseif (is_file($path . $file)) {
38 | unlink($path . $file);
39 | }
40 | }
41 | }
42 | $output->writeln("Clear Successed");
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/Help.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command;
13 |
14 | use think\console\Command;
15 | use think\console\Input;
16 | use think\console\input\Argument as InputArgument;
17 | use think\console\input\Option as InputOption;
18 | use think\console\Output;
19 | use think\console\helper\Descriptor as DescriptorHelper;
20 |
21 | class Help extends Command
22 | {
23 |
24 | private $command;
25 |
26 | /**
27 | * {@inheritdoc}
28 | */
29 | protected function configure()
30 | {
31 | $this->ignoreValidationErrors();
32 |
33 | $this->setName('help')->setDefinition([
34 | new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'),
35 | new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
36 | ])->setDescription('Displays help for a command')->setHelp(<<%command.name% command displays help for a given command:
38 |
39 | php %command.full_name% list
40 |
41 | To display the list of available commands, please use the list command.
42 | EOF
43 | );
44 | }
45 |
46 | /**
47 | * Sets the command.
48 | * @param Command $command The command to set
49 | */
50 | public function setCommand(Command $command)
51 | {
52 | $this->command = $command;
53 | }
54 |
55 | /**
56 | * {@inheritdoc}
57 | */
58 | protected function execute(Input $input, Output $output)
59 | {
60 | if (null === $this->command) {
61 | $this->command = $this->getConsole()->find($input->getArgument('command_name'));
62 | }
63 |
64 | $output->describe($this->command, [
65 | 'raw_text' => $input->getOption('raw'),
66 | ]);
67 |
68 | $this->command = null;
69 | }
70 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/Lists.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command;
13 |
14 | use think\console\Command;
15 | use think\console\Input;
16 | use think\console\Output;
17 | use think\console\input\Argument as InputArgument;
18 | use think\console\input\Option as InputOption;
19 | use think\console\input\Definition as InputDefinition;
20 |
21 | class Lists extends Command
22 | {
23 |
24 | /**
25 | * {@inheritdoc}
26 | */
27 | protected function configure()
28 | {
29 | $this->setName('list')->setDefinition($this->createDefinition())->setDescription('Lists commands')->setHelp(<<%command.name% command lists all commands:
31 |
32 | php %command.full_name%
33 |
34 | You can also display the commands for a specific namespace:
35 |
36 | php %command.full_name% test
37 |
38 | It's also possible to get raw list of commands (useful for embedding command runner):
39 |
40 | php %command.full_name% --raw
41 | EOF
42 | );
43 | }
44 |
45 | /**
46 | * {@inheritdoc}
47 | */
48 | public function getNativeDefinition()
49 | {
50 | return $this->createDefinition();
51 | }
52 |
53 | /**
54 | * {@inheritdoc}
55 | */
56 | protected function execute(Input $input, Output $output)
57 | {
58 | $output->describe($this->getConsole(), [
59 | 'raw_text' => $input->getOption('raw'),
60 | 'namespace' => $input->getArgument('namespace'),
61 | ]);
62 | }
63 |
64 | /**
65 | * {@inheritdoc}
66 | */
67 | private function createDefinition()
68 | {
69 | return new InputDefinition([
70 | new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
71 | new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list')
72 | ]);
73 | }
74 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/Make.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command;
13 |
14 | use think\Config;
15 | use think\console\Command;
16 | use think\console\Input;
17 | use think\console\input\Argument;
18 | use think\console\Output;
19 |
20 | abstract class Make extends Command
21 | {
22 |
23 | protected $type;
24 |
25 | abstract protected function getStub();
26 |
27 | protected function configure()
28 | {
29 | $this->addArgument('name', Argument::REQUIRED, "The name of the class");
30 | }
31 |
32 | protected function execute(Input $input, Output $output)
33 | {
34 |
35 | $name = trim($input->getArgument('name'));
36 |
37 | $classname = $this->getClassName($name);
38 |
39 | $pathname = $this->getPathName($classname);
40 |
41 | if (is_file($pathname)) {
42 | $output->writeln('' . $this->type . ' already exists!');
43 | return false;
44 | }
45 |
46 | if (!is_dir(dirname($pathname))) {
47 | mkdir(strtolower(dirname($pathname)), 0755, true);
48 | }
49 |
50 | file_put_contents($pathname, $this->buildClass($classname));
51 |
52 | $output->writeln('' . $this->type . ' created successfully.');
53 |
54 | }
55 |
56 | protected function buildClass($name)
57 | {
58 | $stub = file_get_contents($this->getStub());
59 |
60 | $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
61 |
62 | $class = str_replace($namespace . '\\', '', $name);
63 |
64 | return str_replace(['{%className%}', '{%namespace%}', '{%app_namespace%}'], [
65 | $class,
66 | $namespace,
67 | Config::get('app_namespace')
68 | ], $stub);
69 |
70 | }
71 |
72 | protected function getPathName($name)
73 | {
74 | $name = str_replace(Config::get('app_namespace') . '\\', '', $name);
75 |
76 | return APP_PATH . str_replace('\\', '/', $name) . '.php';
77 | }
78 |
79 | protected function getClassName($name)
80 | {
81 | $appNamespace = Config::get('app_namespace');
82 |
83 | if (strpos($name, $appNamespace . '\\') === 0) {
84 | return $name;
85 | }
86 |
87 | if (Config::get('app_multi_module')) {
88 | if (strpos($name, '/')) {
89 | list($module, $name) = explode('/', $name, 2);
90 | } else {
91 | $module = 'common';
92 | }
93 | } else {
94 | $module = null;
95 | }
96 |
97 | if (strpos($name, '/') !== false) {
98 | $name = str_replace('/', '\\', $name);
99 | }
100 |
101 | return $this->getNamespace($appNamespace, $module) . '\\' . $name;
102 | }
103 |
104 | protected function getNamespace($appNamespace, $module)
105 | {
106 | return $module ? ($appNamespace . '\\' . $module) : $appNamespace;
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/make/Controller.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command\make;
13 |
14 | use think\Config;
15 | use think\console\command\Make;
16 | use think\console\input\Option;
17 |
18 | class Controller extends Make
19 | {
20 |
21 | protected $type = "Controller";
22 |
23 | protected function configure()
24 | {
25 | parent::configure();
26 | $this->setName('make:controller')
27 | ->addOption('plain', null, Option::VALUE_NONE, 'Generate an empty controller class.')
28 | ->setDescription('Create a new resource controller class');
29 | }
30 |
31 | protected function getStub()
32 | {
33 | if ($this->input->getOption('plain')) {
34 | return __DIR__ . '/stubs/controller.plain.stub';
35 | }
36 |
37 | return __DIR__ . '/stubs/controller.stub';
38 | }
39 |
40 | protected function getClassName($name)
41 | {
42 | return parent::getClassName($name) . (Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '');
43 | }
44 |
45 | protected function getNamespace($appNamespace, $module)
46 | {
47 | return parent::getNamespace($appNamespace, $module) . '\controller';
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/make/Model.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\command\make;
13 |
14 | use think\console\command\Make;
15 |
16 | class Model extends Make
17 | {
18 | protected $type = "Model";
19 |
20 | protected function configure()
21 | {
22 | parent::configure();
23 | $this->setName('make:model')
24 | ->setDescription('Create a new model class');
25 | }
26 |
27 | protected function getStub()
28 | {
29 | return __DIR__ . '/stubs/model.stub';
30 | }
31 |
32 | protected function getNamespace($appNamespace, $module)
33 | {
34 | return parent::getNamespace($appNamespace, $module) . '\model';
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/make/stubs/controller.plain.stub:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | namespace think\console\command\optimize;
12 |
13 | use think\console\Command;
14 | use think\console\Input;
15 | use think\console\input\Option;
16 | use think\console\Output;
17 |
18 | class Config extends Command
19 | {
20 | /** @var Output */
21 | protected $output;
22 |
23 | protected function configure()
24 | {
25 | $this->setName('optimize:config')
26 | ->addOption('module', null, Option::VALUE_REQUIRED, 'Build module config cache .')
27 | ->setDescription('Build config and common file cache.');
28 | }
29 |
30 | protected function execute(Input $input, Output $output)
31 | {
32 | if ($input->hasOption('module')) {
33 | $module = $input->getOption('module') . DS;
34 | } else {
35 | $module = '';
36 | }
37 |
38 | $content = 'buildCacheContent($module);
39 |
40 | if (!is_dir(RUNTIME_PATH . $module)) {
41 | @mkdir(RUNTIME_PATH . $module, 0755, true);
42 | }
43 |
44 | file_put_contents(RUNTIME_PATH . $module . 'init' . EXT, $content);
45 |
46 | $output->writeln('Succeed!');
47 | }
48 |
49 | protected function buildCacheContent($module)
50 | {
51 | $content = '';
52 | $path = realpath(APP_PATH . $module) . DS;
53 | // 加载模块配置
54 | $config = \think\Config::load(CONF_PATH . $module . 'config' . CONF_EXT);
55 |
56 | // 加载应用状态配置
57 | if ($module && $config['app_status']) {
58 | $config = \think\Config::load(CONF_PATH . $module . $config['app_status'] . CONF_EXT);
59 | }
60 |
61 | // 读取扩展配置文件
62 | if ($module && $config['extra_config_list']) {
63 | foreach ($config['extra_config_list'] as $name => $file) {
64 | $filename = CONF_PATH . $module . $file . CONF_EXT;
65 | \think\Config::load($filename, is_string($name) ? $name : pathinfo($filename, PATHINFO_FILENAME));
66 | }
67 | }
68 |
69 | // 加载别名文件
70 | if (is_file(CONF_PATH . $module . 'alias' . EXT)) {
71 | $content .= '\think\Loader::addClassMap(' . (var_export(include CONF_PATH . $module . 'alias' . EXT, true)) . ');' . PHP_EOL;
72 | }
73 |
74 | // 加载行为扩展文件
75 | if (is_file(CONF_PATH . $module . 'tags' . EXT)) {
76 | $content .= '\think\Hook::import(' . (var_export(include CONF_PATH . $module . 'tags' . EXT, true)) . ');' . PHP_EOL;
77 | }
78 |
79 | // 加载公共文件
80 | if (is_file($path . 'common' . EXT)) {
81 | $content .= substr(file_get_contents($path . 'common' . EXT), 5) . PHP_EOL;
82 | }
83 |
84 | $content .= '\think\Config::set(' . var_export(\think\Config::get(), true) . ');';
85 | return $content;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/command/optimize/Route.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 | namespace think\console\command\optimize;
12 |
13 | use think\console\Command;
14 | use think\console\Input;
15 | use think\console\Output;
16 |
17 | class Route extends Command
18 | {
19 | /** @var Output */
20 | protected $output;
21 |
22 | protected function configure()
23 | {
24 | $this->setName('optimize:route')
25 | ->setDescription('Build route cache.');
26 | }
27 |
28 | protected function execute(Input $input, Output $output)
29 | {
30 | file_put_contents(RUNTIME_PATH . 'route.php', $this->buildRouteCache());
31 | $output->writeln('Succeed!');
32 | }
33 |
34 | protected function buildRouteCache()
35 | {
36 | $files = \think\Config::get('route_config_file');
37 | foreach ($files as $file) {
38 | if (is_file(CONF_PATH . $file . CONF_EXT)) {
39 | $config = include CONF_PATH . $file . CONF_EXT;
40 | if (is_array($config)) {
41 | \think\Route::import($config);
42 | }
43 | }
44 | }
45 | $rules = \think\Route::rules(true);
46 | array_walk_recursive($rules, [$this, 'buildClosure']);
47 | $content = 'getStartLine();
58 | $endLine = $reflection->getEndLine();
59 | $file = $reflection->getFileName();
60 | $item = file($file);
61 | $content = '';
62 | for ($i = $startLine - 1; $i <= $endLine - 1; $i++) {
63 | $content .= $item[$i];
64 | }
65 | $start = strpos($content, 'function');
66 | $end = strrpos($content, '}');
67 | $value = '[__start__' . substr($content, $start, $end - $start + 1) . '__end__]';
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/input/Argument.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\input;
13 |
14 | class Argument
15 | {
16 |
17 | const REQUIRED = 1;
18 | const OPTIONAL = 2;
19 | const IS_ARRAY = 4;
20 |
21 | private $name;
22 | private $mode;
23 | private $default;
24 | private $description;
25 |
26 | /**
27 | * 构造方法
28 | * @param string $name 参数名
29 | * @param int $mode 参数类型: self::REQUIRED 或者 self::OPTIONAL
30 | * @param string $description 描述
31 | * @param mixed $default 默认值 (仅 self::OPTIONAL 类型有效)
32 | * @throws \InvalidArgumentException
33 | */
34 | public function __construct($name, $mode = null, $description = '', $default = null)
35 | {
36 | if (null === $mode) {
37 | $mode = self::OPTIONAL;
38 | } elseif (!is_int($mode) || $mode > 7 || $mode < 1) {
39 | throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
40 | }
41 |
42 | $this->name = $name;
43 | $this->mode = $mode;
44 | $this->description = $description;
45 |
46 | $this->setDefault($default);
47 | }
48 |
49 | /**
50 | * 获取参数名
51 | * @return string
52 | */
53 | public function getName()
54 | {
55 | return $this->name;
56 | }
57 |
58 | /**
59 | * 是否必须
60 | * @return bool
61 | */
62 | public function isRequired()
63 | {
64 | return self::REQUIRED === (self::REQUIRED & $this->mode);
65 | }
66 |
67 | /**
68 | * 该参数是否接受数组
69 | * @return bool
70 | */
71 | public function isArray()
72 | {
73 | return self::IS_ARRAY === (self::IS_ARRAY & $this->mode);
74 | }
75 |
76 | /**
77 | * 设置默认值
78 | * @param mixed $default 默认值
79 | * @throws \LogicException
80 | */
81 | public function setDefault($default = null)
82 | {
83 | if (self::REQUIRED === $this->mode && null !== $default) {
84 | throw new \LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.');
85 | }
86 |
87 | if ($this->isArray()) {
88 | if (null === $default) {
89 | $default = [];
90 | } elseif (!is_array($default)) {
91 | throw new \LogicException('A default value for an array argument must be an array.');
92 | }
93 | }
94 |
95 | $this->default = $default;
96 | }
97 |
98 | /**
99 | * 获取默认值
100 | * @return mixed
101 | */
102 | public function getDefault()
103 | {
104 | return $this->default;
105 | }
106 |
107 | /**
108 | * 获取描述
109 | * @return string
110 | */
111 | public function getDescription()
112 | {
113 | return $this->description;
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/output/descriptor/Console.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\output\descriptor;
13 |
14 | use think\Console as ThinkConsole;
15 | use think\console\Command;
16 |
17 | class Console
18 | {
19 |
20 | const GLOBAL_NAMESPACE = '_global';
21 |
22 | /**
23 | * @var ThinkConsole
24 | */
25 | private $console;
26 |
27 | /**
28 | * @var null|string
29 | */
30 | private $namespace;
31 |
32 | /**
33 | * @var array
34 | */
35 | private $namespaces;
36 |
37 | /**
38 | * @var Command[]
39 | */
40 | private $commands;
41 |
42 | /**
43 | * @var Command[]
44 | */
45 | private $aliases;
46 |
47 | /**
48 | * 构造方法
49 | * @param ThinkConsole $console
50 | * @param string|null $namespace
51 | */
52 | public function __construct(ThinkConsole $console, $namespace = null)
53 | {
54 | $this->console = $console;
55 | $this->namespace = $namespace;
56 | }
57 |
58 | /**
59 | * @return array
60 | */
61 | public function getNamespaces()
62 | {
63 | if (null === $this->namespaces) {
64 | $this->inspectConsole();
65 | }
66 |
67 | return $this->namespaces;
68 | }
69 |
70 | /**
71 | * @return Command[]
72 | */
73 | public function getCommands()
74 | {
75 | if (null === $this->commands) {
76 | $this->inspectConsole();
77 | }
78 |
79 | return $this->commands;
80 | }
81 |
82 | /**
83 | * @param string $name
84 | * @return Command
85 | * @throws \InvalidArgumentException
86 | */
87 | public function getCommand($name)
88 | {
89 | if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
90 | throw new \InvalidArgumentException(sprintf('Command %s does not exist.', $name));
91 | }
92 |
93 | return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
94 | }
95 |
96 | private function inspectConsole()
97 | {
98 | $this->commands = [];
99 | $this->namespaces = [];
100 |
101 | $all = $this->console->all($this->namespace ? $this->console->findNamespace($this->namespace) : null);
102 | foreach ($this->sortCommands($all) as $namespace => $commands) {
103 | $names = [];
104 |
105 | /** @var Command $command */
106 | foreach ($commands as $name => $command) {
107 | if (!$command->getName()) {
108 | continue;
109 | }
110 |
111 | if ($command->getName() === $name) {
112 | $this->commands[$name] = $command;
113 | } else {
114 | $this->aliases[$name] = $command;
115 | }
116 |
117 | $names[] = $name;
118 | }
119 |
120 | $this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
121 | }
122 | }
123 |
124 | /**
125 | * @param array $commands
126 | * @return array
127 | */
128 | private function sortCommands(array $commands)
129 | {
130 | $namespacedCommands = [];
131 | foreach ($commands as $name => $command) {
132 | $key = $this->console->extractNamespace($name, 1);
133 | if (!$key) {
134 | $key = self::GLOBAL_NAMESPACE;
135 | }
136 |
137 | $namespacedCommands[$key][$name] = $command;
138 | }
139 | ksort($namespacedCommands);
140 |
141 | foreach ($namespacedCommands as &$commandsSet) {
142 | ksort($commandsSet);
143 | }
144 | // unset reference to keep scope clear
145 | unset($commandsSet);
146 |
147 | return $namespacedCommands;
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/output/driver/Buffer.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\output\driver;
13 |
14 | use think\console\Output;
15 |
16 | class Buffer
17 | {
18 | /**
19 | * @var string
20 | */
21 | private $buffer = '';
22 |
23 | public function __construct(Output $output)
24 | {
25 | // do nothing
26 | }
27 |
28 | public function fetch()
29 | {
30 | $content = $this->buffer;
31 | $this->buffer = '';
32 | return $content;
33 | }
34 |
35 | public function write($messages, $newline = false, $options = Output::OUTPUT_NORMAL)
36 | {
37 | $messages = (array) $messages;
38 |
39 | foreach ($messages as $message) {
40 | $this->buffer .= $message;
41 | }
42 | if ($newline) {
43 | $this->buffer .= "\n";
44 | }
45 | }
46 |
47 | public function renderException(\Exception $e)
48 | {
49 | // do nothing
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/output/driver/Nothing.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\output\driver;
13 |
14 | use think\console\Output;
15 |
16 | class Nothing
17 | {
18 |
19 | public function __construct(Output $output)
20 | {
21 | // do nothing
22 | }
23 |
24 | public function write($messages, $newline = false, $options = Output::OUTPUT_NORMAL)
25 | {
26 | // do nothing
27 | }
28 |
29 | public function renderException(\Exception $e)
30 | {
31 | // do nothing
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/output/formatter/Stack.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\output\formatter;
13 |
14 | class Stack
15 | {
16 |
17 | /**
18 | * @var Style[]
19 | */
20 | private $styles;
21 |
22 | /**
23 | * @var Style
24 | */
25 | private $emptyStyle;
26 |
27 | /**
28 | * 构造方法
29 | * @param Style|null $emptyStyle
30 | */
31 | public function __construct(Style $emptyStyle = null)
32 | {
33 | $this->emptyStyle = $emptyStyle ?: new Style();
34 | $this->reset();
35 | }
36 |
37 | /**
38 | * 重置堆栈
39 | */
40 | public function reset()
41 | {
42 | $this->styles = [];
43 | }
44 |
45 | /**
46 | * 推一个样式进入堆栈
47 | * @param Style $style
48 | */
49 | public function push(Style $style)
50 | {
51 | $this->styles[] = $style;
52 | }
53 |
54 | /**
55 | * 从堆栈中弹出一个样式
56 | * @param Style|null $style
57 | * @return Style
58 | * @throws \InvalidArgumentException
59 | */
60 | public function pop(Style $style = null)
61 | {
62 | if (empty($this->styles)) {
63 | return $this->emptyStyle;
64 | }
65 |
66 | if (null === $style) {
67 | return array_pop($this->styles);
68 | }
69 |
70 | /**
71 | * @var int $index
72 | * @var Style $stackedStyle
73 | */
74 | foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
75 | if ($style->apply('') === $stackedStyle->apply('')) {
76 | $this->styles = array_slice($this->styles, 0, $index);
77 |
78 | return $stackedStyle;
79 | }
80 | }
81 |
82 | throw new \InvalidArgumentException('Incorrectly nested style tag found.');
83 | }
84 |
85 | /**
86 | * 计算堆栈的当前样式。
87 | * @return Style
88 | */
89 | public function getCurrent()
90 | {
91 | if (empty($this->styles)) {
92 | return $this->emptyStyle;
93 | }
94 |
95 | return $this->styles[count($this->styles) - 1];
96 | }
97 |
98 | /**
99 | * @param Style $emptyStyle
100 | * @return Stack
101 | */
102 | public function setEmptyStyle(Style $emptyStyle)
103 | {
104 | $this->emptyStyle = $emptyStyle;
105 |
106 | return $this;
107 | }
108 |
109 | /**
110 | * @return Style
111 | */
112 | public function getEmptyStyle()
113 | {
114 | return $this->emptyStyle;
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/thinkphp/library/think/console/output/question/Confirmation.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\console\output\question;
13 |
14 | use think\console\output\Question;
15 |
16 | class Confirmation extends Question
17 | {
18 |
19 | private $trueAnswerRegex;
20 |
21 | /**
22 | * 构造方法
23 | * @param string $question 问题
24 | * @param bool $default 默认答案
25 | * @param string $trueAnswerRegex 验证正则
26 | */
27 | public function __construct($question, $default = true, $trueAnswerRegex = '/^y/i')
28 | {
29 | parent::__construct($question, (bool) $default);
30 |
31 | $this->trueAnswerRegex = $trueAnswerRegex;
32 | $this->setNormalizer($this->getDefaultNormalizer());
33 | }
34 |
35 | /**
36 | * 获取默认的答案回调
37 | * @return callable
38 | */
39 | private function getDefaultNormalizer()
40 | {
41 | $default = $this->getDefault();
42 | $regex = $this->trueAnswerRegex;
43 |
44 | return function ($answer) use ($default, $regex) {
45 | if (is_bool($answer)) {
46 | return $answer;
47 | }
48 |
49 | $answerIsTrue = (bool) preg_match($regex, $answer);
50 | if (false === $default) {
51 | return $answer && $answerIsTrue;
52 | }
53 |
54 | return !$answer || $answerIsTrue;
55 | };
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/thinkphp/library/think/controller/Rest.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\controller;
13 |
14 | use think\App;
15 | use think\Request;
16 | use think\Response;
17 |
18 | abstract class Rest
19 | {
20 |
21 | protected $method; // 当前请求类型
22 | protected $type; // 当前资源类型
23 | // 输出类型
24 | protected $restMethodList = 'get|post|put|delete';
25 | protected $restDefaultMethod = 'get';
26 | protected $restTypeList = 'html|xml|json|rss';
27 | protected $restDefaultType = 'html';
28 | protected $restOutputType = [ // REST允许输出的资源类型列表
29 | 'xml' => 'application/xml',
30 | 'json' => 'application/json',
31 | 'html' => 'text/html',
32 | ];
33 |
34 | /**
35 | * 架构函数 取得模板对象实例
36 | * @access public
37 | */
38 | public function __construct()
39 | {
40 | // 资源类型检测
41 | $request = Request::instance();
42 | $ext = $request->ext();
43 | if ('' == $ext) {
44 | // 自动检测资源类型
45 | $this->type = $request->type();
46 | } elseif (!preg_match('/\(' . $this->restTypeList . '\)$/i', $ext)) {
47 | // 资源类型非法 则用默认资源类型访问
48 | $this->type = $this->restDefaultType;
49 | } else {
50 | $this->type = $ext;
51 | }
52 | // 请求方式检测
53 | $method = strtolower($request->method());
54 | if (false === stripos($this->restMethodList, $method)) {
55 | // 请求方式非法 则用默认请求方法
56 | $method = $this->restDefaultMethod;
57 | }
58 | $this->method = $method;
59 | }
60 |
61 | /**
62 | * REST 调用
63 | * @access public
64 | * @param string $method 方法名
65 | * @return mixed
66 | * @throws \Exception
67 | */
68 | public function _empty($method)
69 | {
70 | if (method_exists($this, $method . '_' . $this->method . '_' . $this->type)) {
71 | // RESTFul方法支持
72 | $fun = $method . '_' . $this->method . '_' . $this->type;
73 | } elseif ($this->method == $this->restDefaultMethod && method_exists($this, $method . '_' . $this->type)) {
74 | $fun = $method . '_' . $this->type;
75 | } elseif ($this->type == $this->restDefaultType && method_exists($this, $method . '_' . $this->method)) {
76 | $fun = $method . '_' . $this->method;
77 | }
78 | if (isset($fun)) {
79 | return App::invokeMethod([$this, $fun]);
80 | } else {
81 | // 抛出异常
82 | throw new \Exception('error action :' . $method);
83 | }
84 | }
85 |
86 | /**
87 | * 输出返回数据
88 | * @access protected
89 | * @param mixed $data 要返回的数据
90 | * @param String $type 返回类型 JSON XML
91 | * @param integer $code HTTP状态码
92 | * @return Response
93 | */
94 | protected function response($data, $type = 'json', $code = 200)
95 | {
96 | return Response::create($data, $type)->code($code);
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/thinkphp/library/think/controller/Yar.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\controller;
13 |
14 | /**
15 | * ThinkPHP Yar控制器类
16 | */
17 | abstract class Yar
18 | {
19 |
20 | /**
21 | * 架构函数
22 | * @access public
23 | */
24 | public function __construct()
25 | {
26 | //控制器初始化
27 | if (method_exists($this, '_initialize')) {
28 | $this->_initialize();
29 | }
30 |
31 | //判断扩展是否存在
32 | if (!extension_loaded('yar')) {
33 | throw new \Exception('not support yar');
34 | }
35 |
36 | //实例化Yar_Server
37 | $server = new \Yar_Server($this);
38 | // 启动server
39 | $server->handle();
40 | }
41 |
42 | /**
43 | * 魔术方法 有不存在的操作的时候执行
44 | * @access public
45 | * @param string $method 方法名
46 | * @param array $args 参数
47 | * @return mixed
48 | */
49 | public function __call($method, $args)
50 | {}
51 | }
52 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/builder/Mysql.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\builder;
13 |
14 | use think\db\Builder;
15 |
16 | /**
17 | * mysql数据库驱动
18 | */
19 | class Mysql extends Builder
20 | {
21 | protected $updateSql = 'UPDATE %TABLE% %JOIN% SET %SET% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%';
22 |
23 | /**
24 | * 字段和表名处理
25 | * @access protected
26 | * @param string $key
27 | * @return string
28 | */
29 | protected function parseKey($key)
30 | {
31 | $key = trim($key);
32 | if (strpos($key, '$.') && false === strpos($key, '(')) {
33 | // JSON字段支持
34 | list($field, $name) = explode('$.', $key);
35 | $key = 'jsn_extract(' . $field . ', \'$.\'.' . $name . ')';
36 | }
37 | if (!preg_match('/[,\'\"\*\(\)`.\s]/', $key)) {
38 | $key = '`' . $key . '`';
39 | }
40 | return $key;
41 | }
42 |
43 | /**
44 | * 随机排序
45 | * @access protected
46 | * @return string
47 | */
48 | protected function parseRand()
49 | {
50 | return 'rand()';
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/builder/Pgsql.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\builder;
13 |
14 | use think\db\Builder;
15 |
16 | /**
17 | * Pgsql数据库驱动
18 | */
19 | class Pgsql extends Builder
20 | {
21 |
22 | /**
23 | * limit分析
24 | * @access protected
25 | * @param mixed $limit
26 | * @return string
27 | */
28 | public function parseLimit($limit)
29 | {
30 | $limitStr = '';
31 | if (!empty($limit)) {
32 | $limit = explode(',', $limit);
33 | if (count($limit) > 1) {
34 | $limitStr .= ' LIMIT ' . $limit[1] . ' OFFSET ' . $limit[0] . ' ';
35 | } else {
36 | $limitStr .= ' LIMIT ' . $limit[0] . ' ';
37 | }
38 | }
39 | return $limitStr;
40 | }
41 |
42 | /**
43 | * 字段和表名处理
44 | * @access protected
45 | * @param string $key
46 | * @return string
47 | */
48 | protected function parseKey($key)
49 | {
50 | $key = trim($key);
51 | if (strpos($key, '$.') && false === strpos($key, '(')) {
52 | // JSON字段支持
53 | list($field, $name) = explode($key, '$.');
54 | $key = $field . '->>\'' . $name . '\'';
55 | }
56 | return $key;
57 | }
58 |
59 | /**
60 | * 随机排序
61 | * @access protected
62 | * @return string
63 | */
64 | protected function parseRand()
65 | {
66 | return 'RANDOM()';
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/builder/Sqlite.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\builder;
13 |
14 | use think\db\Builder;
15 |
16 | /**
17 | * Sqlite数据库驱动
18 | */
19 | class Sqlite extends Builder
20 | {
21 |
22 | /**
23 | * limit
24 | * @access public
25 | * @return string
26 | */
27 | public function parseLimit($limit)
28 | {
29 | $limitStr = '';
30 | if (!empty($limit)) {
31 | $limit = explode(',', $limit);
32 | if (count($limit) > 1) {
33 | $limitStr .= ' LIMIT ' . $limit[1] . ' OFFSET ' . $limit[0] . ' ';
34 | } else {
35 | $limitStr .= ' LIMIT ' . $limit[0] . ' ';
36 | }
37 | }
38 | return $limitStr;
39 | }
40 |
41 | /**
42 | * 随机排序
43 | * @access protected
44 | * @return string
45 | */
46 | protected function parseRand()
47 | {
48 | return 'RANDOM()';
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/builder/Sqlsrv.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\builder;
13 |
14 | use think\db\Builder;
15 |
16 | /**
17 | * Sqlsrv数据库驱动
18 | */
19 | class Sqlsrv extends Builder
20 | {
21 | 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%';
22 | protected $selectInsertSql = 'SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%';
23 | protected $updateSql = 'UPDATE %TABLE% SET %SET% FROM %TABLE% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%';
24 | protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%';
25 |
26 | /**
27 | * order分析
28 | * @access protected
29 | * @param mixed $order
30 | * @return string
31 | */
32 | protected function parseOrder($order)
33 | {
34 | return !empty($order) ? ' ORDER BY ' . $order : ' ORDER BY rand()';
35 | }
36 |
37 | /**
38 | * 随机排序
39 | * @access protected
40 | * @return string
41 | */
42 | protected function parseRand()
43 | {
44 | return 'rand()';
45 | }
46 |
47 | /**
48 | * 字段名分析
49 | * @access protected
50 | * @param string $key
51 | * @return string
52 | */
53 | protected function parseKey($key)
54 | {
55 | $key = trim($key);
56 | if (!is_numeric($key) && !preg_match('/[,\'\"\*\(\)\[.\s]/', $key)) {
57 | $key = '[' . $key . ']';
58 | }
59 | return $key;
60 | }
61 |
62 | /**
63 | * limit
64 | * @access protected
65 | * @param mixed $limit
66 | * @return string
67 | */
68 | protected function parseLimit($limit)
69 | {
70 | if (empty($limit)) {
71 | return '';
72 | }
73 |
74 | $limit = explode(',', $limit);
75 | if (count($limit) > 1) {
76 | $limitStr = '(T1.ROW_NUMBER BETWEEN ' . $limit[0] . ' + 1 AND ' . $limit[0] . ' + ' . $limit[1] . ')';
77 | } else {
78 | $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND ' . $limit[0] . ")";
79 | }
80 | return 'WHERE ' . $limitStr;
81 | }
82 |
83 | public function selectInsert($fields, $table, $options)
84 | {
85 | $this->selectSql = $this->selectInsertSql;
86 | return parent::selectInsert($fields, $table, $options);
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/connector/Mysql.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\connector;
13 |
14 | use PDO;
15 | use think\db\Connection;
16 | use think\Log;
17 |
18 | /**
19 | * mysql数据库驱动
20 | */
21 | class Mysql extends Connection
22 | {
23 |
24 | /**
25 | * 解析pdo连接的dsn信息
26 | * @access protected
27 | * @param array $config 连接信息
28 | * @return string
29 | */
30 | protected function parseDsn($config)
31 | {
32 | $dsn = 'mysql:dbname=' . $config['database'] . ';host=' . $config['hostname'];
33 | if (!empty($config['hostport'])) {
34 | $dsn .= ';port=' . $config['hostport'];
35 | } elseif (!empty($config['socket'])) {
36 | $dsn .= ';unix_socket=' . $config['socket'];
37 | }
38 | if (!empty($config['charset'])) {
39 | $dsn .= ';charset=' . $config['charset'];
40 | }
41 | return $dsn;
42 | }
43 |
44 | /**
45 | * 取得数据表的字段信息
46 | * @access public
47 | * @param string $tableName
48 | * @return array
49 | */
50 | public function getFields($tableName)
51 | {
52 | $this->initConnect(true);
53 | list($tableName) = explode(' ', $tableName);
54 | if (strpos($tableName, '.')) {
55 | $tableName = str_replace('.', '`.`', $tableName);
56 | }
57 | $sql = 'SHOW COLUMNS FROM `' . $tableName . '`';
58 | // 调试开始
59 | $this->debug(true);
60 | $pdo = $this->linkID->query($sql);
61 | // 调试结束
62 | $this->debug(false, $sql);
63 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
64 | $info = [];
65 | if ($result) {
66 | foreach ($result as $key => $val) {
67 | $val = array_change_key_case($val);
68 | $info[$val['field']] = [
69 | 'name' => $val['field'],
70 | 'type' => $val['type'],
71 | 'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
72 | 'default' => $val['default'],
73 | 'primary' => (strtolower($val['key']) == 'pri'),
74 | 'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
75 | ];
76 | }
77 | }
78 | return $this->fieldCase($info);
79 | }
80 |
81 | /**
82 | * 取得数据库的表信息
83 | * @access public
84 | * @param string $dbName
85 | * @return array
86 | */
87 | public function getTables($dbName = '')
88 | {
89 | $sql = !empty($dbName) ? 'SHOW TABLES FROM ' . $dbName : 'SHOW TABLES ';
90 | // 调试开始
91 | $this->debug(true);
92 | $pdo = $this->linkID->query($sql);
93 | // 调试结束
94 | $this->debug(false, $sql);
95 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
96 | $info = [];
97 | foreach ($result as $key => $val) {
98 | $info[$key] = current($val);
99 | }
100 | return $info;
101 | }
102 |
103 | /**
104 | * SQL性能分析
105 | * @access protected
106 | * @param string $sql
107 | * @return array
108 | */
109 | protected function getExplain($sql)
110 | {
111 | $pdo = $this->linkID->query("EXPLAIN " . $sql);
112 | $result = $pdo->fetch(PDO::FETCH_ASSOC);
113 | $result = array_change_key_case($result);
114 | if (isset($result['extra'])) {
115 | if (strpos($result['extra'], 'filesort') || strpos($result['extra'], 'temporary')) {
116 | Log::record('SQL:' . $this->queryStr . '[' . $result['extra'] . ']', 'warn');
117 | }
118 | }
119 | return $result;
120 | }
121 |
122 | protected function supportSavepoint()
123 | {
124 | return true;
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/connector/Pgsql.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\connector;
13 |
14 | use PDO;
15 | use think\db\Connection;
16 |
17 | /**
18 | * Pgsql数据库驱动
19 | */
20 | class Pgsql extends Connection
21 | {
22 |
23 | /**
24 | * 解析pdo连接的dsn信息
25 | * @access protected
26 | * @param array $config 连接信息
27 | * @return string
28 | */
29 | protected function parseDsn($config)
30 | {
31 | $dsn = 'pgsql:dbname=' . $config['database'] . ';host=' . $config['hostname'];
32 | if (!empty($config['hostport'])) {
33 | $dsn .= ';port=' . $config['hostport'];
34 | }
35 | return $dsn;
36 | }
37 |
38 | /**
39 | * 取得数据表的字段信息
40 | * @access public
41 | * @param string $tableName
42 | * @return array
43 | */
44 | public function getFields($tableName)
45 | {
46 | $this->initConnect(true);
47 | list($tableName) = explode(' ', $tableName);
48 | $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 . '\');';
49 | // 调试开始
50 | $this->debug(true);
51 | $pdo = $this->linkID->query($sql);
52 | // 调试结束
53 | $this->debug(false, $sql);
54 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
55 | $info = [];
56 | if ($result) {
57 | foreach ($result as $key => $val) {
58 | $val = array_change_key_case($val);
59 | $info[$val['field']] = [
60 | 'name' => $val['field'],
61 | 'type' => $val['type'],
62 | 'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
63 | 'default' => $val['default'],
64 | 'primary' => (strtolower($val['key']) == 'pri'),
65 | 'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
66 | ];
67 | }
68 | }
69 | return $this->fieldCase($info);
70 | }
71 |
72 | /**
73 | * 取得数据库的表信息
74 | * @access public
75 | * @param string $dbName
76 | * @return array
77 | */
78 | public function getTables($dbName = '')
79 | {
80 | $sql = "select tablename as Tables_in_test from pg_tables where schemaname ='public'";
81 | // 调试开始
82 | $this->debug(true);
83 | $pdo = $this->linkID->query($sql);
84 | // 调试结束
85 | $this->debug(false, $sql);
86 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
87 | $info = [];
88 | foreach ($result as $key => $val) {
89 | $info[$key] = current($val);
90 | }
91 | return $info;
92 | }
93 |
94 | /**
95 | * SQL性能分析
96 | * @access protected
97 | * @param string $sql
98 | * @return array
99 | */
100 | protected function getExplain($sql)
101 | {
102 | return [];
103 | }
104 |
105 | protected function supportSavepoint()
106 | {
107 | return true;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/connector/Sqlite.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\connector;
13 |
14 | use PDO;
15 | use think\db\Connection;
16 |
17 | /**
18 | * Sqlite数据库驱动
19 | */
20 | class Sqlite extends Connection
21 | {
22 |
23 | /**
24 | * 解析pdo连接的dsn信息
25 | * @access protected
26 | * @param array $config 连接信息
27 | * @return string
28 | */
29 | protected function parseDsn($config)
30 | {
31 | $dsn = 'sqlite:' . $config['database'];
32 | return $dsn;
33 | }
34 |
35 | /**
36 | * 取得数据表的字段信息
37 | * @access public
38 | * @param string $tableName
39 | * @return array
40 | */
41 | public function getFields($tableName)
42 | {
43 | $this->initConnect(true);
44 | list($tableName) = explode(' ', $tableName);
45 | $sql = 'PRAGMA table_info( ' . $tableName . ' )';
46 | // 调试开始
47 | $this->debug(true);
48 | $pdo = $this->linkID->query($sql);
49 | // 调试结束
50 | $this->debug(false, $sql);
51 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
52 | $info = [];
53 | if ($result) {
54 | foreach ($result as $key => $val) {
55 | $val = array_change_key_case($val);
56 | $info[$val['name']] = [
57 | 'name' => $val['name'],
58 | 'type' => $val['type'],
59 | 'notnull' => 1 === $val['notnull'],
60 | 'default' => $val['dflt_value'],
61 | 'primary' => '1' == $val['pk'],
62 | 'autoinc' => '1' == $val['pk'],
63 | ];
64 | }
65 | }
66 | return $this->fieldCase($info);
67 | }
68 |
69 | /**
70 | * 取得数据库的表信息
71 | * @access public
72 | * @param string $dbName
73 | * @return array
74 | */
75 | public function getTables($dbName = '')
76 | {
77 | $sql = "SELECT name FROM sqlite_master WHERE type='table' "
78 | . "UNION ALL SELECT name FROM sqlite_temp_master "
79 | . "WHERE type='table' ORDER BY name";
80 | // 调试开始
81 | $this->debug(true);
82 | $pdo = $this->linkID->query($sql);
83 | // 调试结束
84 | $this->debug(false, $sql);
85 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
86 | $info = [];
87 | foreach ($result as $key => $val) {
88 | $info[$key] = current($val);
89 | }
90 | return $info;
91 | }
92 |
93 | /**
94 | * SQL性能分析
95 | * @access protected
96 | * @param string $sql
97 | * @return array
98 | */
99 | protected function getExplain($sql)
100 | {
101 | return [];
102 | }
103 |
104 | protected function supportSavepoint()
105 | {
106 | return true;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/connector/Sqlsrv.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\connector;
13 |
14 | use PDO;
15 | use think\db\Connection;
16 |
17 | /**
18 | * Sqlsrv数据库驱动
19 | */
20 | class Sqlsrv extends Connection
21 | {
22 | // PDO连接参数
23 | protected $params = [
24 | PDO::ATTR_CASE => PDO::CASE_LOWER,
25 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
26 | PDO::ATTR_STRINGIFY_FETCHES => false,
27 | ];
28 |
29 | /**
30 | * 解析pdo连接的dsn信息
31 | * @access protected
32 | * @param array $config 连接信息
33 | * @return string
34 | */
35 | protected function parseDsn($config)
36 | {
37 | $dsn = 'sqlsrv:Database=' . $config['database'] . ';Server=' . $config['hostname'];
38 | if (!empty($config['hostport'])) {
39 | $dsn .= ',' . $config['hostport'];
40 | }
41 | return $dsn;
42 | }
43 |
44 | /**
45 | * 取得数据表的字段信息
46 | * @access public
47 | * @param string $tableName
48 | * @return array
49 | */
50 | public function getFields($tableName)
51 | {
52 | $this->initConnect(true);
53 | list($tableName) = explode(' ', $tableName);
54 | $sql = "SELECT column_name, data_type, column_default, is_nullable
55 | FROM information_schema.tables AS t
56 | JOIN information_schema.columns AS c
57 | ON t.table_catalog = c.table_catalog
58 | AND t.table_schema = c.table_schema
59 | AND t.table_name = c.table_name
60 | WHERE t.table_name = '$tableName'";
61 | // 调试开始
62 | $this->debug(true);
63 | $pdo = $this->linkID->query($sql);
64 | // 调试结束
65 | $this->debug(false, $sql);
66 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
67 | $info = [];
68 | if ($result) {
69 | foreach ($result as $key => $val) {
70 | $val = array_change_key_case($val);
71 | $info[$val['column_name']] = [
72 | 'name' => $val['column_name'],
73 | 'type' => $val['data_type'],
74 | 'notnull' => (bool) ('' === $val['is_nullable']), // not null is empty, null is yes
75 | 'default' => $val['column_default'],
76 | 'primary' => false,
77 | 'autoinc' => false,
78 | ];
79 | }
80 | }
81 | $sql = "SELECT column_name FROM information_schema.key_column_usage WHERE table_name='$tableName'";
82 | // 调试开始
83 | $this->debug(true);
84 | $pdo = $this->linkID->query($sql);
85 | // 调试结束
86 | $this->debug(false, $sql);
87 | $result = $pdo->fetch(PDO::FETCH_ASSOC);
88 | if ($result) {
89 | $info[$result['column_name']]['primary'] = true;
90 | }
91 | return $this->fieldCase($info);
92 | }
93 |
94 | /**
95 | * 取得数据表的字段信息
96 | * @access public
97 | * @param string $dbName
98 | * @return array
99 | */
100 | public function getTables($dbName = '')
101 | {
102 | $sql = "SELECT TABLE_NAME
103 | FROM INFORMATION_SCHEMA.TABLES
104 | WHERE TABLE_TYPE = 'BASE TABLE'
105 | ";
106 | // 调试开始
107 | $this->debug(true);
108 | $pdo = $this->linkID->query($sql);
109 | // 调试结束
110 | $this->debug(false, $sql);
111 | $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
112 | $info = [];
113 | foreach ($result as $key => $val) {
114 | $info[$key] = current($val);
115 | }
116 | return $info;
117 | }
118 |
119 | /**
120 | * SQL性能分析
121 | * @access protected
122 | * @param string $sql
123 | * @return array
124 | */
125 | protected function getExplain($sql)
126 | {
127 | return [];
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/connector/pgsql.sql:
--------------------------------------------------------------------------------
1 | CREATE OR REPLACE FUNCTION pgsql_type(a_type varchar) RETURNS varchar AS
2 | $BODY$
3 | DECLARE
4 | v_type varchar;
5 | BEGIN
6 | IF a_type='int8' THEN
7 | v_type:='bigint';
8 | ELSIF a_type='int4' THEN
9 | v_type:='integer';
10 | ELSIF a_type='int2' THEN
11 | v_type:='smallint';
12 | ELSIF a_type='bpchar' THEN
13 | v_type:='char';
14 | ELSE
15 | v_type:=a_type;
16 | END IF;
17 | RETURN v_type;
18 | END;
19 | $BODY$
20 | LANGUAGE PLPGSQL;
21 |
22 | CREATE TYPE "public"."tablestruct" AS (
23 | "fields_key_name" varchar(100),
24 | "fields_name" VARCHAR(200),
25 | "fields_type" VARCHAR(20),
26 | "fields_length" BIGINT,
27 | "fields_not_null" VARCHAR(10),
28 | "fields_default" VARCHAR(500),
29 | "fields_comment" VARCHAR(1000)
30 | );
31 |
32 | CREATE OR REPLACE FUNCTION "public"."table_msg" (a_schema_name varchar, a_table_name varchar) RETURNS SETOF "public"."tablestruct" AS
33 | $body$
34 | DECLARE
35 | v_ret tablestruct;
36 | v_oid oid;
37 | v_sql varchar;
38 | v_rec RECORD;
39 | v_key varchar;
40 | BEGIN
41 | SELECT
42 | pg_class.oid INTO v_oid
43 | FROM
44 | pg_class
45 | INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid AND lower(pg_namespace.nspname) = a_schema_name)
46 | WHERE
47 | pg_class.relname=a_table_name;
48 | IF NOT FOUND THEN
49 | RETURN;
50 | END IF;
51 |
52 | v_sql='
53 | SELECT
54 | pg_attribute.attname AS fields_name,
55 | pg_attribute.attnum AS fields_index,
56 | pgsql_type(pg_type.typname::varchar) AS fields_type,
57 | pg_attribute.atttypmod-4 as fields_length,
58 | CASE WHEN pg_attribute.attnotnull THEN ''not null''
59 | ELSE ''''
60 | END AS fields_not_null,
61 | pg_attrdef.adsrc AS fields_default,
62 | pg_description.description AS fields_comment
63 | FROM
64 | pg_attribute
65 | INNER JOIN pg_class ON pg_attribute.attrelid = pg_class.oid
66 | INNER JOIN pg_type ON pg_attribute.atttypid = pg_type.oid
67 | LEFT OUTER JOIN pg_attrdef ON pg_attrdef.adrelid = pg_class.oid AND pg_attrdef.adnum = pg_attribute.attnum
68 | LEFT OUTER JOIN pg_description ON pg_description.objoid = pg_class.oid AND pg_description.objsubid = pg_attribute.attnum
69 | WHERE
70 | pg_attribute.attnum > 0
71 | AND attisdropped <> ''t''
72 | AND pg_class.oid = ' || v_oid || '
73 | ORDER BY pg_attribute.attnum' ;
74 |
75 | FOR v_rec IN EXECUTE v_sql LOOP
76 | v_ret.fields_name=v_rec.fields_name;
77 | v_ret.fields_type=v_rec.fields_type;
78 | IF v_rec.fields_length > 0 THEN
79 | v_ret.fields_length:=v_rec.fields_length;
80 | ELSE
81 | v_ret.fields_length:=NULL;
82 | END IF;
83 | v_ret.fields_not_null=v_rec.fields_not_null;
84 | v_ret.fields_default=v_rec.fields_default;
85 | v_ret.fields_comment=v_rec.fields_comment;
86 | 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;
87 | IF FOUND THEN
88 | v_ret.fields_key_name=v_key;
89 | ELSE
90 | v_ret.fields_key_name='';
91 | END IF;
92 | RETURN NEXT v_ret;
93 | END LOOP;
94 | RETURN ;
95 | END;
96 | $body$
97 | LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
98 |
99 | COMMENT ON FUNCTION "public"."table_msg"(a_schema_name varchar, a_table_name varchar)
100 | IS '获得表信息';
101 |
102 | ---重载一个函数
103 | CREATE OR REPLACE FUNCTION "public"."table_msg" (a_table_name varchar) RETURNS SETOF "public"."tablestruct" AS
104 | $body$
105 | DECLARE
106 | v_ret tablestruct;
107 | BEGIN
108 | FOR v_ret IN SELECT * FROM table_msg('public',a_table_name) LOOP
109 | RETURN NEXT v_ret;
110 | END LOOP;
111 | RETURN;
112 | END;
113 | $body$
114 | LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
115 |
116 | COMMENT ON FUNCTION "public"."table_msg"(a_table_name varchar)
117 | IS '获得表信息';
--------------------------------------------------------------------------------
/thinkphp/library/think/db/exception/BindParamException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\exception;
13 |
14 | use think\exception\DbException;
15 |
16 | /**
17 | * PDO参数绑定异常
18 | */
19 | class BindParamException extends DbException
20 | {
21 |
22 | /**
23 | * BindParamException constructor.
24 | * @param string $message
25 | * @param array $config
26 | * @param string $sql
27 | * @param array $bind
28 | * @param int $code
29 | */
30 | public function __construct($message, $config, $sql, $bind, $code = 10502)
31 | {
32 | $this->setData('Bind Param', $bind);
33 | parent::__construct($message, $config, $sql, $code);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/exception/DataNotFoundException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\exception;
13 |
14 | use think\exception\DbException;
15 |
16 | class DataNotFoundException extends DbException
17 | {
18 | protected $table;
19 |
20 | /**
21 | * DbException constructor.
22 | * @param string $message
23 | * @param string $table
24 | * @param array $config
25 | */
26 | public function __construct($message, $table = '', Array $config = [])
27 | {
28 | $this->message = $message;
29 | $this->table = $table;
30 |
31 | $this->setData('Database Config', $config);
32 | }
33 |
34 | /**
35 | * 获取数据表名
36 | * @access public
37 | * @return string
38 | */
39 | public function getTable()
40 | {
41 | return $this->table;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/thinkphp/library/think/db/exception/ModelNotFoundException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\db\exception;
13 |
14 | use think\exception\DbException;
15 |
16 | class ModelNotFoundException extends DbException
17 | {
18 | protected $model;
19 |
20 | /**
21 | * 构造方法
22 | * @param string $message
23 | * @param string $model
24 | */
25 | public function __construct($message, $model = '', Array $config = [])
26 | {
27 | $this->message = $message;
28 | $this->model = $model;
29 |
30 | $this->setData('Database Config', $config);
31 | }
32 |
33 | /**
34 | * 获取模型类名
35 | * @access public
36 | * @return string
37 | */
38 | public function getModel()
39 | {
40 | return $this->model;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/thinkphp/library/think/debug/Html.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\debug;
13 |
14 | use think\Cache;
15 | use think\Config;
16 | use think\Db;
17 | use think\Debug;
18 | use think\Request;
19 | use think\Response;
20 |
21 | /**
22 | * 页面Trace调试
23 | */
24 | class Html
25 | {
26 | protected $config = [
27 | 'trace_file' => '',
28 | 'trace_tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'],
29 | ];
30 |
31 | // 实例化并传入参数
32 | public function __construct(array $config = [])
33 | {
34 | $this->config['trace_file'] = THINK_PATH . 'tpl/page_trace.tpl';
35 | $this->config = array_merge($this->config, $config);
36 | }
37 |
38 | /**
39 | * 调试输出接口
40 | * @access public
41 | * @param Response $response Response对象
42 | * @param array $log 日志信息
43 | * @return bool
44 | */
45 | public function output(Response $response, array $log = [])
46 | {
47 | $request = Request::instance();
48 | $contentType = $response->getHeader('Content-Type');
49 | $accept = $request->header('accept');
50 | if (strpos($accept, 'application/json') === 0 || $request->isAjax()) {
51 | return false;
52 | } elseif (!empty($contentType) && strpos($contentType, 'html') === false) {
53 | return false;
54 | }
55 | // 获取基本信息
56 | $runtime = number_format(microtime(true) - THINK_START_TIME, 10);
57 | $reqs = number_format(1 / $runtime, 2);
58 | $mem = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
59 |
60 | // 页面Trace信息
61 | if (isset($_SERVER['HTTP_HOST'])) {
62 | $uri = $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
63 | } else {
64 | $uri = 'cmd:' . implode(' ', $_SERVER['argv']);
65 | }
66 | $base = [
67 | '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $uri,
68 | '运行时间' => number_format($runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()),
69 | '查询信息' => Db::$queryTimes . ' queries ' . Db::$executeTimes . ' writes ',
70 | '缓存信息' => Cache::$readTimes . ' reads,' . Cache::$writeTimes . ' writes',
71 | '配置加载' => count(Config::get()),
72 | ];
73 |
74 | if (session_id()) {
75 | $base['会话信息'] = 'SESSION_ID=' . session_id();
76 | }
77 |
78 | $info = Debug::getFile(true);
79 |
80 | // 页面Trace信息
81 | $trace = [];
82 | foreach ($this->config['trace_tabs'] as $name => $title) {
83 | $name = strtolower($name);
84 | switch ($name) {
85 | case 'base': // 基本信息
86 | $trace[$title] = $base;
87 | break;
88 | case 'file': // 文件信息
89 | $trace[$title] = $info;
90 | break;
91 | default: // 调试信息
92 | if (strpos($name, '|')) {
93 | // 多组信息
94 | $names = explode('|', $name);
95 | $result = [];
96 | foreach ($names as $name) {
97 | $result = array_merge($result, isset($log[$name]) ? $log[$name] : []);
98 | }
99 | $trace[$title] = $result;
100 | } else {
101 | $trace[$title] = isset($log[$name]) ? $log[$name] : '';
102 | }
103 | }
104 | }
105 | // 调用Trace页面模板
106 | ob_start();
107 | include $this->config['trace_file'];
108 | return ob_get_clean();
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/ClassNotFoundException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | class ClassNotFoundException extends \RuntimeException
15 | {
16 | protected $class;
17 | public function __construct($message, $class = '')
18 | {
19 | $this->message = $message;
20 | $this->class = $class;
21 | }
22 |
23 | /**
24 | * 获取类名
25 | * @access public
26 | * @return string
27 | */
28 | public function getClass()
29 | {
30 | return $this->class;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/DbException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | use think\Exception;
15 |
16 | /**
17 | * Database相关异常处理类
18 | */
19 | class DbException extends Exception
20 | {
21 | /**
22 | * DbException constructor.
23 | * @param string $message
24 | * @param array $config
25 | * @param string $sql
26 | * @param int $code
27 | */
28 | public function __construct($message, array $config, $sql, $code = 10500)
29 | {
30 | $this->message = $message;
31 | $this->code = $code;
32 |
33 | $this->setData('Database Status', [
34 | 'Error Code' => $code,
35 | 'Error Message' => $message,
36 | 'Error SQL' => $sql,
37 | ]);
38 |
39 | $this->setData('Database Config', $config);
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/ErrorException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | use think\Exception;
15 |
16 | /**
17 | * ThinkPHP错误异常
18 | * 主要用于封装 set_error_handler 和 register_shutdown_function 得到的错误
19 | * 除开从 think\Exception 继承的功能
20 | * 其他和PHP系统\ErrorException功能基本一样
21 | */
22 | class ErrorException extends Exception
23 | {
24 | /**
25 | * 用于保存错误级别
26 | * @var integer
27 | */
28 | protected $severity;
29 |
30 | /**
31 | * 错误异常构造函数
32 | * @param integer $severity 错误级别
33 | * @param string $message 错误详细信息
34 | * @param string $file 出错文件路径
35 | * @param integer $line 出错行号
36 | * @param array $context 错误上下文,会包含错误触发处作用域内所有变量的数组
37 | */
38 | public function __construct($severity, $message, $file, $line, array $context = [])
39 | {
40 | $this->severity = $severity;
41 | $this->message = $message;
42 | $this->file = $file;
43 | $this->line = $line;
44 | $this->code = 0;
45 |
46 | empty($context) || $this->setData('Error Context', $context);
47 | }
48 |
49 | /**
50 | * 获取错误级别
51 | * @return integer 错误级别
52 | */
53 | final public function getSeverity()
54 | {
55 | return $this->severity;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/HttpException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | class HttpException extends \RuntimeException
15 | {
16 | private $statusCode;
17 | private $headers;
18 |
19 | public function __construct($statusCode, $message = null, \Exception $previous = null, array $headers = [], $code = 0)
20 | {
21 | $this->statusCode = $statusCode;
22 | $this->headers = $headers;
23 |
24 | parent::__construct($message, $code, $previous);
25 | }
26 |
27 | public function getStatusCode()
28 | {
29 | return $this->statusCode;
30 | }
31 |
32 | public function getHeaders()
33 | {
34 | return $this->headers;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/HttpResponseException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | use think\Response;
15 |
16 | class HttpResponseException extends \RuntimeException
17 | {
18 | /**
19 | * @var Response
20 | */
21 | protected $response;
22 |
23 | public function __construct(Response $response)
24 | {
25 | $this->response = $response;
26 | }
27 |
28 | public function getResponse()
29 | {
30 | return $this->response;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/PDOException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | use think\exception\DbException;
15 |
16 | /**
17 | * PDO异常处理类
18 | * 重新封装了系统的\PDOException类
19 | */
20 | class PDOException extends DbException
21 | {
22 | /**
23 | * PDOException constructor.
24 | * @param \PDOException $exception
25 | * @param array $config
26 | * @param string $sql
27 | * @param int $code
28 | */
29 | public function __construct(\PDOException $exception, array $config, $sql, $code = 10501)
30 | {
31 | $error = $exception->errorInfo;
32 |
33 | $this->setData('PDO Error Info', [
34 | 'SQLSTATE' => $error[0],
35 | 'Driver Error Code' => $error[1],
36 | 'Driver Error Message' => isset($error[2]) ? $error[2] : '',
37 | ]);
38 |
39 | parent::__construct($exception->getMessage(), $config, $sql, $code);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/TemplateNotFoundException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | class TemplateNotFoundException extends \RuntimeException
15 | {
16 | protected $template;
17 |
18 | public function __construct($message, $template = '')
19 | {
20 | $this->message = $message;
21 | $this->template = $template;
22 | }
23 |
24 | /**
25 | * 获取模板文件
26 | * @access public
27 | * @return string
28 | */
29 | public function getTemplate()
30 | {
31 | return $this->template;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/ThrowableError.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | class ThrowableError extends \ErrorException
15 | {
16 | public function __construct(\Throwable $e)
17 | {
18 |
19 | if ($e instanceof \ParseError) {
20 | $message = 'Parse error: ' . $e->getMessage();
21 | $severity = E_PARSE;
22 | } elseif ($e instanceof \TypeError) {
23 | $message = 'Type error: ' . $e->getMessage();
24 | $severity = E_RECOVERABLE_ERROR;
25 | } else {
26 | $message = 'Fatal error: ' . $e->getMessage();
27 | $severity = E_ERROR;
28 | }
29 |
30 | parent::__construct(
31 | $message,
32 | $e->getCode(),
33 | $severity,
34 | $e->getFile(),
35 | $e->getLine()
36 | );
37 |
38 | $this->setTrace($e->getTrace());
39 | }
40 |
41 | protected function setTrace($trace)
42 | {
43 | $traceReflector = new \ReflectionProperty('Exception', 'trace');
44 | $traceReflector->setAccessible(true);
45 | $traceReflector->setValue($this, $trace);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/thinkphp/library/think/exception/ValidateException.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\exception;
13 |
14 | class ValidateException extends \RuntimeException
15 | {
16 | protected $error;
17 |
18 | public function __construct($error)
19 | {
20 | $this->error = $error;
21 | $this->message = is_array($error) ? implode("\n\r", $error) : $error;
22 | }
23 |
24 | /**
25 | * 获取验证错误信息
26 | * @access public
27 | * @return array|string
28 | */
29 | public function getError()
30 | {
31 | return $this->error;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/thinkphp/library/think/log/driver/File.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\log\driver;
13 |
14 | /**
15 | * 本地化调试输出到文件
16 | */
17 | class File
18 | {
19 | protected $config = [
20 | 'time_format' => ' c ',
21 | 'file_size' => 2097152,
22 | 'path' => LOG_PATH,
23 | 'apart_level' => [],
24 | ];
25 |
26 | // 实例化并传入参数
27 | public function __construct($config = [])
28 | {
29 | if (is_array($config)) {
30 | $this->config = array_merge($this->config, $config);
31 | }
32 | }
33 |
34 | /**
35 | * 日志写入接口
36 | * @access public
37 | * @param array $log 日志信息
38 | * @return bool
39 | */
40 | public function save(array $log = [])
41 | {
42 | $now = date($this->config['time_format']);
43 | $destination = $this->config['path'] . date('Ym') . DS . date('d') . '.log';
44 |
45 | $path = dirname($destination);
46 | !is_dir($path) && mkdir($path, 0755, true);
47 |
48 | //检测日志文件大小,超过配置大小则备份日志文件重新生成
49 | if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
50 | rename($destination, dirname($destination) . DS . $_SERVER['REQUEST_TIME'] . '-' . basename($destination));
51 | }
52 |
53 | // 获取基本信息
54 | if (isset($_SERVER['HTTP_HOST'])) {
55 | $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
56 | } else {
57 | $current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
58 | }
59 |
60 | $runtime = number_format(microtime(true) - THINK_START_TIME, 10);
61 | $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
62 | $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]';
63 | $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
64 | $memory_str = ' [内存消耗:' . $memory_use . 'kb]';
65 | $file_load = ' [文件加载:' . count(get_included_files()) . ']';
66 |
67 | $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n";
68 | $server = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0';
69 | $remote = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
70 | $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI';
71 | $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
72 | foreach ($log as $type => $val) {
73 | $level = '';
74 | foreach ($val as $msg) {
75 | if (!is_string($msg)) {
76 | $msg = var_export($msg, true);
77 | }
78 | $level .= '[ ' . $type . ' ] ' . $msg . "\r\n";
79 | }
80 | if (in_array($type, $this->config['apart_level'])) {
81 | // 独立记录的日志级别
82 | $filename = $path . DS . $type . '.log';
83 | error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$level}\r\n---------------------------------------------------------------\r\n", 3, $filename);
84 | } else {
85 | $info .= $level;
86 | }
87 | }
88 | return error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$info}\r\n---------------------------------------------------------------\r\n", 3, $destination);
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/thinkphp/library/think/log/driver/Test.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\log\driver;
13 |
14 | /**
15 | * 模拟测试输出
16 | */
17 | class Test
18 | {
19 | /**
20 | * 日志写入接口
21 | * @access public
22 | * @param array $log 日志信息
23 | * @return bool
24 | */
25 | public function save(array $log = [])
26 | {
27 | return true;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/thinkphp/library/think/model/Pivot.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\model;
13 |
14 | use think\Model;
15 |
16 | class Pivot extends Model
17 | {
18 |
19 | /**
20 | * 架构函数
21 | * @access public
22 | * @param array|object $data 数据
23 | * @param string $table 中间数据表名
24 | */
25 | public function __construct($data = [], $table = '')
26 | {
27 | if (is_object($data)) {
28 | $this->data = get_object_vars($data);
29 | } else {
30 | $this->data = $data;
31 | }
32 |
33 | $this->table = $table;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/thinkphp/library/think/paginator/Collection.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\paginator;
13 |
14 | use Exception;
15 | use think\Paginator;
16 |
17 | /**
18 | * Class Collection
19 | * @package think\paginator
20 | * @method integer total()
21 | * @method integer listRows()
22 | * @method integer currentPage()
23 | * @method string render()
24 | * @method Paginator fragment($fragment)
25 | * @method Paginator appends($key, $value)
26 | * @method integer lastPage()
27 | * @method boolean hasPages()
28 | */
29 | class Collection extends \think\Collection
30 | {
31 |
32 | /** @var Paginator */
33 | protected $paginator;
34 |
35 | public function __construct($items = [], Paginator $paginator = null)
36 | {
37 | $this->paginator = $paginator;
38 | parent::__construct($items);
39 | }
40 |
41 | public static function make($items = [], Paginator $paginator = null)
42 | {
43 | return new static($items, $paginator);
44 | }
45 |
46 | public function toArray()
47 | {
48 | if ($this->paginator) {
49 | try {
50 | $total = $this->total();
51 | } catch (Exception $e) {
52 | $total = null;
53 | }
54 |
55 | return [
56 | 'total' => $total,
57 | 'per_page' => $this->listRows(),
58 | 'current_page' => $this->currentPage(),
59 | 'data' => parent::toArray()
60 | ];
61 | } else {
62 | return parent::toArray();
63 | }
64 | }
65 |
66 | public function __call($method, $args)
67 | {
68 | if ($this->paginator && method_exists($this->paginator, $method)) {
69 | return call_user_func_array([$this->paginator, $method], $args);
70 | } else {
71 | throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/process/Utils.php:
--------------------------------------------------------------------------------
1 |
8 | // +----------------------------------------------------------------------
9 |
10 | namespace think\process;
11 |
12 | class Utils
13 | {
14 |
15 | /**
16 | * 转义字符串
17 | * @param string $argument
18 | * @return string
19 | */
20 | public static function escapeArgument($argument)
21 | {
22 |
23 | if ('' === $argument) {
24 | return escapeshellarg($argument);
25 | }
26 | $escapedArgument = '';
27 | $quote = false;
28 | foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
29 | if ('"' === $part) {
30 | $escapedArgument .= '\\"';
31 | } elseif (self::isSurroundedBy($part, '%')) {
32 | // Avoid environment variable expansion
33 | $escapedArgument .= '^%"' . substr($part, 1, -1) . '"^%';
34 | } else {
35 | // escape trailing backslash
36 | if ('\\' === substr($part, -1)) {
37 | $part .= '\\';
38 | }
39 | $quote = true;
40 | $escapedArgument .= $part;
41 | }
42 | }
43 | if ($quote) {
44 | $escapedArgument = '"' . $escapedArgument . '"';
45 | }
46 | return $escapedArgument;
47 | }
48 |
49 | /**
50 | * 验证并进行规范化Process输入。
51 | * @param string $caller
52 | * @param mixed $input
53 | * @return string
54 | * @throws \InvalidArgumentException
55 | */
56 | public static function validateInput($caller, $input)
57 | {
58 | if (null !== $input) {
59 | if (is_resource($input)) {
60 | return $input;
61 | }
62 | if (is_scalar($input)) {
63 | return (string)$input;
64 | }
65 | throw new \InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller));
66 | }
67 | return $input;
68 | }
69 |
70 | private static function isSurroundedBy($arg, $char)
71 | {
72 | return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
73 | }
74 |
75 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/process/exception/Faild.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\process\exception;
13 |
14 |
15 | use think\Process;
16 |
17 | class Failed extends \RuntimeException
18 | {
19 |
20 | private $process;
21 |
22 | public function __construct(Process $process)
23 | {
24 | if ($process->isSuccessful()) {
25 | throw new \InvalidArgumentException('Expected a failed process, but the given process was successful.');
26 | }
27 |
28 | $error = sprintf('The command "%s" failed.' . "\nExit Code: %s(%s)", $process->getCommandLine(), $process->getExitCode(), $process->getExitCodeText());
29 |
30 | if (!$process->isOutputDisabled()) {
31 | $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", $process->getOutput(), $process->getErrorOutput());
32 | }
33 |
34 | parent::__construct($error);
35 |
36 | $this->process = $process;
37 | }
38 |
39 | public function getProcess()
40 | {
41 | return $this->process;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/thinkphp/library/think/process/exception/Timeout.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\process\exception;
13 |
14 | use think\Process;
15 |
16 | class Timeout extends \RuntimeException
17 | {
18 |
19 | const TYPE_GENERAL = 1;
20 | const TYPE_IDLE = 2;
21 |
22 | private $process;
23 | private $timeoutType;
24 |
25 | public function __construct(Process $process, $timeoutType)
26 | {
27 | $this->process = $process;
28 | $this->timeoutType = $timeoutType;
29 |
30 | parent::__construct(sprintf('The process "%s" exceeded the timeout of %s seconds.', $process->getCommandLine(), $this->getExceededTimeout()));
31 | }
32 |
33 | public function getProcess()
34 | {
35 | return $this->process;
36 | }
37 |
38 | public function isGeneralTimeout()
39 | {
40 | return $this->timeoutType === self::TYPE_GENERAL;
41 | }
42 |
43 | public function isIdleTimeout()
44 | {
45 | return $this->timeoutType === self::TYPE_IDLE;
46 | }
47 |
48 | public function getExceededTimeout()
49 | {
50 | switch ($this->timeoutType) {
51 | case self::TYPE_GENERAL:
52 | return $this->process->getTimeout();
53 |
54 | case self::TYPE_IDLE:
55 | return $this->process->getIdleTimeout();
56 |
57 | default:
58 | throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/process/pipes/Pipes.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\process\pipes;
13 |
14 | abstract class Pipes
15 | {
16 |
17 | /** @var array */
18 | public $pipes = [];
19 |
20 | /** @var string */
21 | protected $inputBuffer = '';
22 | /** @var resource|null */
23 | protected $input;
24 |
25 | /** @var bool */
26 | private $blocked = true;
27 |
28 | const CHUNK_SIZE = 16384;
29 |
30 | /**
31 | * 返回用于 proc_open 描述符的数组
32 | * @return array
33 | */
34 | abstract public function getDescriptors();
35 |
36 | /**
37 | * 返回一个数组的索引由其相关的流,以防这些管道使用的临时文件的文件名。
38 | * @return string[]
39 | */
40 | abstract public function getFiles();
41 |
42 | /**
43 | * 文件句柄和管道中读取数据。
44 | * @param bool $blocking 是否使用阻塞调用
45 | * @param bool $close 是否要关闭管道,如果他们已经到达 EOF。
46 | * @return string[]
47 | */
48 | abstract public function readAndWrite($blocking, $close = false);
49 |
50 | /**
51 | * 返回当前状态如果有打开的文件句柄或管道。
52 | * @return bool
53 | */
54 | abstract public function areOpen();
55 |
56 |
57 | /**
58 | * {@inheritdoc}
59 | */
60 | public function close()
61 | {
62 | foreach ($this->pipes as $pipe) {
63 | fclose($pipe);
64 | }
65 | $this->pipes = [];
66 | }
67 |
68 | /**
69 | * 检查系统调用已被中断
70 | * @return bool
71 | */
72 | protected function hasSystemCallBeenInterrupted()
73 | {
74 | $lastError = error_get_last();
75 |
76 | return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
77 | }
78 |
79 | protected function unblock()
80 | {
81 | if (!$this->blocked) {
82 | return;
83 | }
84 |
85 | foreach ($this->pipes as $pipe) {
86 | stream_set_blocking($pipe, 0);
87 | }
88 | if (null !== $this->input) {
89 | stream_set_blocking($this->input, 0);
90 | }
91 |
92 | $this->blocked = false;
93 | }
94 | }
--------------------------------------------------------------------------------
/thinkphp/library/think/response/Json.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\response;
13 |
14 | use think\Response;
15 |
16 | class Json extends Response
17 | {
18 | // 输出参数
19 | protected $options = [
20 | 'json_encode_param' => JSON_UNESCAPED_UNICODE,
21 | ];
22 |
23 | protected $contentType = 'application/json';
24 |
25 | /**
26 | * 处理数据
27 | * @access protected
28 | * @param mixed $data 要处理的数据
29 | * @return mixed
30 | */
31 | protected function output($data)
32 | {
33 | // 返回JSON数据格式到客户端 包含状态信息
34 | $data = json_encode($data, $this->options['json_encode_param']);
35 |
36 | if ($data === false) {
37 | throw new \InvalidArgumentException(json_last_error_msg());
38 | }
39 |
40 | return $data;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/thinkphp/library/think/response/Jsonp.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\response;
13 |
14 | use think\Request;
15 | use think\Response;
16 |
17 | class Jsonp extends Response
18 | {
19 | // 输出参数
20 | protected $options = [
21 | 'var_jsonp_handler' => 'callback',
22 | 'default_jsonp_handler' => 'jsonpReturn',
23 | 'json_encode_param' => JSON_UNESCAPED_UNICODE,
24 | ];
25 |
26 | protected $contentType = 'application/javascript';
27 |
28 | /**
29 | * 处理数据
30 | * @access protected
31 | * @param mixed $data 要处理的数据
32 | * @return mixed
33 | */
34 | protected function output($data)
35 | {
36 | // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取]
37 | $var_jsonp_handler = Request::instance()->param($this->options['var_jsonp_handler'], "");
38 | $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler'];
39 |
40 | $data = json_encode($data, $this->options['json_encode_param']);
41 |
42 | if ($data === false) {
43 | throw new \InvalidArgumentException(json_last_error_msg());
44 | }
45 |
46 | $data = $handler . '(' . $data . ');';
47 | return $data;
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/thinkphp/library/think/response/Redirect.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\response;
13 |
14 | use think\Request;
15 | use think\Response;
16 | use think\Session;
17 | use think\Url;
18 |
19 | class Redirect extends Response
20 | {
21 |
22 | protected $options = [];
23 |
24 | // URL参数
25 | protected $params = [];
26 |
27 | public function __construct($data = '', $code = 302, array $header = [], array $options = [])
28 | {
29 | parent::__construct($data, $code, $header, $options);
30 | $this->cacheControl('no-cache,must-revalidate');
31 | }
32 |
33 | /**
34 | * 处理数据
35 | * @access protected
36 | * @param mixed $data 要处理的数据
37 | * @return mixed
38 | */
39 | protected function output($data)
40 | {
41 | $this->header['Location'] = $this->getTargetUrl();
42 | return;
43 | }
44 |
45 | /**
46 | * 获取跳转地址
47 | * @return string
48 | */
49 | public function getTargetUrl()
50 | {
51 | return preg_match('/^(https?:|\/)/', $this->data) ? $this->data : Url::build($this->data, $this->params);
52 | }
53 |
54 | public function params($params = [])
55 | {
56 | $this->params = $params;
57 | return $this;
58 | }
59 |
60 | /**
61 | * 记住当前url后跳转
62 | */
63 | public function remember()
64 | {
65 | Session::set('redirect_url', Request::instance()->url());
66 | }
67 |
68 | /**
69 | * 跳转到上次记住的url
70 | */
71 | public function restore()
72 | {
73 | if (Session::has('redirect_url')) {
74 | $this->data = Session::get('redirect_url');
75 | Session::delete('redirect_url');
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/thinkphp/library/think/response/View.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\response;
13 |
14 | use think\Config;
15 | use think\Response;
16 | use think\View as ViewTemplate;
17 |
18 | class View extends Response
19 | {
20 | // 输出参数
21 | protected $options = [];
22 | protected $vars = [];
23 | protected $replace = [];
24 | protected $contentType = 'text/html';
25 |
26 | /**
27 | * 处理数据
28 | * @access protected
29 | * @param mixed $data 要处理的数据
30 | * @return mixed
31 | */
32 | protected function output($data)
33 | {
34 | // 渲染模板输出
35 | return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
36 | ->fetch($data, $this->vars, $this->replace);
37 | }
38 |
39 | /**
40 | * 获取视图变量
41 | * @access public
42 | * @param string $name 模板变量
43 | * @return mixed
44 | */
45 | public function getVars($name = null)
46 | {
47 | if (is_null($name)) {
48 | return $this->vars;
49 | } else {
50 | return isset($this->vars[$name]) ? $this->vars[$name] : null;
51 | }
52 | }
53 |
54 | /**
55 | * 模板变量赋值
56 | * @access public
57 | * @param mixed $name 变量名
58 | * @param mixed $value 变量值
59 | * @return $this
60 | */
61 | public function assign($name, $value = '')
62 | {
63 | if (is_array($name)) {
64 | $this->vars = array_merge($this->vars, $name);
65 | return $this;
66 | } else {
67 | $this->vars[$name] = $value;
68 | }
69 | return $this;
70 | }
71 |
72 | /**
73 | * 视图内容替换
74 | * @access public
75 | * @param string|array $content 被替换内容(支持批量替换)
76 | * @param string $replace 替换内容
77 | * @return $this
78 | */
79 | public function replace($content, $replace = '')
80 | {
81 | if (is_array($content)) {
82 | $this->replace = array_merge($this->replace, $content);
83 | } else {
84 | $this->replace[$content] = $replace;
85 | }
86 | return $this;
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/thinkphp/library/think/response/Xml.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\response;
13 |
14 | use think\Response;
15 |
16 | class Xml extends Response
17 | {
18 | // 输出参数
19 | protected $options = [
20 | // 根节点名
21 | 'root_node' => 'think',
22 | // 根节点属性
23 | 'root_attr' => '',
24 | //数字索引的子节点名
25 | 'item_node' => 'item',
26 | // 数字索引子节点key转换的属性名
27 | 'item_key' => 'id',
28 | // 数据编码
29 | 'encoding' => 'utf-8',
30 | ];
31 |
32 | protected $contentType = 'text/xml';
33 |
34 | /**
35 | * 处理数据
36 | * @access protected
37 | * @param mixed $data 要处理的数据
38 | * @return mixed
39 | */
40 | protected function output($data)
41 | {
42 | // XML数据转换
43 | return $this->xmlEncode($data, $this->options['root_node'], $this->options['item_node'], $this->options['root_attr'], $this->options['item_key'], $this->options['encoding']);
44 | }
45 |
46 | /**
47 | * XML编码
48 | * @param mixed $data 数据
49 | * @param string $root 根节点名
50 | * @param string $item 数字索引的子节点名
51 | * @param string $attr 根节点属性
52 | * @param string $id 数字索引子节点key转换的属性名
53 | * @param string $encoding 数据编码
54 | * @return string
55 | */
56 | protected function xmlEncode($data, $root, $item, $attr, $id, $encoding)
57 | {
58 | if (is_array($attr)) {
59 | $array = [];
60 | foreach ($attr as $key => $value) {
61 | $array[] = "{$key}=\"{$value}\"";
62 | }
63 | $attr = implode(' ', $array);
64 | }
65 | $attr = trim($attr);
66 | $attr = empty($attr) ? '' : " {$attr}";
67 | $xml = "";
68 | $xml .= "<{$root}{$attr}>";
69 | $xml .= $this->dataToXml($data, $item, $id);
70 | $xml .= "{$root}>";
71 | return $xml;
72 | }
73 |
74 | /**
75 | * 数据XML编码
76 | * @param mixed $data 数据
77 | * @param string $item 数字索引时的节点名称
78 | * @param string $id 数字索引key转换为的属性名
79 | * @return string
80 | */
81 | protected function dataToXml($data, $item, $id)
82 | {
83 | $xml = $attr = '';
84 | foreach ($data as $key => $val) {
85 | if (is_numeric($key)) {
86 | $id && $attr = " {$id}=\"{$key}\"";
87 | $key = $item;
88 | }
89 | $xml .= "<{$key}{$attr}>";
90 | $xml .= (is_array($val) || is_object($val)) ? $this->dataToXml($val, $item, $id) : $val;
91 | $xml .= "{$key}>";
92 | }
93 | return $xml;
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/thinkphp/library/think/session/driver/Memcache.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\session\driver;
13 |
14 | use SessionHandler;
15 | use think\Exception;
16 |
17 | class Memcache extends SessionHandler
18 | {
19 | protected $handler = null;
20 | protected $config = [
21 | 'host' => '127.0.0.1', // memcache主机
22 | 'port' => 1121, // memcache端口
23 | 'expire' => 3600, // session有效期
24 | 'timeout' => 0, // 连接超时时间(单位:毫秒)
25 | 'persistent' => true, // 长连接
26 | 'session_name' => '', // memcache key前缀
27 | ];
28 |
29 | public function __construct($config = [])
30 | {
31 | $this->config = array_merge($this->config, $config);
32 | }
33 |
34 | /**
35 | * 打开Session
36 | * @access public
37 | * @param string $savePath
38 | * @param mixed $sessName
39 | */
40 | public function open($savePath, $sessName)
41 | {
42 | // 检测php环境
43 | if (!extension_loaded('memcache')) {
44 | throw new Exception('not support:memcache');
45 | }
46 | $this->handler = new \Memcache;
47 | // 支持集群
48 | $hosts = explode(',', $this->config['host']);
49 | $ports = explode(',', $this->config['port']);
50 | if (empty($ports[0])) {
51 | $ports[0] = 11211;
52 | }
53 | // 建立连接
54 | foreach ((array) $hosts as $i => $host) {
55 | $port = isset($ports[$i]) ? $ports[$i] : $ports[0];
56 | $this->config['timeout'] > 0 ?
57 | $this->handler->addServer($host, $port, $this->config['persistent'], 1, $this->config['timeout']) :
58 | $this->handler->addServer($host, $port, $this->config['persistent'], 1);
59 | }
60 | return true;
61 | }
62 |
63 | /**
64 | * 关闭Session
65 | * @access public
66 | */
67 | public function close()
68 | {
69 | $this->gc(ini_get('session.gc_maxlifetime'));
70 | $this->handler->close();
71 | $this->handler = null;
72 | return true;
73 | }
74 |
75 | /**
76 | * 读取Session
77 | * @access public
78 | * @param string $sessID
79 | */
80 | public function read($sessID)
81 | {
82 | return $this->handler->get($this->config['session_name'] . $sessID);
83 | }
84 |
85 | /**
86 | * 写入Session
87 | * @access public
88 | * @param string $sessID
89 | * @param String $sessData
90 | */
91 | public function write($sessID, $sessData)
92 | {
93 | return $this->handler->set($this->config['session_name'] . $sessID, $sessData, 0, $this->config['expire']);
94 | }
95 |
96 | /**
97 | * 删除Session
98 | * @access public
99 | * @param string $sessID
100 | */
101 | public function destroy($sessID)
102 | {
103 | return $this->handler->delete($this->config['session_name'] . $sessID);
104 | }
105 |
106 | /**
107 | * Session 垃圾回收
108 | * @access public
109 | * @param string $sessMaxLifeTime
110 | */
111 | public function gc($sessMaxLifeTime)
112 | {
113 | return true;
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/thinkphp/library/think/session/driver/Memcached.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\session\driver;
13 |
14 | use SessionHandler;
15 | use think\Exception;
16 |
17 | class Memcached extends SessionHandler
18 | {
19 | protected $handler = null;
20 | protected $config = [
21 | 'host' => '127.0.0.1', // memcache主机
22 | 'port' => 1121, // memcache端口
23 | 'expire' => 3600, // session有效期
24 | 'timeout' => 0, // 连接超时时间(单位:毫秒)
25 | 'session_name' => '', // memcache key前缀
26 | 'username' => '', //账号
27 | 'password' => '', //密码
28 | ];
29 |
30 | public function __construct($config = [])
31 | {
32 | $this->config = array_merge($this->config, $config);
33 | }
34 |
35 | /**
36 | * 打开Session
37 | * @access public
38 | * @param string $savePath
39 | * @param mixed $sessName
40 | */
41 | public function open($savePath, $sessName)
42 | {
43 | // 检测php环境
44 | if (!extension_loaded('memcached')) {
45 | throw new Exception('not support:memcached');
46 | }
47 | $this->handler = new \Memcached;
48 | // 设置连接超时时间(单位:毫秒)
49 | if ($this->config['timeout'] > 0) {
50 | $this->handler->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->config['timeout']);
51 | }
52 | // 支持集群
53 | $hosts = explode(',', $this->config['host']);
54 | $ports = explode(',', $this->config['port']);
55 | if (empty($ports[0])) {
56 | $ports[0] = 11211;
57 | }
58 | // 建立连接
59 | $servers = [];
60 | foreach ((array) $hosts as $i => $host) {
61 | $servers[] = [$host, (isset($ports[$i]) ? $ports[$i] : $ports[0]), 1];
62 | }
63 | $this->handler->addServers($servers);
64 | if('' != $this->config['username']){
65 | $this->handler->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
66 | $this->handler->setSaslAuthData($this->config['username'], $this->config['password']);
67 | }
68 | return true;
69 | }
70 |
71 | /**
72 | * 关闭Session
73 | * @access public
74 | */
75 | public function close()
76 | {
77 | $this->gc(ini_get('session.gc_maxlifetime'));
78 | $this->handler->quit();
79 | $this->handler = null;
80 | return true;
81 | }
82 |
83 | /**
84 | * 读取Session
85 | * @access public
86 | * @param string $sessID
87 | */
88 | public function read($sessID)
89 | {
90 | return $this->handler->get($this->config['session_name'] . $sessID);
91 | }
92 |
93 | /**
94 | * 写入Session
95 | * @access public
96 | * @param string $sessID
97 | * @param String $sessData
98 | */
99 | public function write($sessID, $sessData)
100 | {
101 | return $this->handler->set($this->config['session_name'] . $sessID, $sessData, $this->config['expire']);
102 | }
103 |
104 | /**
105 | * 删除Session
106 | * @access public
107 | * @param string $sessID
108 | */
109 | public function destroy($sessID)
110 | {
111 | return $this->handler->delete($this->config['session_name'] . $sessID);
112 | }
113 |
114 | /**
115 | * Session 垃圾回收
116 | * @access public
117 | * @param string $sessMaxLifeTime
118 | */
119 | public function gc($sessMaxLifeTime)
120 | {
121 | return true;
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/thinkphp/library/think/session/driver/Redis.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\session\driver;
13 |
14 | use SessionHandler;
15 | use think\Exception;
16 |
17 | class Redis extends SessionHandler
18 | {
19 | /** @var \Redis */
20 | protected $handler = null;
21 | protected $config = [
22 | 'host' => '127.0.0.1', // redis主机
23 | 'port' => 6379, // redis端口
24 | 'password' => '', // 密码
25 | 'expire' => 3600, // 有效期(秒)
26 | 'timeout' => 0, // 超时时间(秒)
27 | 'persistent' => true, // 是否长连接
28 | 'session_name' => '', // sessionkey前缀
29 | ];
30 |
31 | public function __construct($config = [])
32 | {
33 | $this->config = array_merge($this->config, $config);
34 | }
35 |
36 | /**
37 | * 打开Session
38 | * @access public
39 | * @param string $savePath
40 | * @param mixed $sessName
41 | * @return bool
42 | * @throws Exception
43 | */
44 | public function open($savePath, $sessName)
45 | {
46 | // 检测php环境
47 | if (!extension_loaded('redis')) {
48 | throw new Exception('not support:redis');
49 | }
50 | $this->handler = new \Redis;
51 |
52 | // 建立连接
53 | $func = $this->config['persistent'] ? 'pconnect' : 'connect';
54 | $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']);
55 |
56 | if ('' != $this->config['password']) {
57 | $this->handler->auth($this->config['password']);
58 | }
59 | return true;
60 | }
61 |
62 | /**
63 | * 关闭Session
64 | * @access public
65 | */
66 | public function close()
67 | {
68 | $this->gc(ini_get('session.gc_maxlifetime'));
69 | $this->handler->close();
70 | $this->handler = null;
71 | return true;
72 | }
73 |
74 | /**
75 | * 读取Session
76 | * @access public
77 | * @param string $sessID
78 | * @return bool|string
79 | */
80 | public function read($sessID)
81 | {
82 | return $this->handler->get($this->config['session_name'] . $sessID);
83 | }
84 |
85 | /**
86 | * 写入Session
87 | * @access public
88 | * @param string $sessID
89 | * @param String $sessData
90 | * @return bool
91 | */
92 | public function write($sessID, $sessData)
93 | {
94 | if ($this->config['expire'] > 0) {
95 | return $this->handler->setex($this->config['session_name'] . $sessID, $this->config['expire'], $sessData);
96 | } else {
97 | return $this->handler->set($this->config['session_name'] . $sessID, $sessData);
98 | }
99 | }
100 |
101 | /**
102 | * 删除Session
103 | * @access public
104 | * @param string $sessID
105 | * @return bool|void
106 | */
107 | public function destroy($sessID)
108 | {
109 | $this->handler->delete($this->config['session_name'] . $sessID);
110 | }
111 |
112 | /**
113 | * Session 垃圾回收
114 | * @access public
115 | * @param string $sessMaxLifeTime
116 | * @return bool
117 | */
118 | public function gc($sessMaxLifeTime)
119 | {
120 | return true;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/thinkphp/library/think/template/driver/File.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\template\driver;
13 |
14 | use think\Exception;
15 |
16 | class File
17 | {
18 | /**
19 | * 写入编译缓存
20 | * @param string $cacheFile 缓存的文件名
21 | * @param string $content 缓存的内容
22 | * @return void|array
23 | */
24 | public function write($cacheFile, $content)
25 | {
26 | // 检测模板目录
27 | $dir = dirname($cacheFile);
28 | if (!is_dir($dir)) {
29 | mkdir($dir, 0755, true);
30 | }
31 | // 生成模板缓存文件
32 | if (false === file_put_contents($cacheFile, $content)) {
33 | throw new Exception('cache write error:' . $cacheFile, 11602);
34 | }
35 | }
36 |
37 | /**
38 | * 读取编译编译
39 | * @param string $cacheFile 缓存的文件名
40 | * @param array $vars 变量数组
41 | * @return void
42 | */
43 | public function read($cacheFile, $vars = [])
44 | {
45 | if (!empty($vars) && is_array($vars)) {
46 | // 模板阵列变量分解成为独立变量
47 | extract($vars, EXTR_OVERWRITE);
48 | }
49 | //载入模版缓存文件
50 | include $cacheFile;
51 | }
52 |
53 | /**
54 | * 检查编译缓存是否有效
55 | * @param string $cacheFile 缓存的文件名
56 | * @param int $cacheTime 缓存时间
57 | * @return boolean
58 | */
59 | public function check($cacheFile, $cacheTime)
60 | {
61 | // 缓存文件不存在, 直接返回false
62 | if (!file_exists($cacheFile)) {
63 | return false;
64 | }
65 | if (0 != $cacheTime && $_SERVER['REQUEST_TIME'] > filemtime($cacheFile) + $cacheTime) {
66 | // 缓存是否在有效期
67 | return false;
68 | }
69 | return true;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/thinkphp/library/think/view/driver/Php.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\view\driver;
13 |
14 | use think\App;
15 | use think\exception\TemplateNotFoundException;
16 | use think\Log;
17 | use think\Request;
18 |
19 | class Php
20 | {
21 | // 模板引擎参数
22 | protected $config = [
23 | // 模板起始路径
24 | 'view_path' => '',
25 | // 模板文件后缀
26 | 'view_suffix' => 'php',
27 | // 模板文件名分隔符
28 | 'view_depr' => DS,
29 | ];
30 |
31 | public function __construct($config = [])
32 | {
33 | $this->config = array_merge($this->config, $config);
34 | }
35 |
36 | /**
37 | * 检测是否存在模板文件
38 | * @access public
39 | * @param string $template 模板文件或者模板规则
40 | * @return bool
41 | */
42 | public function exists($template)
43 | {
44 | if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
45 | // 获取模板文件名
46 | $template = $this->parseTemplate($template);
47 | }
48 | return is_file($template);
49 | }
50 |
51 | /**
52 | * 渲染模板文件
53 | * @access public
54 | * @param string $template 模板文件
55 | * @param array $data 模板变量
56 | * @return void
57 | */
58 | public function fetch($template, $data = [])
59 | {
60 | if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
61 | // 获取模板文件名
62 | $template = $this->parseTemplate($template);
63 | }
64 | // 模板不存在 抛出异常
65 | if (!is_file($template)) {
66 | throw new TemplateNotFoundException('template not exists:' . $template, $template);
67 | }
68 | // 记录视图信息
69 | App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info');
70 | if (isset($data['template'])) {
71 | $__template__ = $template;
72 | extract($data, EXTR_OVERWRITE);
73 | include $__template__;
74 | } else {
75 | extract($data, EXTR_OVERWRITE);
76 | include $template;
77 | }
78 | }
79 |
80 | /**
81 | * 渲染模板内容
82 | * @access public
83 | * @param string $content 模板内容
84 | * @param array $data 模板变量
85 | * @return void
86 | */
87 | public function display($content, $data = [])
88 | {
89 | if (isset($data['content'])) {
90 | $__content__ = $content;
91 | extract($data, EXTR_OVERWRITE);
92 | eval('?>' . $__content__);
93 | } else {
94 | extract($data, EXTR_OVERWRITE);
95 | eval('?>' . $content);
96 | }
97 | }
98 |
99 | /**
100 | * 自动定位模板文件
101 | * @access private
102 | * @param string $template 模板文件规则
103 | * @return string
104 | */
105 | private function parseTemplate($template)
106 | {
107 | if (empty($this->config['view_path'])) {
108 | $this->config['view_path'] = App::$modulePath . 'view' . DS;
109 | }
110 |
111 | if (strpos($template, '@')) {
112 | list($module, $template) = explode('@', $template);
113 | $path = APP_PATH . $module . DS . 'view' . DS;
114 | } else {
115 | $path = $this->config['view_path'];
116 | }
117 |
118 | // 分析模板文件规则
119 | $request = Request::instance();
120 | $controller = $request->controller();
121 | if ($controller && 0 !== strpos($template, '/')) {
122 | $depr = $this->config['view_depr'];
123 | $template = str_replace(['/', ':'], $depr, $template);
124 | if ('' == $template) {
125 | // 如果模板文件名为空 按照默认规则定位
126 | $template = str_replace('.', DS, $controller) . $depr . $request->action();
127 | } elseif (false === strpos($template, $depr)) {
128 | $template = str_replace('.', DS, $controller) . $depr . $template;
129 | }
130 | }
131 | return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.');
132 | }
133 |
134 | }
135 |
--------------------------------------------------------------------------------
/thinkphp/library/think/view/driver/Think.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think\view\driver;
13 |
14 | use think\App;
15 | use think\exception\TemplateNotFoundException;
16 | use think\Log;
17 | use think\Request;
18 | use think\Template;
19 |
20 | class Think
21 | {
22 | // 模板引擎实例
23 | private $template;
24 | // 模板引擎参数
25 | protected $config = [
26 | // 模板起始路径
27 | 'view_path' => '',
28 | // 模板文件后缀
29 | 'view_suffix' => 'html',
30 | // 模板文件名分隔符
31 | 'view_depr' => DS,
32 | // 是否开启模板编译缓存,设为false则每次都会重新编译
33 | 'tpl_cache' => true,
34 | ];
35 |
36 | public function __construct($config = [])
37 | {
38 | $this->config = array_merge($this->config, $config);
39 | if (empty($this->config['view_path'])) {
40 | $this->config['view_path'] = App::$modulePath . 'view' . DS;
41 | }
42 |
43 | $this->template = new Template($this->config);
44 | }
45 |
46 | /**
47 | * 检测是否存在模板文件
48 | * @access public
49 | * @param string $template 模板文件或者模板规则
50 | * @return bool
51 | */
52 | public function exists($template)
53 | {
54 | if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
55 | // 获取模板文件名
56 | $template = $this->parseTemplate($template);
57 | }
58 | return is_file($template);
59 | }
60 |
61 | /**
62 | * 渲染模板文件
63 | * @access public
64 | * @param string $template 模板文件
65 | * @param array $data 模板变量
66 | * @param array $config 模板参数
67 | * @return void
68 | */
69 | public function fetch($template, $data = [], $config = [])
70 | {
71 | if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
72 | // 获取模板文件名
73 | $template = $this->parseTemplate($template);
74 | }
75 | // 模板不存在 抛出异常
76 | if (!is_file($template)) {
77 | throw new TemplateNotFoundException('template not exists:' . $template, $template);
78 | }
79 | // 记录视图信息
80 | App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info');
81 | $this->template->fetch($template, $data, $config);
82 | }
83 |
84 | /**
85 | * 渲染模板内容
86 | * @access public
87 | * @param string $template 模板内容
88 | * @param array $data 模板变量
89 | * @param array $config 模板参数
90 | * @return void
91 | */
92 | public function display($template, $data = [], $config = [])
93 | {
94 | $this->template->display($template, $data, $config);
95 | }
96 |
97 | /**
98 | * 自动定位模板文件
99 | * @access private
100 | * @param string $template 模板文件规则
101 | * @return string
102 | */
103 | private function parseTemplate($template)
104 | {
105 | // 获取视图根目录
106 | if (strpos($template, '@')) {
107 | // 跨模块调用
108 | list($module, $template) = explode('@', $template);
109 | $path = APP_PATH . $module . DS . 'view' . DS;
110 | } else {
111 | // 当前视图目录
112 | $path = $this->config['view_path'];
113 | }
114 |
115 | // 分析模板文件规则
116 | $request = Request::instance();
117 | $controller = $request->controller();
118 | if ($controller && 0 !== strpos($template, '/')) {
119 | $depr = $this->config['view_depr'];
120 | $template = str_replace(['/', ':'], $depr, $template);
121 | if ('' == $template) {
122 | // 如果模板文件名为空 按照默认规则定位
123 | $template = str_replace('.', DS, $controller) . $depr . $request->action();
124 | } elseif (false === strpos($template, $depr)) {
125 | $template = str_replace('.', DS, $controller) . $depr . $template;
126 | }
127 | }
128 | return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.');
129 | }
130 |
131 | public function __call($method, $params)
132 | {
133 | return call_user_func_array([$this->template, $method], $params);
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/thinkphp/library/traits/model/SoftDelete.php:
--------------------------------------------------------------------------------
1 | data[static::$deleteTime])) {
16 | return true;
17 | }
18 | return false;
19 | }
20 |
21 | /**
22 | * 查询软删除数据
23 | * @access public
24 | * @return \think\db\Query
25 | */
26 | public static function withTrashed()
27 | {
28 | $model = new static();
29 | return $model->db();
30 | }
31 |
32 | /**
33 | * 只查询软删除数据
34 | * @access public
35 | * @return \think\db\Query
36 | */
37 | public static function onlyTrashed()
38 | {
39 | $model = new static();
40 | return $model->db()->where(static::$deleteTime, 'exp', 'is not null');
41 | }
42 |
43 | /**
44 | * 删除当前的记录
45 | * @access public
46 | * @param bool $force 是否强制删除
47 | * @return integer
48 | */
49 | public function delete($force = false)
50 | {
51 | if (false === $this->trigger('before_delete', $this)) {
52 | return false;
53 | }
54 |
55 | if (static::$deleteTime && !$force) {
56 | // 软删除
57 | $name = static::$deleteTime;
58 | $this->change[] = $name;
59 | $this->data[$name] = $this->autoWriteTimestamp($name);
60 | $result = $this->isUpdate()->save();
61 | } else {
62 | $result = $this->db()->delete($this->data);
63 | }
64 |
65 | $this->trigger('after_delete', $this);
66 | return $result;
67 | }
68 |
69 | /**
70 | * 删除记录
71 | * @access public
72 | * @param mixed $data 主键列表 支持闭包查询条件
73 | * @param bool $force 是否强制删除
74 | * @return integer 成功删除的记录数
75 | */
76 | public static function destroy($data, $force = false)
77 | {
78 | $model = new static();
79 | $query = $model->db();
80 | if (is_array($data) && key($data) !== 0) {
81 | $query->where($data);
82 | $data = null;
83 | } elseif ($data instanceof \Closure) {
84 | call_user_func_array($data, [ & $query]);
85 | $data = null;
86 | }
87 | $resultSet = $query->select($data);
88 | $count = 0;
89 | if ($resultSet) {
90 | foreach ($resultSet as $data) {
91 | $result = $data->delete($force);
92 | $count += $result;
93 | }
94 | }
95 | return $count;
96 | }
97 |
98 | /**
99 | * 恢复被软删除的记录
100 | * @access public
101 | * @return integer
102 | */
103 | public function restore()
104 | {
105 | if (static::$deleteTime) {
106 | // 恢复删除
107 | $name = static::$deleteTime;
108 | $this->change[] = $name;
109 | $this->data[$name] = null;
110 | return $this->isUpdate()->save();
111 | }
112 | return false;
113 | }
114 |
115 | /**
116 | * 查询默认不包含软删除数据
117 | * @access protected
118 | * @return void
119 | */
120 | protected static function base($query)
121 | {
122 | if (static::$deleteTime) {
123 | $query->where(static::$deleteTime, 'null');
124 | }
125 | }
126 |
127 | }
128 |
--------------------------------------------------------------------------------
/thinkphp/library/traits/think/Instance.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace traits\think;
13 |
14 | use \think\Exception;
15 |
16 | trait Instance
17 | {
18 | protected static $instance = null;
19 |
20 | /**
21 | * @param array $options
22 | * @return static
23 | */
24 | public static function instance($options = [])
25 | {
26 | if (is_null(self::$instance)) {
27 | self::$instance = new self($options);
28 | }
29 | return self::$instance;
30 | }
31 |
32 | // 静态调用
33 | public static function __callStatic($method, $params)
34 | {
35 | if (is_null(self::$instance)) {
36 | self::$instance = new self();
37 | }
38 | $call = substr($method, 1);
39 | if (0 === strpos($method, '_') && is_callable([self::$instance, $call])) {
40 | return call_user_func_array([self::$instance, $call], $params);
41 | } else {
42 | throw new Exception("method not exists:" . $method);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/thinkphp/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phper-hard/tp5-restful/e9a7bc6635f0f3cff5a215464cf674ea1100c958/thinkphp/logo.png
--------------------------------------------------------------------------------
/thinkphp/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 | ./tests/thinkphp/
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | ./
23 |
24 | tests
25 | vendor
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/thinkphp/start.php:
--------------------------------------------------------------------------------
1 |
10 | // +----------------------------------------------------------------------
11 |
12 | namespace think;
13 |
14 | // ThinkPHP 引导文件
15 | // 加载基础文件
16 | require __DIR__ . '/base.php';
17 | // 执行应用
18 | App::run()->send();
19 |
--------------------------------------------------------------------------------
/thinkphp/tpl/default_index.tpl:
--------------------------------------------------------------------------------
1 | *{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px } :)
ThinkPHP V5
十年磨一剑 - 为API开发设计的高性能框架
[ V5.0 版本由 七牛云 独家赞助发布 ] ';
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/thinkphp/tpl/dispatch_jump.tpl:
--------------------------------------------------------------------------------
1 | {__NOLAYOUT__}
2 |
3 |
4 |
5 | 跳转提示
6 |
16 |
17 |
18 |
19 |
20 |
21 |
:)
22 |
23 |
24 |
25 |
:(
26 |
27 |
28 |
29 |
30 |
31 | 页面自动 跳转 等待时间:
32 |
33 |
34 |
47 |
48 |
49 |
--------------------------------------------------------------------------------