Merge branch 'v5.0.0dev' of https://gitee.com/ZhongBangKeJi/CRMEB into v5.0.0dev

This commit is contained in:
From-wh 2023-04-11 16:54:26 +08:00
commit a788ecb60d
287 changed files with 1843 additions and 12786 deletions

View File

@ -16,7 +16,9 @@ namespace app\adminapi\controller\v1\setting;
use app\adminapi\controller\AuthController;
use app\services\system\SystemCrudServices;
use app\services\system\SystemMenusServices;
use think\facade\App;
use think\helper\Str;
/**
* Class SystemCrud
@ -39,11 +41,23 @@ class SystemCrud extends AuthController
$this->services = $services;
}
/**
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function index()
{
return app('json')->success($this->services->getList());
}
/**
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function save()
{
$data = $this->request->postMore([
@ -61,7 +75,82 @@ class SystemCrud extends AuthController
]);
$this->services->createCrud($data);
return app('json')->success('创建成功');
}
/**
* 获取创建文件的目录存放位置
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function getFilePath()
{
[$menuName, $tableName, $fromField, $columnField] = $this->request->postMore([
['menuName', ''],
['tableName', ''],
['fromField', []],
['columnField', []],
], true);
$routeName = 'crud/' . Str::snake($tableName);
$make = $this->services->makeFile($tableName, $routeName, false, [
'menuName' => $menuName,
'fromField' => $fromField,
'columnField' => $columnField,
]);
$makePath = [];
foreach ($make as $key => $item) {
$makePath[$key] = $item['path'];
}
return app('json')->success($makePath);
}
/**
* 获取tree菜单
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function getMenus()
{
return app('json')->success(app()->make(SystemMenusServices::class)
->getList(['auth_type' => 1], ['pid', 'id', 'menu_name as label', 'id as value']));
}
/**
* 获取创建表数据类型
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function columnType()
{
return app('json')->success($this->services->getTabelRule());
}
/**
* @param $id
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function delete($id)
{
if (!$id) {
return app('json')->fail('缺少参数');
}
$this->services->delete($id);
return app('json')->success('删除成功');
}
}

View File

@ -13,6 +13,7 @@ namespace app\adminapi\controller\v1\setting;
use app\adminapi\controller\AuthController;
use app\services\system\SystemMenusServices;
use app\services\system\SystemRouteServices;
use think\facade\App;
use think\facade\Route;
@ -97,6 +98,39 @@ class SystemMenus extends AuthController
}
}
/**
* 批量保存权限
* @return \think\Response
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function batchSave()
{
$menus = $this->request->post('menus', []);
if (!$menus) {
return app('json')->fail(100026);
}
$data = [];
foreach ($menus as $menu) {
if (empty($menu['menu_name'])) {
return app('json')->fail(400198);
}
$data[] = [
'methods' => $menu['method'],
'menu_name' => $menu['menu_name'],
'unique_auth' => $menu['unique_auth'] ?? '',
'api_url' => $menu['api_url'],
'pid' => $menu['path'],
];
}
$this->services->saveAll($data);
return app('json')->success(100021);
}
/**
* 获取一条菜单权限信息
* @param int $id
@ -222,25 +256,14 @@ class SystemMenus extends AuthController
public function ruleList()
{
//获取所有的路由
$this->app = app();
$this->app->route->setTestMode(true);
$this->app->route->clear();
$path = $this->app->getRootPath() . 'app' . DS . 'adminapi' . DS . 'route' . DS;
$files = is_dir($path) ? scandir($path) : [];
foreach ($files as $file) {
if (strpos($file, '.php')) {
include $path . $file;
}
}
$ruleList = $this->app->route->getRuleList();
$ruleList = app()->make(SystemRouteServices::class)->selectList(['app_name' => 'adminapi'], 'name,path,method,type,id');
$menuApiList = $this->services->getColumn(['auth_type' => 2, 'is_del' => 0], "concat(`api_url`,'_',lower(`methods`)) as rule");
if ($menuApiList) $menuApiList = array_column($menuApiList, 'rule');
$list = [];
foreach ($ruleList as $item) {
$item['rule'] = str_replace('adminapi/', '', $item['rule']);
if (!in_array($item['rule'] . '_' . $item['method'], $menuApiList)) {
$item['real_name'] = $item['option']['real_name'] ?? '';
unset($item['option']);
$item['path'] = str_replace('adminapi/', '', $item['path']);
if (!in_array($item['path'] . '_' . $item['method'], $menuApiList)) {
$item['real_name'] = $item['name'] ?? '';
$item['method'] = strtoupper($item['method']);
$list[] = $item;
}

View File

@ -101,7 +101,7 @@ class SystemRouteCate extends AuthController
*/
public function edit($id)
{
return app('json')->success($this->services->getFrom($id));
return app('json')->success($this->services->getFrom($id, $this->request->get('app_name', 'adminapi')));
}
/**

View File

@ -42,13 +42,30 @@ Route::group('agent', function () {
Route::get('config/edit_basics', 'v1.setting.SystemConfig/edit_basics')->option(['real_name' => '积分配置编辑表单']);
//积分配置保存数据
Route::post('config/save_basics', 'v1.setting.SystemConfig/save_basics')->option(['real_name' => '积分配置保存数据']);
//分销员等级资源路由
Route::resource('level', 'v1.agent.AgentLevel')->name('AgentLevelResource')->option(['real_name' => '分销员等级']);
Route::resource('level', 'v1.agent.AgentLevel')->except(['read'])->name('AgentLevel')->option([
'real_name' => [
'index' => '获取分销员等级列表',
'create' => '获取分销员等级表单',
'save' => '保存分销员等级',
'edit' => '获取修改分销员等级表单',
'update' => '修改分销员等级',
'delete' => '删除分销员等级'
]
]);
//修改分销等级状态
Route::put('level/set_status/:id/:status', 'v1.agent.AgentLevel/set_status')->name('levelSetStatus')->option(['real_name' => '修改分销等级状态']);
//分销员等级任务资源路由
Route::resource('level_task', 'v1.agent.AgentLevelTask')->name('AgentLevelTaskResource')->option(['real_name' => '分销员等级任务']);
Route::resource('level_task', 'v1.agent.AgentLevelTask')->except(['read'])->option([
'real_name' => [
'index' => '获取分销员等级任务列表',
'create' => '获取分销员等级任务表单',
'save' => '保存分销员等级任务',
'edit' => '获取修改分销员等级任务表单',
'update' => '修改分销员等级任务',
'delete' => '删除分销员等级任务'
]
]);
//修改分销任务状态
Route::put('level_task/set_status/:id/:status', 'v1.agent.AgentLevelTask/set_status')->name('levelTaskSetStatus')->option(['real_name' => '修改分销等级任务状态']);
//获取赠送分销等级表单
@ -66,10 +83,10 @@ Route::group('agent', function () {
Route::post('division/agent/save', 'v1.agent.Division/divisionAgentSave')->name('divisionAgentSave')->option(['real_name' => '事业部保存']);//代理商保存
Route::put('division/set_status/:status/:uid', 'v1.agent.Division/setDivisionStatus')->name('setDivisionStatus')->option(['real_name' => '状态切换']);//状态切换
Route::delete('division/del/:type/:uid', 'v1.agent.Division/delDivision')->name('delDivision')->option(['real_name' => '删除代理商']);//状态切换
Route::get('division/agent_apply/list','v1.agent.Division/AdminApplyList')->name('AdminApplyList')->option(['real_name'=>'代理商申请列表']);//代理商申请列表
Route::get('division/examine_apply/:id/:type','v1.agent.Division/examineApply')->name('examineApply')->option(['real_name'=>'审核表单']);//审核表单
Route::post('division/apply_agent/save','v1.agent.Division/applyAgentSave')->name('applyAgentSave')->option(['real_name'=>'提交审核']);//提交审核
Route::delete('division/del_apply/:id','v1.agent.Division/delApply')->name('delApply')->option(['real_name'=>'删除审核']);//删除审核
Route::get('division/agent_apply/list', 'v1.agent.Division/AdminApplyList')->name('AdminApplyList')->option(['real_name' => '代理商申请列表']);//代理商申请列表
Route::get('division/examine_apply/:id/:type', 'v1.agent.Division/examineApply')->name('examineApply')->option(['real_name' => '审核表单']);//审核表单
Route::post('division/apply_agent/save', 'v1.agent.Division/applyAgentSave')->name('applyAgentSave')->option(['real_name' => '提交审核']);//提交审核
Route::delete('division/del_apply/:id', 'v1.agent.Division/delApply')->name('delApply')->option(['real_name' => '删除审核']);//删除审核
})->middleware([
\app\http\middleware\AllowOriginMiddleware::class,

View File

@ -15,7 +15,16 @@ use think\facade\Route;
*/
Route::group('app', function () {
//小程序模板资源路由
Route::resource('routine', 'v1.application.routine.RoutineTemplate')->name('RoutineResource')->option(['real_name' => '小程序订阅消息']);
Route::resource('routine', 'v1.application.routine.RoutineTemplate')->except(['read'])->option([
'real_name' => [
'index' => '获取小程序订阅消息列表',
'create' => '获取小程序订阅消息表单',
'save' => '保存小程序订阅消息',
'edit' => '获取修改小程序订阅消息表单',
'update' => '修改小程序订阅消息',
'delete' => '删除小程序订阅消息'
]
]);
//一键同步订阅消息
Route::get('routine/syncSubscribe', 'v1.application.routine.RoutineTemplate/syncSubscribe')->name('syncSubscribe')->option(['real_name' => '一键同步订阅消息']);
//一键同步微信模版消息消息
@ -27,7 +36,16 @@ Route::group('app', function () {
//保存菜单
Route::post('wechat/menu', 'v1.application.wechat.menus/save')->option(['real_name' => '保存微信公众号菜单']);
//微信模板消息资源路由
Route::resource('wechat/template', 'v1.application.wechat.WechatTemplate')->name('WechatTemplateResource')->option(['real_name' => '公众号模版消息']);
Route::resource('wechat/template', 'v1.application.wechat.WechatTemplate')->except(['read'])->option([
'real_name' => [
'index' => '获取公众号模版消息列表',
'create' => '获取公众号模版消息表单',
'save' => '保存公众号模版消息',
'edit' => '获取修改公众号模版消息表单',
'update' => '修改公众号模版消息',
'delete' => '删除公众号模版消息'
]
]);
//微信模板消息修改状态
Route::put('wechat/template/set_status/:id/:status', 'v1.application.wechat.WechatTemplate/set_status')->name('WechatTemplateSetStatus')->option(['real_name' => '修改关键字回复状态']);
//关注回复
@ -78,11 +96,36 @@ Route::group('app', function () {
/** 客服相关 */
//客服反馈接口
Route::resource('feedback', 'v1.kefu.StoreServiceFeedback')->only(['index', 'delete', 'update', 'edit'])->option(['real_name' => '用户反馈']);
Route::resource('feedback', 'v1.kefu.StoreServiceFeedback')->only(['index', 'delete', 'update', 'edit'])->option([
'real_name' => [
'index' => '获取用户反馈列表',
'edit' => '获取修改用户反馈表单',
'update' => '修改用户反馈',
'delete' => '删除用户反馈'
]
]);
//话术接口
Route::resource('wechat/speechcraft', 'v1.kefu.StoreServiceSpeechcraft')->option(['real_name' => '客服话术']);
Route::resource('wechat/speechcraft', 'v1.kefu.StoreServiceSpeechcraft')->except(['read'])->option([
'real_name' => [
'index' => '获取客服话术列表',
'create' => '获取客服话术表单',
'save' => '保存客服话术',
'edit' => '获取修改客服话术表单',
'update' => '修改客服话术',
'delete' => '删除客服话术'
]
]);
//话术分类接口
Route::resource('wechat/speechcraftcate', 'v1.kefu.StoreServiceSpeechcraftCate')->option(['real_name' => '客服话术分类']);
Route::resource('wechat/speechcraftcate', 'v1.kefu.StoreServiceSpeechcraftCate')->except(['read'])->option([
'real_name' => [
'index' => '获取客服话术分类列表',
'create' => '获取客服话术分类表单',
'save' => '保存客服话术分类',
'edit' => '获取修改客服话术分类表单',
'update' => '修改客服话术分类',
'delete' => '删除客服话术分类'
]
]);
//客服列表
Route::get('wechat/kefu', 'v1.kefu.StoreService/index')->option(['real_name' => '客服列表']);
//客服登录

View File

@ -15,13 +15,31 @@ use think\facade\Route;
*/
Route::group('cms', function () {
//文章资源路由
Route::resource('cms', 'v1.cms.Article')->name('ArticleResource')->option(['real_name' => '文章']);
Route::resource('cms', 'v1.cms.Article')->except(['read'])->option([
'real_name' => [
'index' => '获取文章列表',
'create' => '获取文章表单',
'save' => '保存文章',
'edit' => '获取修改文章表单',
'update' => '修改文章',
'delete' => '删除文章'
]
]);
//关联商品
Route::put('cms/relation/:id', 'v1.cms.Article/relation')->name('Relation')->option(['real_name' => '文章关联商品']);
//取消关联
Route::put('cms/unrelation/:id', 'v1.cms.Article/unrelation')->name('UnRelation')->option(['real_name' => '取消文章关联商品']);
//文章分类资源路由
Route::resource('category', 'v1.cms.ArticleCategory')->name('ArticleCategoryResource')->option(['real_name' => '文章分类']);
Route::resource('category', 'v1.cms.ArticleCategory')->except(['read'])->option([
'real_name' => [
'index' => '获取文章分类列表',
'create' => '获取文章分类表单',
'save' => '保存文章分类',
'edit' => '获取修改文章分类表单',
'update' => '修改文章分类',
'delete' => '删除文章分类'
]
]);
//修改状态
Route::put('category/set_status/:id/:status', 'v1.cms.ArticleCategory/set_status')->name('CategoryStatus')->option(['real_name' => '修改文章分类状态']);
//分类列表

View File

@ -27,7 +27,17 @@ Route::group('file', function () {
//上传图片
Route::post('upload/[:upload_type]', 'v1.file.SystemAttachment/upload')->option(['real_name' => '上传图片', 'is_common' => true]);
//附件分类管理资源路由
Route::resource('category', 'v1.file.SystemAttachmentCategory')->option(['real_name' => '附件分类管理', 'is_common' => true]);
Route::resource('category', 'v1.file.SystemAttachmentCategory')->except(['read'])->option([
'real_name' => [
'index' => '获取附件分类管理列表',
'create' => '获取附件分类管理表单',
'save' => '保存附件分类管理',
'edit' => '获取修改附件分类管理表单',
'update' => '修改附件分类管理',
'delete' => '删除附件分类管理'
],
'is_common' => true
]);
//获取上传类型
Route::get('upload_type', 'v1.file.SystemAttachment/uploadType')->option(['real_name' => '上传类型', 'is_common' => true]);
//分片上传本地视频

View File

@ -15,7 +15,16 @@ use think\facade\Route;
*/
Route::group('freight', function () {
//物流公司资源路由
Route::resource('express', 'v1.freight.Express')->name('ExpressResource')->option(['real_name' => '物流公司']);
Route::resource('express', 'v1.freight.Express')->except(['read'])->name('ExpressResource')->option([
'real_name' => [
'index' => '获取物流公司列表',
'create' => '获取物流公司表单',
'save' => '保存物流公司',
'edit' => '获取修改物流公司表单',
'update' => '修改物流公司',
'delete' => '删除物流公司'
],
]);
//修改状态
Route::put('express/set_status/:id/:status', 'v1.freight.Express/set_status')->option(['real_name' => '修改物流公司状态']);
//同步物流快递公司

View File

@ -182,12 +182,14 @@ Route::group('marketing', function () {
Route::post('lottery/record/deliver', 'v1.marketing.lottery.LuckLotteryRecord/deliver')->option(['real_name' => '抽奖中奖发货、备注处理']);
//积分记录
Route::get('point_record', 'v1.marketing.integral.StorePointRecord/pointRecord')->option(['read_name' => '积分记录列表']);
Route::post('point_record/remark/:id', 'v1.marketing.integral.StorePointRecord/pointRecordRemark')->option(['read_name' => '积分记录列表备注']);
Route::get('point/get_basic', 'v1.marketing.integral.StorePointRecord/getBasic')->option(['read_name' => '积分统计基本信息']);
Route::get('point/get_trend', 'v1.marketing.integral.StorePointRecord/getTrend')->option(['read_name' => '积分统计趋势图']);
Route::get('point/get_channel', 'v1.marketing.integral.StorePointRecord/getChannel')->option(['read_name' => '积分来源统计']);
Route::get('point/get_type', 'v1.marketing.integral.StorePointRecord/getType')->option(['read_name' => '积分消耗统计']);
Route::get('point_record', 'v1.marketing.integral.StorePointRecord/pointRecord')->option(['real_name' => '积分记录列表']);
Route::post('point_record/remark/:id', 'v1.marketing.integral.StorePointRecord/pointRecordRemark')->option(['real_name' => '积分记录列表备注']);
Route::get('point/get_basic', 'v1.marketing.integral.StorePointRecord/getBasic')->option(['real_name' => '积分统计基本信息']);
Route::get('point/get_trend', 'v1.marketing.integral.StorePointRecord/getTrend')->option(['real_name' => '积分统计趋势图']);
//积分来源统计
Route::get('point/get_channel', 'v1.marketing.integral.StorePointRecord/getChannel')->option(['real_name' => '积分来源统计']);
//积分消耗统计
Route::get('point/get_type', 'v1.marketing.integral.StorePointRecord/getType')->option(['real_name' => '积分消耗统计']);
})->middleware([
\app\http\middleware\AllowOriginMiddleware::class,

View File

@ -16,7 +16,16 @@ use think\facade\Route;
Route::group('setting', function () {
//管理员资源路由
Route::resource('admin', 'v1.setting.SystemAdmin')->except(['read'])->option(['real_name' => '管理员']);
Route::resource('admin', 'v1.setting.SystemAdmin')->except(['read'])->option([
'real_name' => [
'index' => '获取管理员列表',
'create' => '获取管理员表单',
'save' => '保存管理员',
'edit' => '获取修改管理员表单',
'update' => '修改管理员',
'delete' => '删除管理员'
]
]);
//退出登陆
Route::get('admin/logout', 'v1.setting.SystemAdmin/logout')->name('SystemAdminLogout')->option(['real_name' => '退出登陆']);
//修改状态
@ -27,8 +36,20 @@ Route::group('setting', function () {
Route::put('update_admin', 'v1.setting.SystemAdmin/update_admin')->name('SystemAdminUpdateAdmin')->option(['real_name' => '修改当前管理员信息']);
//设置文件管理密码
Route::put('set_file_password', 'v1.setting.SystemAdmin/set_file_password')->name('SystemAdminSetFilePassword')->option(['real_name' => '设置当前文件管理密码']);
//批量保存权限
Route::post('menus/batch', 'v1.setting.SystemMenus/batchSave')->name('SystemMenusBatchSave')->option(['real_name' => '批量保存权限']);
//权限菜单资源路由
Route::resource('menus', 'v1.setting.SystemMenus')->option(['real_name' => '权限菜单']);
Route::resource('menus', 'v1.setting.SystemMenus')->option([
'real_name' => [
'index' => '获取权限菜单列表',
'create' => '获取权限菜单表单',
'save' => '保存权限菜单',
'edit' => '获取修改权限菜单表单',
'read' => '查看权限菜单信息',
'update' => '修改权限菜单',
'delete' => '删除权限菜单'
],
]);
//未添加的权限规则列表
Route::get('ruleList', 'v1.setting.SystemMenus/ruleList')->option(['real_name' => '未添加的权限规则列表']);
//修改显示
@ -46,11 +67,29 @@ Route::group('setting', function () {
//删除身份
Route::delete('role/:id', 'v1.setting.SystemRole/delete')->option(['real_name' => '删除管理员身份']);
//配置分类资源路由
Route::resource('config_class', 'v1.setting.SystemConfigTab')->option(['real_name' => '系统配置分类']);
Route::resource('config_class', 'v1.setting.SystemConfigTab')->except(['read'])->option([
'real_name' => [
'index' => '获取系统配置分类列表',
'create' => '获取系统配置分类表单',
'save' => '保存系统配置分类',
'edit' => '获取修改系统配置分类表单',
'update' => '修改系统配置分类',
'delete' => '删除系统配置分类'
],
]);
//修改配置分类状态
Route::put('config_class/set_status/:id/:status', 'v1.setting.SystemConfigTab/set_status')->option(['real_name' => '修改配置分类状态']);
//配置资源路由
Route::resource('config', 'v1.setting.SystemConfig')->option(['real_name' => '系统配置']);
Route::resource('config', 'v1.setting.SystemConfig')->except(['read'])->option([
'real_name' => [
'index' => '获取系统配置列表',
'create' => '获取系统配置表单',
'save' => '保存系统配置',
'edit' => '获取修改系统配置表单',
'update' => '修改系统配置',
'delete' => '删除系统配置'
]
]);
//修改配置状态
Route::put('config/set_status/:id/:status', 'v1.setting.SystemConfig/set_status')->option(['real_name' => '修改配置状态']);
//基本配置编辑表单
@ -66,11 +105,29 @@ Route::group('setting', function () {
//获取某个分类下的所有配置信息
Route::get('config_list/:tabId', 'v1.setting.SystemConfig/get_config_list')->option(['real_name' => '获取某个分类下的所有配置信息']);
//组合数据资源路由
Route::resource('group', 'v1.setting.SystemGroup')->option(['real_name' => '组合数据']);
Route::resource('group', 'v1.setting.SystemGroup')->except(['read'])->option([
'real_name' => [
'index' => '获取组合数据列表',
'create' => '获取组合数据表单',
'save' => '保存组合数据',
'edit' => '获取修改组合数据表单',
'update' => '修改组合数据',
'delete' => '删除组合数据'
]
]);
//组合数据全部
Route::get('group_all', 'v1.setting.SystemGroup/getGroup')->option(['real_name' => '组合数据全部']);
//组合数据子数据资源路由
Route::resource('group_data', 'v1.setting.SystemGroupData')->option(['real_name' => '组合数据子数据']);
Route::resource('group_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取组合数据子数据列表',
'create' => '获取组合数据子数据表单',
'save' => '保存组合数据子数据',
'edit' => '获取修改组合数据子数据表单',
'update' => '修改组合数据子数据',
'delete' => '删除组合数据子数据'
]
]);
//修改数据状态
Route::get('group_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '组合数据头部']);
//修改数据状态
@ -105,34 +162,77 @@ Route::group('setting', function () {
Route::get('get_kf_adv', 'v1.setting.SystemGroupData/getKfAdv')->option(['real_name' => '获取客服广告']);
//设置客服广告
Route::post('set_kf_adv', 'v1.setting.SystemGroupData/setKfAdv')->option(['real_name' => '设置客服广告']);
//签到天数配置资源
Route::resource('sign_data', 'v1.setting.SystemGroupData')->option(['real_name' => '签到天数配置']);
Route::resource('sign_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取签到天数配置列表',
'create' => '获取签到天数配置表单',
'save' => '保存签到天数配置',
'edit' => '获取修改签到天数配置表单',
'update' => '修改签到天数配置',
'delete' => '删除签到天数配置'
]
]);
//签到数据字段
Route::get('sign_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '签到数据头部']);
//修改签到数据状态
Route::put('sign_data/set_status/:id/:status', 'v1.setting.SystemGroupData/set_status')->option(['real_name' => '修改签到数据状态']);
//订单详情动态图配置资源
Route::resource('order_data', 'v1.setting.SystemGroupData')->option(['real_name' => '订单详情动态图配置资源']);
Route::resource('order_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取订单详情动态图列表',
'create' => '获取订单详情动态图表单',
'save' => '保存订单详情动态图',
'edit' => '获取修改订单详情动态图表单',
'update' => '修改订单详情动态图',
'delete' => '删除订单详情动态图'
]
]);
//订单数据字段
Route::get('order_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '订单数据字段']);
//订单数据状态
Route::put('order_data/set_status/:id/:status', 'v1.setting.SystemGroupData/set_status')->option(['real_name' => '订单数据状态']);
//个人中心菜单配置资源
Route::resource('usermenu_data', 'v1.setting.SystemGroupData')->option(['real_name' => '个人中心菜单']);
Route::resource('usermenu_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取个人中心菜单列表',
'create' => '获取个人中心菜单表单',
'save' => '保存个人中心菜单',
'edit' => '获取修改个人中心菜单表单',
'update' => '修改个人中心菜单',
'delete' => '删除个人中心菜单'
]
]);
//个人中心菜单数据字段
Route::get('usermenu_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '个人中心菜单数据字段']);
//个人中心菜单数据状态
Route::put('usermenu_data/set_status/:id/:status', 'v1.setting.SystemGroupData/set_status')->option(['real_name' => '个人中心菜单数据状态']);
//分享海报配置资源
Route::resource('poster_data', 'v1.setting.SystemGroupData')->option(['real_name' => '分享海报']);
Route::resource('poster_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取分享海报列表',
'create' => '获取分享海报表单',
'save' => '保存分享海报',
'edit' => '获取修改分享海报表单',
'update' => '修改分享海报',
'delete' => '删除分享海报'
]
]);
//分享海报数据字段
Route::get('poster_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '分享海报数据字段']);
//分享海报数据状态
Route::put('poster_data/set_status/:id/:status', 'v1.setting.SystemGroupData/set_status')->option(['real_name' => '分享海报数据状态']);
//秒杀配置资源
Route::resource('seckill_data', 'v1.setting.SystemGroupData')->option(['real_name' => '秒杀配置']);
Route::resource('seckill_data', 'v1.setting.SystemGroupData')->except(['read'])->option([
'real_name' => [
'index' => '获取分秒杀配置列表',
'create' => '获取秒杀配置表单',
'save' => '保存秒杀配置',
'edit' => '获取修改秒杀配置表单',
'update' => '修改秒杀配置',
'delete' => '删除秒杀配置'
]
]);
//秒杀数据字段
Route::get('seckill_data/header', 'v1.setting.SystemGroupData/header')->option(['real_name' => '秒杀数据字段']);
//秒杀数据状态

View File

@ -121,7 +121,7 @@ Route::group('system', function () {
//保存路由权限
Route::post('route/:id', 'v1.setting.SystemRoute/save')->option(['real_name' => '保存路由权限']);
//路由分类
Route::resource('route_cate', 'v1.setting.SystemRouteCate')->option([
Route::resource('route_cate', 'v1.setting.SystemRouteCate')->except(['read'])->option([
'real_name' => [
'index' => '获取路由分类列表',
'create' => '获取创建路由分类表单',
@ -131,7 +131,18 @@ Route::group('system', function () {
'delete' => '删除路由分类'
],
]);
//获取CRUD列表
Route::get('crud/column_type', 'v1.setting.SystemCrud/columnType')->option(['real_name' => '获取CRUD列表']);
//获取菜单TREE形数据
Route::get('crud/menus', 'v1.setting.SystemCrud/getMenus')->option(['real_name' => '获取菜单TREE形数据']);
//获取CRUD文件存放
Route::post('crud/file_path', 'v1.setting.SystemCrud/getFilePath')->option(['real_name' => '获取CRUD文件存放']);
//删除CRUD
Route::delete('crud/:id', 'v1.setting.SystemCrud/delete')->option(['real_name' => '删除CRUD']);
//获取CRUD列表
Route::get('crud', 'v1.setting.SystemCrud/index')->option(['real_name' => '获取CRUD列表']);
//保存生成CRUD
Route::post('crud', 'v1.setting.SystemCrud/save')->option(['real_name' => '保存生成CRUD']);
})->middleware([
\app\http\middleware\AllowOriginMiddleware::class,
\app\adminapi\middleware\AdminAuthTokenMiddleware::class,

View File

@ -15,7 +15,16 @@ use think\facade\Route;
*/
Route::group('user', function () {
//用户管理资源路由
Route::resource('user', 'v1.user.user')->option(['real_name' => '用户']);
Route::resource('user', 'v1.user.user')->except(['read'])->option([
'real_name' => [
'index' => '获取用户列表',
'create' => '获取用户表单',
'save' => '保存用户',
'edit' => '获取修改用户表单',
'update' => '修改用户',
'delete' => '删除用户'
]
]);
//添加用户保存
Route::post('user/save', 'v1.user.user/save_info')->option(['real_name' => '添加用户']);
//同步微信用户
@ -98,7 +107,16 @@ Route::group('user', function () {
//设置会员分组
Route::put('save_set_label', 'v1.user.user/save_set_label')->option(['real_name' => '保存用户标签']);
//标签分类
Route::resource('user_label_cate', 'v1.user.UserLabelCate')->option(['real_name' => '标签分类']);
Route::resource('user_label_cate', 'v1.user.UserLabelCate')->except(['read'])->option([
'real_name' => [
'index' => '获取标签分类',
'create' => '获取标签分类表单',
'save' => '保存标签分类',
'edit' => '获取修改标签分类表单',
'update' => '修改标签分类',
'delete' => '删除标签分类'
]
]);
Route::get('user_label_cate/all', 'v1.user.user_label_cate/getAll')->option(['real_name' => '获取用户标签分类全部']);
//会员卡批次列表资源

View File

@ -46,12 +46,13 @@ abstract class BaseDao
/**
* 读取数据条数
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
*/
public function count(array $where = [])
public function count(array $where = [], bool $search = true)
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
/**
@ -324,7 +325,6 @@ abstract class BaseDao
$with = [];
$otherWhere = [];
$responses = new \ReflectionClass($this->setModel());
foreach ($where as $key => $value) {
$method = 'search' . Str::studly($key) . 'Attr';
if ($responses->hasMethod($method)) {
@ -352,10 +352,29 @@ abstract class BaseDao
{
[$with, $otherWhere] = $this->getSearchData($where);
return $this->getModel()->withSearch($with, $where)->when($search, function ($query) use ($otherWhere) {
$query->where($otherWhere);
$query->where($this->filterWhere($otherWhere));
});
}
/**
* 过滤数据表中不存在的where条件字段
* @param array $where
* @return array
* @author 吴汐
* @email 442384644@qq.com
* @date 2023/04/11
*/
protected function filterWhere(array $where = [])
{
$fields = $this->getModel()->getTableFields();
foreach ($where as $key => $item) {
if (!in_array($item[0], $fields)) {
unset($where[$key]);
}
}
return $where;
}
/**
* 搜索
* @param array $where

View File

@ -65,12 +65,13 @@ class StoreCombinationDao extends BaseDao
/**
* 获取指定条件下的条数
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
*/
public function count(array $where = []): int
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
/**

View File

@ -35,11 +35,13 @@ class StoreIntegralDao extends BaseDao
/**
* 获取指定条件下的条数
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
*/
public function count(array $where = []): int
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
/**

View File

@ -89,11 +89,13 @@ class StoreIntegralOrderDao extends BaseDao
/**
* 获取订单总数
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
*/
public function count(array $where = []): int
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
/**

View File

@ -181,8 +181,17 @@ class OtherOrderDao extends BaseDao
});
}
public function count(array $where = []): int
/**
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
* @author 吴汐
* @email 442384644@qq.com
* @date 2023/04/11
*/
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
}

View File

@ -263,11 +263,13 @@ class StoreOrderDao extends BaseDao
/**
* 获取订单总数
* @param array $where
* @param bool $search
* @return int
* @throws \ReflectionException
*/
public function count(array $where = []): int
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->count();
return $this->search($where, $search)->count();
}
/**

View File

@ -28,7 +28,7 @@ class StoreProductLogDao extends BaseDao
public function getRanking($where)
{
return $this->search($where)->with('storeName')
return $this->search($where, false)->with('storeName')
->field([
'product_id',
'SUM(visit_num) as visit',
@ -47,7 +47,7 @@ class StoreProductLogDao extends BaseDao
public function getRepeats($where, $product_id)
{
return count($this->search($where)->where('type', 'pay')->where('product_id', $product_id)->field('count(pay_uid) as p')->group('pay_uid')->having('p>1')->select());
return count($this->search($where, false)->where('type', 'pay')->where('product_id', $product_id)->field('count(pay_uid) as p')->group('pay_uid')->having('p>1')->select());
}
/**

View File

@ -76,10 +76,10 @@ class SystemMenusDao extends BaseDao
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getMenusList(array $where)
public function getMenusList(array $where, array $field = ['*'])
{
$where = array_merge($where, ['is_del' => 0]);
return $this->search($where)->order('sort DESC,id ASC')->select();
return $this->search($where)->field($field)->order('sort DESC,id ASC')->select();
}
/**

View File

@ -103,10 +103,11 @@ class WechatReplyKeyDao extends BaseDao
/**
* 获取条件下的条数
* @param array $where
* @param bool $search
* @return int
*/
public function count(array $where = []): int
public function count(array $where = [], bool $search = true): int
{
return $this->search($where)->group($this->alias . '.id')->count();
return $this->search($where, $search)->group($this->alias . '.id')->count();
}
}

View File

@ -33,6 +33,7 @@ use think\Model;
* @method mixed delete($id, ?string $key = null) 删除
* @method mixed save(array $data) 保存数据
* @method mixed saveAll(array $data) 批量保存数据
* @method Model selectList(array $where, string $field = '*', int $page = 0, int $limit = 0, string $order = '', array $with = [], bool $search = false) 获取列表
* @method bool bcInc($key, string $incField, string $inc, string $keyField = null, int $acc = 2) 高精度加法
* @method bool bcDec($key, string $decField, string $dec, string $keyField = null, int $acc = 2) 高精度 减法
* @method mixed decStockIncSales(array $where, int $num, string $stock = 'stock', string $sales = 'sales') 减库存加销量

View File

@ -131,11 +131,12 @@ class ArticleServices extends BaseServices
/**
* 获取数量
* @param array $where
* @param bool $search
* @return int
*/
public function count(array $where)
public function count(array $where = [], bool $search = true): int
{
return $this->dao->count($where);
return $this->search($where, $search)->count();
}
/**获取一条数据

View File

@ -27,6 +27,7 @@ use crmeb\services\crud\ViewPages;
use crmeb\services\crud\ViewRouter;
use think\exception\ValidateException;
use think\facade\Db;
use think\helper\Str;
use think\migration\Migrator;
use Phinx\Db\Adapter\MysqlAdapter;
@ -49,6 +50,21 @@ class SystemCrudServices extends BaseServices
$this->dao = $dao;
}
/**
* @return array
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function getList()
{
[$page, $limit] = $this->getPageValue();
$list = $this->dao->selectList([], '*', $page, $limit, 'id desc');
$count = $this->dao->count();
return compact('list', 'count');
}
public function getTabelRule()
{
$adapter = app()->make(MysqlAdapter::class);
@ -90,6 +106,14 @@ class SystemCrudServices extends BaseServices
return $columns;
}
/**
* 创建
* @param array $data
* @return mixed
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/11
*/
public function createCrud(array $data)
{
$tableName = $data['tableName'];
@ -108,9 +132,8 @@ class SystemCrudServices extends BaseServices
throw new ValidateException('请先创建' . $tableName . '表');
}
//TODO 没写完
$routeName = '';
$uniqueAuth = '';
$routeName = 'crud/' . Str::snake($tableName);
$uniqueAuth = $routeName . '-index-list';
$make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
$makePath = [];
@ -133,10 +156,72 @@ class SystemCrudServices extends BaseServices
];
$menuInfo = app()->make(SystemMenusServices::class)->save($data);
//写入路由权限
//TODO 没写完
$cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
$ruleData = [
[
'path' => $routeName,
'method' => 'GET',
'name' => $data['menuName'] . '列表接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
[
'path' => $routeName . '/create',
'method' => 'GET',
'name' => $data['menuName'] . '获取创建表单接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
[
'path' => $routeName,
'method' => 'POST',
'name' => $data['menuName'] . '保存数据接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
[
'path' => $routeName . '/<id>/edit',
'method' => 'GET',
'name' => $data['menuName'] . '获取修改表单接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
[
'path' => $routeName . '/<id>',
'method' => 'PUT',
'name' => $data['menuName'] . '修改数据接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
[
'path' => $routeName . '/<id>',
'method' => 'DELETE',
'name' => $data['menuName'] . '删除数据接口',
'app_name' => 'adminapi',
'cate_id' => $cateId,
'add_time' => date('Y-m-d H:i:s')
],
];
app()->make(SystemRouteServices::class)->saveAll($ruleData);
//记录权限加入菜单表
$menuData = [];
foreach ($ruleData as $item) {
$menuData[] = [
'pid' => $menuInfo->id,
'method' => $item['method'],
'api_url' => $item['path'],
'name' => $item['name'],
'is_del' => 0,
];
}
app()->make(SystemMenusServices::class)->saveAll($menuData);
//记录crud生成
$this->dao->save([
$res = $this->dao->save([
'pid' => $data['pid'],
'name' => $data['menuName'],
'table_name' => $tableName,
@ -144,6 +229,7 @@ class SystemCrudServices extends BaseServices
'make_path' => json_encode($makePath),
'add_time' => time()
]);
return $res->toArray();
}
/**

View File

@ -89,9 +89,9 @@ class SystemMenusServices extends BaseServices
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getList(array $where)
public function getList(array $where, array $field = ['*'])
{
$menusList = $this->dao->getMenusList($where);
$menusList = $this->dao->getMenusList($where, $field);
$menusList = $this->getMenusData($menusList);
return get_tree_children($menusList);
}

View File

@ -69,9 +69,9 @@ class SystemRouteCateServices extends BaseServices
* @email 136327134@qq.com
* @date 2023/4/6
*/
public function getAllList(string $appName = 'outapi', string $field = '*')
public function getAllList(string $appName = 'outapi', string $field = '*', string $order = '')
{
$list = $this->dao->selectList(['app_name' => $appName], $field)->toArray();
$list = $this->dao->selectList(['app_name' => $appName], $field, 0, 0, $order)->toArray();
return get_tree_children($list);
}

View File

@ -68,7 +68,9 @@ class SystemRouteServices extends BaseServices
throw new ValidateException('修改的路由不存在');
}
return $routeInfo->toArray();
$routeInfo = $routeInfo->toArray();
$routeInfo['cate_tree'] = app()->make(SystemRouteCateServices::class)->getAllList($routeInfo['app_name'], '*', 'id asc,sort desc');
return $routeInfo;
}
/**
@ -119,28 +121,44 @@ class SystemRouteServices extends BaseServices
$route = $this->app->route->getRuleList();
$action_arr = ['index', 'read', 'create', 'save', 'edit', 'update', 'delete'];
foreach ($route as &$item) {
foreach ($route as $key => $item) {
$real_name = $item['option']['real_name'] ?? '';
if (is_array($real_name)) {
foreach ($action_arr as $action) {
if (Str::contains($item['route'], $action)) {
$real_name = $real_name[$action] ?? '';
foreach ($action_arr as $a) {
if (Str::contains($item['route'], $a)) {
$real_name = $real_name[$a] ?? '';
}
}
}
$item['option']['real_name'] = $real_name;
$route[$key] = $item;
$except = $item['option']['except'] ?? [];
$router = is_string($item['route']) ? explode('/', $item['route']) : [];
$action = $router[count($router) - 1] ?? null;
//去除不需要的路由
if ($except && $action && in_array($action, $except)) {
unset($route[$key]);
}
$only = $item['option']['only'] ?? [];
if ($only && $action && !in_array($action, $only)) {
unset($route[$key]);
}
}
return $route;
}
/**
* 同步路由
* 获取顶级id
* @param string $app
* @return mixed
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/6
* @date 2023/4/11
*/
public function syncRoute(string $app = 'adminapi')
public function topCateId(string $app)
{
$id = app()->make(SystemRouteCateServices::class)->value(['app_name' => $app, 'name' => '全部权限', 'pid' => 0], 'id');
if (!$id) {
@ -152,6 +170,19 @@ class SystemRouteServices extends BaseServices
]);
$id = $res->id;
}
return $id;
}
/**
* 同步路由
* @author 等风来
* @email 136327134@qq.com
* @date 2023/4/6
*/
public function syncRoute(string $app = 'adminapi')
{
$id = $this->topCateId($app);
$listAll = $this->getRouteListAll($app);
//保持新增的权限路由
$data = $this->dao->selectList(['app_name' => $app], 'path,method')->toArray();

295
crmeb/composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "7c5a944e11d96dd74471efbeddebdae8",
"content-hash": "792b4cc7488c49b6d812dda8d5c55d02",
"packages": [
{
"name": "adbario/php-dot-notation",
@ -1954,149 +1954,6 @@
],
"time": "2022-05-21T17:30:32+00:00"
},
{
"name": "league/flysystem",
"version": "1.0.61",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem.git",
"reference": "4fb13c01784a6c9f165a351e996871488ca2d8c9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem/zipball/4fb13c01784a6c9f165a351e996871488ca2d8c9",
"reference": "4fb13c01784a6c9f165a351e996871488ca2d8c9",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-fileinfo": "*",
"php": ">=5.5.9"
},
"conflict": {
"league/flysystem-sftp": "<1.0.6"
},
"require-dev": {
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7.10"
},
"suggest": {
"ext-fileinfo": "Required for MimeType",
"ext-ftp": "Allows you to use FTP server storage",
"ext-openssl": "Allows you to use FTPS server storage",
"league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2",
"league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3",
"league/flysystem-azure": "Allows you to use Windows Azure Blob storage",
"league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching",
"league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem",
"league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files",
"league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib",
"league/flysystem-webdav": "Allows you to use WebDAV storage",
"league/flysystem-ziparchive": "Allows you to use ZipArchive adapter",
"spatie/flysystem-dropbox": "Allows you to use Dropbox storage",
"srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"psr-4": {
"League\\Flysystem\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frenky.net"
}
],
"description": "Filesystem abstraction: Many filesystems, one API.",
"keywords": [
"Cloud Files",
"WebDAV",
"abstraction",
"aws",
"cloud",
"copy.com",
"dropbox",
"file systems",
"files",
"filesystem",
"filesystems",
"ftp",
"rackspace",
"remote",
"s3",
"sftp",
"storage"
],
"time": "2019-12-08T21:46:50+00:00"
},
{
"name": "league/flysystem-cached-adapter",
"version": "1.0.9",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem-cached-adapter.git",
"reference": "08ef74e9be88100807a3b92cc9048a312bf01d6f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem-cached-adapter/zipball/08ef74e9be88100807a3b92cc9048a312bf01d6f",
"reference": "08ef74e9be88100807a3b92cc9048a312bf01d6f",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"league/flysystem": "~1.0",
"psr/cache": "^1.0.0"
},
"require-dev": {
"mockery/mockery": "~0.9",
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7",
"predis/predis": "~1.0",
"tedivm/stash": "~0.12"
},
"suggest": {
"ext-phpredis": "Pure C implemented extension for PHP"
},
"type": "library",
"autoload": {
"psr-4": {
"League\\Flysystem\\Cached\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "frankdejonge",
"email": "info@frenky.net"
}
],
"description": "An adapter decorator to enable meta-data caching.",
"time": "2018-07-09T20:51:04+00:00"
},
{
"name": "lizhichao/one-sm",
"version": "1.10",
@ -2711,73 +2568,6 @@
],
"time": "2019-06-25T10:00:57+00:00"
},
{
"name": "opis/closure",
"version": "3.5.1",
"source": {
"type": "git",
"url": "https://github.com/opis/closure.git",
"reference": "93ebc5712cdad8d5f489b500c59d122df2e53969"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/opis/closure/zipball/93ebc5712cdad8d5f489b500c59d122df2e53969",
"reference": "93ebc5712cdad8d5f489b500c59d122df2e53969",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": "^5.4 || ^7.0"
},
"require-dev": {
"jeremeamia/superclosure": "^2.0",
"phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.5.x-dev"
}
},
"autoload": {
"psr-4": {
"Opis\\Closure\\": "src/"
},
"files": [
"functions.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Marius Sarca",
"email": "marius.sarca@gmail.com"
},
{
"name": "Sorin Sarca",
"email": "sarca_sorin@hotmail.com"
}
],
"description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.",
"homepage": "https://opis.io/closure",
"keywords": [
"anonymous functions",
"closure",
"function",
"serializable",
"serialization",
"serialize"
],
"time": "2019-11-29T22:36:02+00:00"
},
{
"name": "overtrue/socialite",
"version": "1.3.0",
@ -4524,16 +4314,16 @@
},
{
"name": "topthink/framework",
"version": "v6.0.3",
"version": "v6.1.2",
"source": {
"type": "git",
"url": "https://github.com/top-think/framework.git",
"reference": "b4046fb21e6163ba23a792b694162693dbe71b4b"
"reference": "67235be5b919aaaf1de5aed9839f65d8e766aca3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/top-think/framework/zipball/b4046fb21e6163ba23a792b694162693dbe71b4b",
"reference": "b4046fb21e6163ba23a792b694162693dbe71b4b",
"url": "https://api.github.com/repos/top-think/framework/zipball/67235be5b919aaaf1de5aed9839f65d8e766aca3",
"reference": "67235be5b919aaaf1de5aed9839f65d8e766aca3",
"shasum": "",
"mirrors": [
{
@ -4545,17 +4335,16 @@
"require": {
"ext-json": "*",
"ext-mbstring": "*",
"league/flysystem": "^1.0",
"league/flysystem-cached-adapter": "^1.0",
"opis/closure": "^3.1",
"php": ">=7.1.0",
"php": ">=7.2.5",
"psr/container": "~1.0",
"psr/http-message": "^1.0",
"psr/log": "~1.0",
"psr/simple-cache": "^1.0",
"topthink/think-helper": "^3.1.1",
"topthink/think-orm": "^2.0"
"topthink/think-orm": "^2.0|^3.0"
},
"require-dev": {
"guzzlehttp/psr7": "^2.1.0",
"mikey179/vfsstream": "^1.6",
"mockery/mockery": "^1.2",
"phpunit/phpunit": "^7.0"
@ -4588,7 +4377,11 @@
"orm",
"thinkphp"
],
"time": "2020-06-26T16:03:10+00:00"
"support": {
"issues": "https://github.com/top-think/framework/issues",
"source": "https://github.com/top-think/framework/tree/v6.1.2"
},
"time": "2023-02-08T02:24:01+00:00"
},
{
"name": "topthink/think-captcha",
@ -4776,6 +4569,66 @@
"description": "The ThinkPHP5 Image Package",
"time": "2016-09-29T06:05:43+00:00"
},
{
"name": "topthink/think-migration",
"version": "v3.0.4",
"source": {
"type": "git",
"url": "https://github.com/top-think/think-migration.git",
"reference": "c5880669b277762d5ff935e551bc0d5c71de6811"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/top-think/think-migration/zipball/c5880669b277762d5ff935e551bc0d5c71de6811",
"reference": "c5880669b277762d5ff935e551bc0d5c71de6811",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"topthink/framework": "^6.0",
"topthink/think-helper": "^3.0.3"
},
"require-dev": {
"fzaninotto/faker": "^1.8"
},
"suggest": {
"fzaninotto/faker": "Required to use the factory builder (^1.8)."
},
"type": "library",
"extra": {
"think": {
"services": [
"think\\migration\\Service"
]
}
},
"autoload": {
"psr-4": {
"Phinx\\": "phinx/src/Phinx",
"think\\migration\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "yunwuxin",
"email": "448901948@qq.com"
}
],
"support": {
"issues": "https://github.com/top-think/think-migration/issues",
"source": "https://github.com/top-think/think-migration/tree/v3.0.4"
},
"time": "2022-10-26T07:57:54+00:00"
},
{
"name": "topthink/think-multi-app",
"version": "v1.0.14",

View File

@ -14,6 +14,7 @@
namespace crmeb\services\pay\storage;
use app\services\pay\PayServices;
use crmeb\exceptions\AdminException;
use crmeb\exceptions\PayException;
use crmeb\services\pay\BasePay;
use crmeb\services\pay\PayInterface;
@ -115,7 +116,8 @@ class AllinPay extends BasePay implements PayInterface
*/
public function refund(string $outTradeNo, array $options = [])
{
return $this->pay->refund($options['refund_price'], $options['order_id'], $outTradeNo);
$result = $this->pay->refund($options['refund_price'], $options['order_id'], $outTradeNo);
if ($result['retcode'] != 'SUCCESS') throw new AdminException($result['retmsg']);
}
public function queryRefund(string $outTradeNo, string $outRequestNo, array $other = [])

View File

@ -103,18 +103,22 @@ class WechatPay extends BasePay implements PayInterface
$refundNo = $opt['refund_id'] ?? $outTradeNo;
$opUserId = $opt['op_user_id'] ?? null;
$type = $opt['type'] ?? 'out_trade_no';
/*仅针对老资金流商户使用
REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款
*/
/**
* 仅针对老资金流商户使用
* REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
* REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款
*/
$refundAccount = $opt['refund_account'] ?? 'REFUND_SOURCE_UNSETTLED_FUNDS';
if (isset($opt['wechat'])) {
return WechatService::refund($outTradeNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount);
$result = WechatService::refund($outTradeNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount);
if ($result['status'] != 'SUCCESS') throw new AdminException($result['status']);
} else {
if ($opt['pay_new_weixin_open']) {
return MiniProgramService::miniRefund($outTradeNo, $totalFee, $refundFee, $opt);
$result = MiniProgramService::miniRefund($outTradeNo, $totalFee, $refundFee, $opt);
if ($result['errcode'] != 0) throw new AdminException($result['errmsg']);
} else {
return MiniProgramService::refund($outTradeNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount);
$result = MiniProgramService::refund($outTradeNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount);
if ($result['status'] != 'SUCCESS') throw new AdminException($result['status']);
}
}
}

View File

@ -1 +1 @@
APP_DEBUG = true [APP] DEFAULT_TIMEZONE = Asia/Shanghai [DATABASE] TYPE = mysql HOSTNAME = #DB_HOST# HOSTPORT = #DB_PORT# USERNAME = #DB_USER# PASSWORD = '#DB_PWD#' DATABASE = #DB_NAME# PREFIX = #DB_PREFIX# CHARSET = utf8mb4 DEBUG = true [LANG] default_lang = zh-cn [CACHE] DRIVER = #CACHE_TYPE# CACHE_PREFIX = #CACHE_PREFIX# CACHE_TAG_PREFIX = #CACHE_TAG_PREFIX# [REDIS] REDIS_HOSTNAME = #RB_HOST# PORT = #RB_PORT# REDIS_PASSWORD = '#RB_PWD#' SELECT = #RB_SELECT# [QUEUE] QUEUE_NAME = #QUEUE_NAME#
APP_DEBUG = true [APP] DEFAULT_TIMEZONE = Asia/Shanghai [DATABASE] TYPE = mysql HOSTNAME = #DB_HOST# HOSTPORT = #DB_PORT# USERNAME = #DB_USER# PASSWORD = #DB_PWD# DATABASE = #DB_NAME# PREFIX = #DB_PREFIX# CHARSET = utf8mb4 DEBUG = true [LANG] default_lang = zh-cn [CACHE] DRIVER = #CACHE_TYPE# CACHE_PREFIX = #CACHE_PREFIX# CACHE_TAG_PREFIX = #CACHE_TAG_PREFIX# [REDIS] REDIS_HOSTNAME = #RB_HOST# PORT = #RB_PORT# REDIS_PASSWORD = '#RB_PWD#' SELECT = #RB_SELECT# [QUEUE] QUEUE_NAME = #QUEUE_NAME#

View File

@ -17,7 +17,6 @@ return array(
'd767e4fc2dc52fe66584ab8c6684783e' => $vendorDir . '/adbario/php-dot-notation/src/helpers.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'9b552a3cc426e3287cc811caefa3cf53' => $vendorDir . '/topthink/think-helper/src/helper.php',
'538ca81a9a966a6716601ecf48f4eaef' => $vendorDir . '/opis/closure/functions.php',
'65fec9ebcfbb3cbb4fd0d519687aea01' => $vendorDir . '/danielstjules/stringy/src/Create.php',
'abede361264e2ae69ec1eee813a101af' => $vendorDir . '/markbaker/complex/classes/src/functions/abs.php',
'21a5860fbef5be28db5ddfbc3cca67c4' => $vendorDir . '/markbaker/complex/classes/src/functions/acos.php',

View File

@ -46,15 +46,12 @@ return array(
'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet'),
'Phinx\\' => array($vendorDir . '/topthink/think-migration/phinx/src/Phinx'),
'Overtrue\\Socialite\\' => array($vendorDir . '/overtrue/socialite/src'),
'Opis\\Closure\\' => array($vendorDir . '/opis/closure/src'),
'OneSm\\' => array($vendorDir . '/lizhichao/one-sm/src'),
'OSS\\' => array($vendorDir . '/aliyuncs/oss-sdk-php/src/OSS'),
'MyCLabs\\Enum\\' => array($vendorDir . '/myclabs/php-enum/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'Matrix\\' => array($vendorDir . '/markbaker/matrix/classes/src'),
'Lizhichao\\Word\\' => array($vendorDir . '/lizhichao/word/Lib'),
'League\\Flysystem\\Cached\\' => array($vendorDir . '/league/flysystem-cached-adapter/src'),
'League\\Flysystem\\' => array($vendorDir . '/league/flysystem/src'),
'JmesPath\\' => array($vendorDir . '/mtdowling/jmespath.php/src'),
'Intervention\\Image\\' => array($vendorDir . '/intervention/image/src/Intervention/Image'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),

View File

@ -18,7 +18,6 @@ class ComposerStaticInitf16474ac994ccc25392f403933800b79
'd767e4fc2dc52fe66584ab8c6684783e' => __DIR__ . '/..' . '/adbario/php-dot-notation/src/helpers.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'9b552a3cc426e3287cc811caefa3cf53' => __DIR__ . '/..' . '/topthink/think-helper/src/helper.php',
'538ca81a9a966a6716601ecf48f4eaef' => __DIR__ . '/..' . '/opis/closure/functions.php',
'65fec9ebcfbb3cbb4fd0d519687aea01' => __DIR__ . '/..' . '/danielstjules/stringy/src/Create.php',
'abede361264e2ae69ec1eee813a101af' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/abs.php',
'21a5860fbef5be28db5ddfbc3cca67c4' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acos.php',
@ -167,7 +166,6 @@ class ComposerStaticInitf16474ac994ccc25392f403933800b79
'O' =>
array (
'Overtrue\\Socialite\\' => 19,
'Opis\\Closure\\' => 13,
'OneSm\\' => 6,
'OSS\\' => 4,
),
@ -180,8 +178,6 @@ class ComposerStaticInitf16474ac994ccc25392f403933800b79
'L' =>
array (
'Lizhichao\\Word\\' => 15,
'League\\Flysystem\\Cached\\' => 24,
'League\\Flysystem\\' => 17,
),
'J' =>
array (
@ -414,10 +410,6 @@ class ComposerStaticInitf16474ac994ccc25392f403933800b79
array (
0 => __DIR__ . '/..' . '/overtrue/socialite/src',
),
'Opis\\Closure\\' =>
array (
0 => __DIR__ . '/..' . '/opis/closure/src',
),
'OneSm\\' =>
array (
0 => __DIR__ . '/..' . '/lizhichao/one-sm/src',
@ -442,14 +434,6 @@ class ComposerStaticInitf16474ac994ccc25392f403933800b79
array (
0 => __DIR__ . '/..' . '/lizhichao/word/Lib',
),
'League\\Flysystem\\Cached\\' =>
array (
0 => __DIR__ . '/..' . '/league/flysystem-cached-adapter/src',
),
'League\\Flysystem\\' =>
array (
0 => __DIR__ . '/..' . '/league/flysystem/src',
),
'JmesPath\\' =>
array (
0 => __DIR__ . '/..' . '/mtdowling/jmespath.php/src',

View File

@ -2047,155 +2047,6 @@
],
"install-path": "../intervention/image"
},
{
"name": "league/flysystem",
"version": "1.0.61",
"version_normalized": "1.0.61.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem.git",
"reference": "4fb13c01784a6c9f165a351e996871488ca2d8c9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem/zipball/4fb13c01784a6c9f165a351e996871488ca2d8c9",
"reference": "4fb13c01784a6c9f165a351e996871488ca2d8c9",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-fileinfo": "*",
"php": ">=5.5.9"
},
"conflict": {
"league/flysystem-sftp": "<1.0.6"
},
"require-dev": {
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7.10"
},
"suggest": {
"ext-fileinfo": "Required for MimeType",
"ext-ftp": "Allows you to use FTP server storage",
"ext-openssl": "Allows you to use FTPS server storage",
"league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2",
"league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3",
"league/flysystem-azure": "Allows you to use Windows Azure Blob storage",
"league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching",
"league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem",
"league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files",
"league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib",
"league/flysystem-webdav": "Allows you to use WebDAV storage",
"league/flysystem-ziparchive": "Allows you to use ZipArchive adapter",
"spatie/flysystem-dropbox": "Allows you to use Dropbox storage",
"srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications"
},
"time": "2019-12-08T21:46:50+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\Flysystem\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frenky.net"
}
],
"description": "Filesystem abstraction: Many filesystems, one API.",
"keywords": [
"Cloud Files",
"WebDAV",
"abstraction",
"aws",
"cloud",
"copy.com",
"dropbox",
"file systems",
"files",
"filesystem",
"filesystems",
"ftp",
"rackspace",
"remote",
"s3",
"sftp",
"storage"
],
"install-path": "../league/flysystem"
},
{
"name": "league/flysystem-cached-adapter",
"version": "1.0.9",
"version_normalized": "1.0.9.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem-cached-adapter.git",
"reference": "08ef74e9be88100807a3b92cc9048a312bf01d6f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem-cached-adapter/zipball/08ef74e9be88100807a3b92cc9048a312bf01d6f",
"reference": "08ef74e9be88100807a3b92cc9048a312bf01d6f",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"league/flysystem": "~1.0",
"psr/cache": "^1.0.0"
},
"require-dev": {
"mockery/mockery": "~0.9",
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7",
"predis/predis": "~1.0",
"tedivm/stash": "~0.12"
},
"suggest": {
"ext-phpredis": "Pure C implemented extension for PHP"
},
"time": "2018-07-09T20:51:04+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\Flysystem\\Cached\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "frankdejonge",
"email": "info@frenky.net"
}
],
"description": "An adapter decorator to enable meta-data caching.",
"install-path": "../league/flysystem-cached-adapter"
},
{
"name": "lizhichao/one-sm",
"version": "1.10",
@ -2833,76 +2684,6 @@
],
"install-path": "../nesbot/carbon"
},
{
"name": "opis/closure",
"version": "3.5.1",
"version_normalized": "3.5.1.0",
"source": {
"type": "git",
"url": "https://github.com/opis/closure.git",
"reference": "93ebc5712cdad8d5f489b500c59d122df2e53969"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/opis/closure/zipball/93ebc5712cdad8d5f489b500c59d122df2e53969",
"reference": "93ebc5712cdad8d5f489b500c59d122df2e53969",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": "^5.4 || ^7.0"
},
"require-dev": {
"jeremeamia/superclosure": "^2.0",
"phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"time": "2019-11-29T22:36:02+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.5.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Opis\\Closure\\": "src/"
},
"files": [
"functions.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Marius Sarca",
"email": "marius.sarca@gmail.com"
},
{
"name": "Sorin Sarca",
"email": "sarca_sorin@hotmail.com"
}
],
"description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.",
"homepage": "https://opis.io/closure",
"keywords": [
"anonymous functions",
"closure",
"function",
"serializable",
"serialization",
"serialize"
],
"install-path": "../opis/closure"
},
{
"name": "overtrue/socialite",
"version": "1.3.0",
@ -4733,17 +4514,17 @@
},
{
"name": "topthink/framework",
"version": "v6.0.3",
"version_normalized": "6.0.3.0",
"version": "v6.1.2",
"version_normalized": "6.1.2.0",
"source": {
"type": "git",
"url": "https://github.com/top-think/framework.git",
"reference": "b4046fb21e6163ba23a792b694162693dbe71b4b"
"reference": "67235be5b919aaaf1de5aed9839f65d8e766aca3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/top-think/framework/zipball/b4046fb21e6163ba23a792b694162693dbe71b4b",
"reference": "b4046fb21e6163ba23a792b694162693dbe71b4b",
"url": "https://api.github.com/repos/top-think/framework/zipball/67235be5b919aaaf1de5aed9839f65d8e766aca3",
"reference": "67235be5b919aaaf1de5aed9839f65d8e766aca3",
"shasum": "",
"mirrors": [
{
@ -4755,22 +4536,21 @@
"require": {
"ext-json": "*",
"ext-mbstring": "*",
"league/flysystem": "^1.0",
"league/flysystem-cached-adapter": "^1.0",
"opis/closure": "^3.1",
"php": ">=7.1.0",
"php": ">=7.2.5",
"psr/container": "~1.0",
"psr/http-message": "^1.0",
"psr/log": "~1.0",
"psr/simple-cache": "^1.0",
"topthink/think-helper": "^3.1.1",
"topthink/think-orm": "^2.0"
"topthink/think-orm": "^2.0|^3.0"
},
"require-dev": {
"guzzlehttp/psr7": "^2.1.0",
"mikey179/vfsstream": "^1.6",
"mockery/mockery": "^1.2",
"phpunit/phpunit": "^7.0"
},
"time": "2020-06-26T16:03:10+00:00",
"time": "2023-02-08T02:24:01+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@ -4800,6 +4580,10 @@
"orm",
"thinkphp"
],
"support": {
"issues": "https://github.com/top-think/framework/issues",
"source": "https://github.com/top-think/framework/tree/v6.1.2"
},
"install-path": "../topthink/framework"
},
{

View File

@ -3,7 +3,7 @@
'name' => 'topthink/think',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '7c2cc12b79fc2e12fb5f255ac2746a4ffaa6110a',
'reference' => 'aa532e3f4aa4c78a733d68dc8cfd89eff585fbb6',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@ -439,24 +439,6 @@
'aliases' => array(),
'dev_requirement' => false,
),
'league/flysystem' => array(
'pretty_version' => '1.0.61',
'version' => '1.0.61.0',
'reference' => '4fb13c01784a6c9f165a351e996871488ca2d8c9',
'type' => 'library',
'install_path' => __DIR__ . '/../league/flysystem',
'aliases' => array(),
'dev_requirement' => false,
),
'league/flysystem-cached-adapter' => array(
'pretty_version' => '1.0.9',
'version' => '1.0.9.0',
'reference' => '08ef74e9be88100807a3b92cc9048a312bf01d6f',
'type' => 'library',
'install_path' => __DIR__ . '/../league/flysystem-cached-adapter',
'aliases' => array(),
'dev_requirement' => false,
),
'lizhichao/one-sm' => array(
'pretty_version' => '1.10',
'version' => '1.10.0.0',
@ -538,15 +520,6 @@
'aliases' => array(),
'dev_requirement' => false,
),
'opis/closure' => array(
'pretty_version' => '3.5.1',
'version' => '3.5.1.0',
'reference' => '93ebc5712cdad8d5f489b500c59d122df2e53969',
'type' => 'library',
'install_path' => __DIR__ . '/../opis/closure',
'aliases' => array(),
'dev_requirement' => false,
),
'overtrue/socialite' => array(
'pretty_version' => '1.3.0',
'version' => '1.3.0.0',
@ -818,9 +791,9 @@
'dev_requirement' => false,
),
'topthink/framework' => array(
'pretty_version' => 'v6.0.3',
'version' => '6.0.3.0',
'reference' => 'b4046fb21e6163ba23a792b694162693dbe71b4b',
'pretty_version' => 'v6.1.2',
'version' => '6.1.2.0',
'reference' => '67235be5b919aaaf1de5aed9839f65d8e766aca3',
'type' => 'library',
'install_path' => __DIR__ . '/../topthink/framework',
'aliases' => array(),
@ -829,7 +802,7 @@
'topthink/think' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '7c2cc12b79fc2e12fb5f255ac2746a4ffaa6110a',
'reference' => 'aa532e3f4aa4c78a733d68dc8cfd89eff585fbb6',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),

View File

@ -1,10 +0,0 @@
; top-most EditorConfig file
root = true
; Unix-style newlines
[*]
end_of_line = LF
[*.php]
indent_style = space
indent_size = 4

View File

@ -1,4 +0,0 @@
coverage
coverage.xml
composer.lock
vendor

View File

@ -1,7 +0,0 @@
<?php
return Symfony\CS\Config\Config::create()
->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
->fixers(['-yoda_conditions', 'ordered_use', 'short_array_syntax'])
->finder(Symfony\CS\Finder\DefaultFinder::create()
->in(__DIR__.'/src/'));

View File

@ -1,34 +0,0 @@
filter:
paths: [src/*]
checks:
php:
code_rating: true
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
tools:
external_code_coverage:
timeout: 900
runs: 6
php_code_coverage: false
php_code_sniffer:
config:
standard: PSR2
filter:
paths: ['src']
php_loc:
enabled: true
excluded_dirs: [vendor, spec, stubs]
php_cpd:
enabled: true
excluded_dirs: [vendor, spec, stubs]

View File

@ -1,29 +0,0 @@
language: php
php:
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
matrix:
allow_failures:
- php: 5.5
env:
- COMPOSER_OPTS=""
- COMPOSER_OPTS="--prefer-lowest"
install:
- if [[ "${TRAVIS_PHP_VERSION}" == "5.5" ]]; then composer require phpunit/phpunit:^4.8.36 phpspec/phpspec:^2 --prefer-dist --update-with-dependencies; fi
- if [[ "${TRAVIS_PHP_VERSION}" == "7.2" ]]; then composer require phpunit/phpunit:^6.0 --prefer-dist --update-with-dependencies; fi
- travis_retry composer update --prefer-dist $COMPOSER_OPTS
script:
- vendor/bin/phpspec run
- vendor/bin/phpunit
after_script:
- wget https://scrutinizer-ci.com/ocular.phar'
- php ocular.phar code-coverage:upload --format=php-clover ./clover/phpunit.xml'

View File

@ -1,19 +0,0 @@
Copyright (c) 2015 Frank de Jonge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,2 +0,0 @@
*
!.gitignore

View File

@ -1,30 +0,0 @@
{
"name": "league/flysystem-cached-adapter",
"description": "An adapter decorator to enable meta-data caching.",
"autoload": {
"psr-4": {
"League\\Flysystem\\Cached\\": "src/"
}
},
"require": {
"league/flysystem": "~1.0",
"psr/cache": "^1.0.0"
},
"require-dev": {
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7",
"mockery/mockery": "~0.9",
"predis/predis": "~1.0",
"tedivm/stash": "~0.12"
},
"suggest": {
"ext-phpredis": "Pure C implemented extension for PHP"
},
"license": "MIT",
"authors": [
{
"name": "frankdejonge",
"email": "info@frenky.net"
}
]
}

View File

@ -1,6 +0,0 @@
---
suites:
cached_adapter_suite:
namespace: League\Flysystem\Cached
psr4_prefix: League\Flysystem\Cached
formatter.name: pretty

View File

@ -1,3 +0,0 @@
<?php
include __DIR__.'/vendor/autoload.php';

View File

@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="./phpunit.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
verbose="true"
>
<testsuites>
<testsuite name="flysystem/tests">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/>
<log type="coverage-html" target="coverage" showUncoveredFiles="true"/>
<log type="coverage-clover" target="clover/phpunit.xml" showUncoveredFiles="true"/>
</logging>
</phpunit>

View File

@ -1,20 +0,0 @@
# Flysystem Cached CachedAdapter
[![Author](http://img.shields.io/badge/author-@frankdejonge-blue.svg?style=flat-square)](https://twitter.com/frankdejonge)
[![Build Status](https://img.shields.io/travis/thephpleague/flysystem-cached-adapter/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/flysystem-cached-adapter)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/flysystem-cached-adapter.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/flysystem-cached-adapter/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/flysystem-cached-adapter.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/flysystem-cached-adapter)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)
[![Packagist Version](https://img.shields.io/packagist/v/league/flysystem-cached-adapter.svg?style=flat-square)](https://packagist.org/packages/league/flysystem-cached-adapter)
[![Total Downloads](https://img.shields.io/packagist/dt/league/flysystem-cached-adapter.svg?style=flat-square)](https://packagist.org/packages/league/flysystem-cached-adapter)
The adapter decorator caches metadata and directory listings.
```bash
composer require league/flysystem-cached-adapter
```
## Usage
[Check out the docs.](https://flysystem.thephpleague.com/docs/advanced/caching/)

View File

@ -1,435 +0,0 @@
<?php
namespace spec\League\Flysystem\Cached;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Cached\CacheInterface;
use League\Flysystem\Config;
use PhpSpec\ObjectBehavior;
class CachedAdapterSpec extends ObjectBehavior
{
/**
* @var AdapterInterface
*/
private $adapter;
/**
* @var CacheInterface
*/
private $cache;
public function let(AdapterInterface $adapter, CacheInterface $cache)
{
$this->adapter = $adapter;
$this->cache = $cache;
$this->cache->load()->shouldBeCalled();
$this->beConstructedWith($adapter, $cache);
}
public function it_is_initializable()
{
$this->shouldHaveType('League\Flysystem\Cached\CachedAdapter');
$this->shouldHaveType('League\Flysystem\AdapterInterface');
}
public function it_should_forward_read_streams()
{
$path = 'path.txt';
$response = ['path' => $path];
$this->adapter->readStream($path)->willReturn($response);
$this->readStream($path)->shouldbe($response);
}
public function it_should_cache_writes()
{
$type = 'file';
$path = 'path.txt';
$contents = 'contents';
$config = new Config();
$response = compact('path', 'contents', 'type');
$this->adapter->write($path, $contents, $config)->willReturn($response);
$this->cache->updateObject($path, $response, true)->shouldBeCalled();
$this->write($path, $contents, $config)->shouldBe($response);
}
public function it_should_cache_streamed_writes()
{
$type = 'file';
$path = 'path.txt';
$stream = tmpfile();
$config = new Config();
$response = compact('path', 'stream', 'type');
$this->adapter->writeStream($path, $stream, $config)->willReturn($response);
$this->cache->updateObject($path, ['contents' => false] + $response, true)->shouldBeCalled();
$this->writeStream($path, $stream, $config)->shouldBe($response);
fclose($stream);
}
public function it_should_cache_streamed_updates()
{
$type = 'file';
$path = 'path.txt';
$stream = tmpfile();
$config = new Config();
$response = compact('path', 'stream', 'type');
$this->adapter->updateStream($path, $stream, $config)->willReturn($response);
$this->cache->updateObject($path, ['contents' => false] + $response, true)->shouldBeCalled();
$this->updateStream($path, $stream, $config)->shouldBe($response);
fclose($stream);
}
public function it_should_ignore_failed_writes()
{
$path = 'path.txt';
$contents = 'contents';
$config = new Config();
$this->adapter->write($path, $contents, $config)->willReturn(false);
$this->write($path, $contents, $config)->shouldBe(false);
}
public function it_should_ignore_failed_streamed_writes()
{
$path = 'path.txt';
$contents = tmpfile();
$config = new Config();
$this->adapter->writeStream($path, $contents, $config)->willReturn(false);
$this->writeStream($path, $contents, $config)->shouldBe(false);
fclose($contents);
}
public function it_should_cache_updated()
{
$type = 'file';
$path = 'path.txt';
$contents = 'contents';
$config = new Config();
$response = compact('path', 'contents', 'type');
$this->adapter->update($path, $contents, $config)->willReturn($response);
$this->cache->updateObject($path, $response, true)->shouldBeCalled();
$this->update($path, $contents, $config)->shouldBe($response);
}
public function it_should_ignore_failed_updates()
{
$path = 'path.txt';
$contents = 'contents';
$config = new Config();
$this->adapter->update($path, $contents, $config)->willReturn(false);
$this->update($path, $contents, $config)->shouldBe(false);
}
public function it_should_ignore_failed_streamed_updates()
{
$path = 'path.txt';
$contents = tmpfile();
$config = new Config();
$this->adapter->updateStream($path, $contents, $config)->willReturn(false);
$this->updateStream($path, $contents, $config)->shouldBe(false);
fclose($contents);
}
public function it_should_cache_renames()
{
$old = 'old.txt';
$new = 'new.txt';
$this->adapter->rename($old, $new)->willReturn(true);
$this->cache->rename($old, $new)->shouldBeCalled();
$this->rename($old, $new)->shouldBe(true);
}
public function it_should_ignore_rename_fails()
{
$old = 'old.txt';
$new = 'new.txt';
$this->adapter->rename($old, $new)->willReturn(false);
$this->rename($old, $new)->shouldBe(false);
}
public function it_should_cache_copies()
{
$old = 'old.txt';
$new = 'new.txt';
$this->adapter->copy($old, $new)->willReturn(true);
$this->cache->copy($old, $new)->shouldBeCalled();
$this->copy($old, $new)->shouldBe(true);
}
public function it_should_ignore_copy_fails()
{
$old = 'old.txt';
$new = 'new.txt';
$this->adapter->copy($old, $new)->willReturn(false);
$this->copy($old, $new)->shouldBe(false);
}
public function it_should_cache_deletes()
{
$delete = 'delete.txt';
$this->adapter->delete($delete)->willReturn(true);
$this->cache->delete($delete)->shouldBeCalled();
$this->delete($delete)->shouldBe(true);
}
public function it_should_ignore_delete_fails()
{
$delete = 'delete.txt';
$this->adapter->delete($delete)->willReturn(false);
$this->delete($delete)->shouldBe(false);
}
public function it_should_cache_dir_deletes()
{
$delete = 'delete';
$this->adapter->deleteDir($delete)->willReturn(true);
$this->cache->deleteDir($delete)->shouldBeCalled();
$this->deleteDir($delete)->shouldBe(true);
}
public function it_should_ignore_delete_dir_fails()
{
$delete = 'delete';
$this->adapter->deleteDir($delete)->willReturn(false);
$this->deleteDir($delete)->shouldBe(false);
}
public function it_should_cache_dir_creates()
{
$dirname = 'dirname';
$config = new Config();
$response = ['path' => $dirname, 'type' => 'dir'];
$this->adapter->createDir($dirname, $config)->willReturn($response);
$this->cache->updateObject($dirname, $response, true)->shouldBeCalled();
$this->createDir($dirname, $config)->shouldBe($response);
}
public function it_should_ignore_create_dir_fails()
{
$dirname = 'dirname';
$config = new Config();
$this->adapter->createDir($dirname, $config)->willReturn(false);
$this->createDir($dirname, $config)->shouldBe(false);
}
public function it_should_cache_set_visibility()
{
$path = 'path.txt';
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
$this->adapter->setVisibility($path, $visibility)->willReturn(true);
$this->cache->updateObject($path, ['path' => $path, 'visibility' => $visibility], true)->shouldBeCalled();
$this->setVisibility($path, $visibility)->shouldBe(true);
}
public function it_should_ignore_set_visibility_fails()
{
$dirname = 'delete';
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
$this->adapter->setVisibility($dirname, $visibility)->willReturn(false);
$this->setVisibility($dirname, $visibility)->shouldBe(false);
}
public function it_should_indicate_missing_files()
{
$this->cache->has($path = 'path.txt')->willReturn(false);
$this->has($path)->shouldBe(false);
}
public function it_should_indicate_file_existance()
{
$this->cache->has($path = 'path.txt')->willReturn(true);
$this->has($path)->shouldBe(true);
}
public function it_should_cache_missing_files()
{
$this->cache->has($path = 'path.txt')->willReturn(null);
$this->adapter->has($path)->willReturn(false);
$this->cache->storeMiss($path)->shouldBeCalled();
$this->has($path)->shouldBe(false);
}
public function it_should_delete_when_metadata_is_missing()
{
$path = 'path.txt';
$this->cache->has($path)->willReturn(true);
$this->cache->getSize($path)->willReturn(['path' => $path]);
$this->adapter->getSize($path)->willReturn($response = ['path' => $path, 'size' => 1024]);
$this->cache->updateObject($path, $response, true)->shouldBeCalled();
$this->getSize($path)->shouldBe($response);
}
public function it_should_cache_has()
{
$this->cache->has($path = 'path.txt')->willReturn(null);
$this->adapter->has($path)->willReturn(true);
$this->cache->updateObject($path, compact('path'), true)->shouldBeCalled();
$this->has($path)->shouldBe(true);
}
public function it_should_list_cached_contents()
{
$this->cache->isComplete($dirname = 'dirname', $recursive = true)->willReturn(true);
$response = [['path' => 'path.txt']];
$this->cache->listContents($dirname, $recursive)->willReturn($response);
$this->listContents($dirname, $recursive)->shouldBe($response);
}
public function it_should_ignore_failed_list_contents()
{
$this->cache->isComplete($dirname = 'dirname', $recursive = true)->willReturn(false);
$this->adapter->listContents($dirname, $recursive)->willReturn(false);
$this->listContents($dirname, $recursive)->shouldBe(false);
}
public function it_should_cache_contents_listings()
{
$this->cache->isComplete($dirname = 'dirname', $recursive = true)->willReturn(false);
$response = [['path' => 'path.txt']];
$this->adapter->listContents($dirname, $recursive)->willReturn($response);
$this->cache->storeContents($dirname, $response, $recursive)->shouldBeCalled();
$this->listContents($dirname, $recursive)->shouldBe($response);
}
public function it_should_use_cached_visibility()
{
$this->make_it_use_getter_cache('getVisibility', 'path.txt', [
'path' => 'path.txt',
'visibility' => AdapterInterface::VISIBILITY_PUBLIC,
]);
}
public function it_should_cache_get_visibility()
{
$path = 'path.txt';
$response = ['visibility' => AdapterInterface::VISIBILITY_PUBLIC, 'path' => $path];
$this->make_it_cache_getter('getVisibility', $path, $response);
}
public function it_should_ignore_failed_get_visibility()
{
$path = 'path.txt';
$this->make_it_ignore_failed_getter('getVisibility', $path);
}
public function it_should_use_cached_timestamp()
{
$this->make_it_use_getter_cache('getTimestamp', 'path.txt', [
'path' => 'path.txt',
'timestamp' => 1234,
]);
}
public function it_should_cache_timestamps()
{
$this->make_it_cache_getter('getTimestamp', 'path.txt', [
'path' => 'path.txt',
'timestamp' => 1234,
]);
}
public function it_should_ignore_failed_get_timestamps()
{
$this->make_it_ignore_failed_getter('getTimestamp', 'path.txt');
}
public function it_should_cache_get_metadata()
{
$path = 'path.txt';
$response = ['visibility' => AdapterInterface::VISIBILITY_PUBLIC, 'path' => $path];
$this->make_it_cache_getter('getMetadata', $path, $response);
}
public function it_should_use_cached_metadata()
{
$this->make_it_use_getter_cache('getMetadata', 'path.txt', [
'path' => 'path.txt',
'timestamp' => 1234,
]);
}
public function it_should_ignore_failed_get_metadata()
{
$this->make_it_ignore_failed_getter('getMetadata', 'path.txt');
}
public function it_should_cache_get_size()
{
$path = 'path.txt';
$response = ['size' => 1234, 'path' => $path];
$this->make_it_cache_getter('getSize', $path, $response);
}
public function it_should_use_cached_size()
{
$this->make_it_use_getter_cache('getSize', 'path.txt', [
'path' => 'path.txt',
'size' => 1234,
]);
}
public function it_should_ignore_failed_get_size()
{
$this->make_it_ignore_failed_getter('getSize', 'path.txt');
}
public function it_should_cache_get_mimetype()
{
$path = 'path.txt';
$response = ['mimetype' => 'text/plain', 'path' => $path];
$this->make_it_cache_getter('getMimetype', $path, $response);
}
public function it_should_use_cached_mimetype()
{
$this->make_it_use_getter_cache('getMimetype', 'path.txt', [
'path' => 'path.txt',
'mimetype' => 'text/plain',
]);
}
public function it_should_ignore_failed_get_mimetype()
{
$this->make_it_ignore_failed_getter('getMimetype', 'path.txt');
}
public function it_should_cache_reads()
{
$path = 'path.txt';
$response = ['path' => $path, 'contents' => 'contents'];
$this->make_it_cache_getter('read', $path, $response);
}
public function it_should_use_cached_file_contents()
{
$this->make_it_use_getter_cache('read', 'path.txt', [
'path' => 'path.txt',
'contents' => 'contents'
]);
}
public function it_should_ignore_failed_reads()
{
$this->make_it_ignore_failed_getter('read', 'path.txt');
}
protected function make_it_use_getter_cache($method, $path, $response)
{
$this->cache->{$method}($path)->willReturn($response);
$this->{$method}($path)->shouldBe($response);
}
protected function make_it_cache_getter($method, $path, $response)
{
$this->cache->{$method}($path)->willReturn(false);
$this->adapter->{$method}($path)->willReturn($response);
$this->cache->updateObject($path, $response, true)->shouldBeCalled();
$this->{$method}($path)->shouldBe($response);
}
protected function make_it_ignore_failed_getter($method, $path)
{
$this->cache->{$method}($path)->willReturn(false);
$this->adapter->{$method}($path)->willReturn(false);
$this->{$method}($path)->shouldBe(false);
}
}

View File

@ -1,101 +0,0 @@
<?php
namespace League\Flysystem\Cached;
use League\Flysystem\ReadInterface;
interface CacheInterface extends ReadInterface
{
/**
* Check whether the directory listing of a given directory is complete.
*
* @param string $dirname
* @param bool $recursive
*
* @return bool
*/
public function isComplete($dirname, $recursive);
/**
* Set a directory to completely listed.
*
* @param string $dirname
* @param bool $recursive
*/
public function setComplete($dirname, $recursive);
/**
* Store the contents of a directory.
*
* @param string $directory
* @param array $contents
* @param bool $recursive
*/
public function storeContents($directory, array $contents, $recursive);
/**
* Flush the cache.
*/
public function flush();
/**
* Autosave trigger.
*/
public function autosave();
/**
* Store the cache.
*/
public function save();
/**
* Load the cache.
*/
public function load();
/**
* Rename a file.
*
* @param string $path
* @param string $newpath
*/
public function rename($path, $newpath);
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*/
public function copy($path, $newpath);
/**
* Delete an object from cache.
*
* @param string $path object path
*/
public function delete($path);
/**
* Delete all objects from from a directory.
*
* @param string $dirname directory path
*/
public function deleteDir($dirname);
/**
* Update the metadata for an object.
*
* @param string $path object path
* @param array $object object metadata
* @param bool $autosave whether to trigger the autosave routine
*/
public function updateObject($path, array $object, $autosave = false);
/**
* Store object hit miss.
*
* @param string $path
*/
public function storeMiss($path);
}

View File

@ -1,324 +0,0 @@
<?php
namespace League\Flysystem\Cached;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
class CachedAdapter implements AdapterInterface
{
/**
* @var AdapterInterface
*/
private $adapter;
/**
* @var CacheInterface
*/
private $cache;
/**
* Constructor.
*
* @param AdapterInterface $adapter
* @param CacheInterface $cache
*/
public function __construct(AdapterInterface $adapter, CacheInterface $cache)
{
$this->adapter = $adapter;
$this->cache = $cache;
$this->cache->load();
}
/**
* Get the underlying Adapter implementation.
*
* @return AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* Get the used Cache implementation.
*
* @return CacheInterface
*/
public function getCache()
{
return $this->cache;
}
/**
* {@inheritdoc}
*/
public function write($path, $contents, Config $config)
{
$result = $this->adapter->write($path, $contents, $config);
if ($result !== false) {
$result['type'] = 'file';
$this->cache->updateObject($path, $result + compact('path', 'contents'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function writeStream($path, $resource, Config $config)
{
$result = $this->adapter->writeStream($path, $resource, $config);
if ($result !== false) {
$result['type'] = 'file';
$contents = false;
$this->cache->updateObject($path, $result + compact('path', 'contents'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function update($path, $contents, Config $config)
{
$result = $this->adapter->update($path, $contents, $config);
if ($result !== false) {
$result['type'] = 'file';
$this->cache->updateObject($path, $result + compact('path', 'contents'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function updateStream($path, $resource, Config $config)
{
$result = $this->adapter->updateStream($path, $resource, $config);
if ($result !== false) {
$result['type'] = 'file';
$contents = false;
$this->cache->updateObject($path, $result + compact('path', 'contents'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function rename($path, $newPath)
{
$result = $this->adapter->rename($path, $newPath);
if ($result !== false) {
$this->cache->rename($path, $newPath);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function copy($path, $newpath)
{
$result = $this->adapter->copy($path, $newpath);
if ($result !== false) {
$this->cache->copy($path, $newpath);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function delete($path)
{
$result = $this->adapter->delete($path);
if ($result !== false) {
$this->cache->delete($path);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function deleteDir($dirname)
{
$result = $this->adapter->deleteDir($dirname);
if ($result !== false) {
$this->cache->deleteDir($dirname);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function createDir($dirname, Config $config)
{
$result = $this->adapter->createDir($dirname, $config);
if ($result !== false) {
$type = 'dir';
$path = $dirname;
$this->cache->updateObject($dirname, compact('path', 'type'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function setVisibility($path, $visibility)
{
$result = $this->adapter->setVisibility($path, $visibility);
if ($result !== false) {
$this->cache->updateObject($path, compact('path', 'visibility'), true);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function has($path)
{
$cacheHas = $this->cache->has($path);
if ($cacheHas !== null) {
return $cacheHas;
}
$adapterResponse = $this->adapter->has($path);
if (! $adapterResponse) {
$this->cache->storeMiss($path);
} else {
$cacheEntry = is_array($adapterResponse) ? $adapterResponse : compact('path');
$this->cache->updateObject($path, $cacheEntry, true);
}
return $adapterResponse;
}
/**
* {@inheritdoc}
*/
public function read($path)
{
return $this->callWithFallback('contents', $path, 'read');
}
/**
* {@inheritdoc}
*/
public function readStream($path)
{
return $this->adapter->readStream($path);
}
/**
* {@inheritdoc}
*/
public function listContents($directory = '', $recursive = false)
{
if ($this->cache->isComplete($directory, $recursive)) {
return $this->cache->listContents($directory, $recursive);
}
$result = $this->adapter->listContents($directory, $recursive);
if ($result !== false) {
$this->cache->storeContents($directory, $result, $recursive);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function getMetadata($path)
{
return $this->callWithFallback(null, $path, 'getMetadata');
}
/**
* {@inheritdoc}
*/
public function getSize($path)
{
return $this->callWithFallback('size', $path, 'getSize');
}
/**
* {@inheritdoc}
*/
public function getMimetype($path)
{
return $this->callWithFallback('mimetype', $path, 'getMimetype');
}
/**
* {@inheritdoc}
*/
public function getTimestamp($path)
{
return $this->callWithFallback('timestamp', $path, 'getTimestamp');
}
/**
* {@inheritdoc}
*/
public function getVisibility($path)
{
return $this->callWithFallback('visibility', $path, 'getVisibility');
}
/**
* Call a method and cache the response.
*
* @param string $property
* @param string $path
* @param string $method
*
* @return mixed
*/
protected function callWithFallback($property, $path, $method)
{
$result = $this->cache->{$method}($path);
if ($result !== false && ($property === null || array_key_exists($property, $result))) {
return $result;
}
$result = $this->adapter->{$method}($path);
if ($result) {
$object = $result + compact('path');
$this->cache->updateObject($path, $object, true);
}
return $result;
}
}

View File

@ -1,417 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use League\Flysystem\Cached\CacheInterface;
use League\Flysystem\Util;
abstract class AbstractCache implements CacheInterface
{
/**
* @var bool
*/
protected $autosave = true;
/**
* @var array
*/
protected $cache = [];
/**
* @var array
*/
protected $complete = [];
/**
* Destructor.
*/
public function __destruct()
{
if (! $this->autosave) {
$this->save();
}
}
/**
* Get the autosave setting.
*
* @return bool autosave
*/
public function getAutosave()
{
return $this->autosave;
}
/**
* Get the autosave setting.
*
* @param bool $autosave
*/
public function setAutosave($autosave)
{
$this->autosave = $autosave;
}
/**
* Store the contents listing.
*
* @param string $directory
* @param array $contents
* @param bool $recursive
*
* @return array contents listing
*/
public function storeContents($directory, array $contents, $recursive = false)
{
$directories = [$directory];
foreach ($contents as $object) {
$this->updateObject($object['path'], $object);
$object = $this->cache[$object['path']];
if ($recursive && $this->pathIsInDirectory($directory, $object['path'])) {
$directories[] = $object['dirname'];
}
}
foreach (array_unique($directories) as $directory) {
$this->setComplete($directory, $recursive);
}
$this->autosave();
}
/**
* Update the metadata for an object.
*
* @param string $path object path
* @param array $object object metadata
* @param bool $autosave whether to trigger the autosave routine
*/
public function updateObject($path, array $object, $autosave = false)
{
if (! $this->has($path)) {
$this->cache[$path] = Util::pathinfo($path);
}
$this->cache[$path] = array_merge($this->cache[$path], $object);
if ($autosave) {
$this->autosave();
}
$this->ensureParentDirectories($path);
}
/**
* Store object hit miss.
*
* @param string $path
*/
public function storeMiss($path)
{
$this->cache[$path] = false;
$this->autosave();
}
/**
* Get the contents listing.
*
* @param string $dirname
* @param bool $recursive
*
* @return array contents listing
*/
public function listContents($dirname = '', $recursive = false)
{
$result = [];
foreach ($this->cache as $object) {
if ($object === false) {
continue;
}
if ($object['dirname'] === $dirname) {
$result[] = $object;
} elseif ($recursive && $this->pathIsInDirectory($dirname, $object['path'])) {
$result[] = $object;
}
}
return $result;
}
/**
* {@inheritdoc}
*/
public function has($path)
{
if ($path !== false && array_key_exists($path, $this->cache)) {
return $this->cache[$path] !== false;
}
if ($this->isComplete(Util::dirname($path), false)) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function read($path)
{
if (isset($this->cache[$path]['contents']) && $this->cache[$path]['contents'] !== false) {
return $this->cache[$path];
}
return false;
}
/**
* {@inheritdoc}
*/
public function readStream($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function rename($path, $newpath)
{
if ($this->has($path)) {
$object = $this->cache[$path];
unset($this->cache[$path]);
$object['path'] = $newpath;
$object = array_merge($object, Util::pathinfo($newpath));
$this->cache[$newpath] = $object;
$this->autosave();
}
}
/**
* {@inheritdoc}
*/
public function copy($path, $newpath)
{
if ($this->has($path)) {
$object = $this->cache[$path];
$object = array_merge($object, Util::pathinfo($newpath));
$this->updateObject($newpath, $object, true);
}
}
/**
* {@inheritdoc}
*/
public function delete($path)
{
$this->storeMiss($path);
}
/**
* {@inheritdoc}
*/
public function deleteDir($dirname)
{
foreach ($this->cache as $path => $object) {
if ($this->pathIsInDirectory($dirname, $path) || $path === $dirname) {
unset($this->cache[$path]);
}
}
unset($this->complete[$dirname]);
$this->autosave();
}
/**
* {@inheritdoc}
*/
public function getMimetype($path)
{
if (isset($this->cache[$path]['mimetype'])) {
return $this->cache[$path];
}
if (! $result = $this->read($path)) {
return false;
}
$mimetype = Util::guessMimeType($path, $result['contents']);
$this->cache[$path]['mimetype'] = $mimetype;
return $this->cache[$path];
}
/**
* {@inheritdoc}
*/
public function getSize($path)
{
if (isset($this->cache[$path]['size'])) {
return $this->cache[$path];
}
return false;
}
/**
* {@inheritdoc}
*/
public function getTimestamp($path)
{
if (isset($this->cache[$path]['timestamp'])) {
return $this->cache[$path];
}
return false;
}
/**
* {@inheritdoc}
*/
public function getVisibility($path)
{
if (isset($this->cache[$path]['visibility'])) {
return $this->cache[$path];
}
return false;
}
/**
* {@inheritdoc}
*/
public function getMetadata($path)
{
if (isset($this->cache[$path]['type'])) {
return $this->cache[$path];
}
return false;
}
/**
* {@inheritdoc}
*/
public function isComplete($dirname, $recursive)
{
if (! array_key_exists($dirname, $this->complete)) {
return false;
}
if ($recursive && $this->complete[$dirname] !== 'recursive') {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function setComplete($dirname, $recursive)
{
$this->complete[$dirname] = $recursive ? 'recursive' : true;
}
/**
* Filter the contents from a listing.
*
* @param array $contents object listing
*
* @return array filtered contents
*/
public function cleanContents(array $contents)
{
$cachedProperties = array_flip([
'path', 'dirname', 'basename', 'extension', 'filename',
'size', 'mimetype', 'visibility', 'timestamp', 'type',
]);
foreach ($contents as $path => $object) {
if (is_array($object)) {
$contents[$path] = array_intersect_key($object, $cachedProperties);
}
}
return $contents;
}
/**
* {@inheritdoc}
*/
public function flush()
{
$this->cache = [];
$this->complete = [];
$this->autosave();
}
/**
* {@inheritdoc}
*/
public function autosave()
{
if ($this->autosave) {
$this->save();
}
}
/**
* Retrieve serialized cache data.
*
* @return string serialized data
*/
public function getForStorage()
{
$cleaned = $this->cleanContents($this->cache);
return json_encode([$cleaned, $this->complete]);
}
/**
* Load from serialized cache data.
*
* @param string $json
*/
public function setFromStorage($json)
{
list($cache, $complete) = json_decode($json, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($cache) && is_array($complete)) {
$this->cache = $cache;
$this->complete = $complete;
}
}
/**
* Ensure parent directories of an object.
*
* @param string $path object path
*/
public function ensureParentDirectories($path)
{
$object = $this->cache[$path];
while ($object['dirname'] !== '' && ! isset($this->cache[$object['dirname']])) {
$object = Util::pathinfo($object['dirname']);
$object['type'] = 'dir';
$this->cache[$object['path']] = $object;
}
}
/**
* Determines if the path is inside the directory.
*
* @param string $directory
* @param string $path
*
* @return bool
*/
protected function pathIsInDirectory($directory, $path)
{
return $directory === '' || strpos($path, $directory . '/') === 0;
}
}

View File

@ -1,115 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
class Adapter extends AbstractCache
{
/**
* @var AdapterInterface An adapter
*/
protected $adapter;
/**
* @var string the file to cache to
*/
protected $file;
/**
* @var int|null seconds until cache expiration
*/
protected $expire = null;
/**
* Constructor.
*
* @param AdapterInterface $adapter adapter
* @param string $file the file to cache to
* @param int|null $expire seconds until cache expiration
*/
public function __construct(AdapterInterface $adapter, $file, $expire = null)
{
$this->adapter = $adapter;
$this->file = $file;
$this->setExpire($expire);
}
/**
* Set the expiration time in seconds.
*
* @param int $expire relative expiration time
*/
protected function setExpire($expire)
{
if ($expire) {
$this->expire = $this->getTime($expire);
}
}
/**
* Get expiration time in seconds.
*
* @param int $time relative expiration time
*
* @return int actual expiration time
*/
protected function getTime($time = 0)
{
return intval(microtime(true)) + $time;
}
/**
* {@inheritdoc}
*/
public function setFromStorage($json)
{
list($cache, $complete, $expire) = json_decode($json, true);
if (! $expire || $expire > $this->getTime()) {
$this->cache = $cache;
$this->complete = $complete;
} else {
$this->adapter->delete($this->file);
}
}
/**
* {@inheritdoc}
*/
public function load()
{
if ($this->adapter->has($this->file)) {
$file = $this->adapter->read($this->file);
if ($file && !empty($file['contents'])) {
$this->setFromStorage($file['contents']);
}
}
}
/**
* {@inheritdoc}
*/
public function getForStorage()
{
$cleaned = $this->cleanContents($this->cache);
return json_encode([$cleaned, $this->complete, $this->expire]);
}
/**
* {@inheritdoc}
*/
public function save()
{
$config = new Config();
$contents = $this->getForStorage();
if ($this->adapter->has($this->file)) {
$this->adapter->update($this->file, $contents, $config);
} else {
$this->adapter->write($this->file, $contents, $config);
}
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use Memcached as NativeMemcached;
class Memcached extends AbstractCache
{
/**
* @var string storage key
*/
protected $key;
/**
* @var int|null seconds until cache expiration
*/
protected $expire;
/**
* @var \Memcached Memcached instance
*/
protected $memcached;
/**
* Constructor.
*
* @param \Memcached $memcached
* @param string $key storage key
* @param int|null $expire seconds until cache expiration
*/
public function __construct(NativeMemcached $memcached, $key = 'flysystem', $expire = null)
{
$this->key = $key;
$this->expire = $expire;
$this->memcached = $memcached;
}
/**
* {@inheritdoc}
*/
public function load()
{
$contents = $this->memcached->get($this->key);
if ($contents !== false) {
$this->setFromStorage($contents);
}
}
/**
* {@inheritdoc}
*/
public function save()
{
$contents = $this->getForStorage();
$expiration = $this->expire === null ? 0 : time() + $this->expire;
$this->memcached->set($this->key, $contents, $expiration);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
class Memory extends AbstractCache
{
/**
* {@inheritdoc}
*/
public function save()
{
// There is nothing to save
}
/**
* {@inheritdoc}
*/
public function load()
{
// There is nothing to load
}
}

View File

@ -1,171 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
class Noop extends AbstractCache
{
/**
* {@inheritdoc}
*/
protected $autosave = false;
/**
* {@inheritdoc}
*/
public function updateObject($path, array $object, $autosave = false)
{
return $object;
}
/**
* {@inheritdoc}
*/
public function isComplete($dirname, $recursive)
{
return false;
}
/**
* {@inheritdoc}
*/
public function setComplete($dirname, $recursive)
{
//
}
/**
* {@inheritdoc}
*/
public function copy($path, $newpath)
{
return false;
}
/**
* {@inheritdoc}
*/
public function rename($path, $newpath)
{
return false;
}
/**
* {@inheritdoc}
*/
public function storeContents($directory, array $contents, $recursive = false)
{
return $contents;
}
/**
* {@inheritdoc}
*/
public function storeMiss($path)
{
return $this;
}
/**
* {@inheritdoc}
*/
public function flush()
{
//
}
/**
* {@inheritdoc}
*/
public function autosave()
{
//
}
/**
* {@inheritdoc}
*/
public function save()
{
//
}
/**
* {@inheritdoc}
*/
public function load()
{
//
}
/**
* {@inheritdoc}
*/
public function has($path)
{
return;
}
/**
* {@inheritdoc}
*/
public function read($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function readStream($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function listContents($directory = '', $recursive = false)
{
return [];
}
/**
* {@inheritdoc}
*/
public function getMetadata($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getSize($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getMimetype($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getTimestamp($path)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getVisibility($path)
{
return false;
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use Redis;
class PhpRedis extends AbstractCache
{
/**
* @var Redis PhpRedis Client
*/
protected $client;
/**
* @var string storage key
*/
protected $key;
/**
* @var int|null seconds until cache expiration
*/
protected $expire;
/**
* Constructor.
*
* @param Redis|null $client phpredis client
* @param string $key storage key
* @param int|null $expire seconds until cache expiration
*/
public function __construct(Redis $client = null, $key = 'flysystem', $expire = null)
{
$this->client = $client ?: new Redis();
$this->key = $key;
$this->expire = $expire;
}
/**
* {@inheritdoc}
*/
public function load()
{
$contents = $this->client->get($this->key);
if ($contents !== false) {
$this->setFromStorage($contents);
}
}
/**
* {@inheritdoc}
*/
public function save()
{
$contents = $this->getForStorage();
$this->client->set($this->key, $contents);
if ($this->expire !== null) {
$this->client->expire($this->key, $this->expire);
}
}
}

View File

@ -1,75 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use Predis\Client;
class Predis extends AbstractCache
{
/**
* @var \Predis\Client Predis Client
*/
protected $client;
/**
* @var string storage key
*/
protected $key;
/**
* @var int|null seconds until cache expiration
*/
protected $expire;
/**
* Constructor.
*
* @param \Predis\Client $client predis client
* @param string $key storage key
* @param int|null $expire seconds until cache expiration
*/
public function __construct(Client $client = null, $key = 'flysystem', $expire = null)
{
$this->client = $client ?: new Client();
$this->key = $key;
$this->expire = $expire;
}
/**
* {@inheritdoc}
*/
public function load()
{
if (($contents = $this->executeCommand('get', [$this->key])) !== null) {
$this->setFromStorage($contents);
}
}
/**
* {@inheritdoc}
*/
public function save()
{
$contents = $this->getForStorage();
$this->executeCommand('set', [$this->key, $contents]);
if ($this->expire !== null) {
$this->executeCommand('expire', [$this->key, $this->expire]);
}
}
/**
* Execute a Predis command.
*
* @param string $name
* @param array $arguments
*
* @return string
*/
protected function executeCommand($name, array $arguments)
{
$command = $this->client->createCommand($name, $arguments);
return $this->client->executeCommand($command);
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use Psr\Cache\CacheItemPoolInterface;
class Psr6Cache extends AbstractCache
{
/**
* @var CacheItemPoolInterface
*/
private $pool;
/**
* @var string storage key
*/
protected $key;
/**
* @var int|null seconds until cache expiration
*/
protected $expire;
/**
* Constructor.
*
* @param CacheItemPoolInterface $pool
* @param string $key storage key
* @param int|null $expire seconds until cache expiration
*/
public function __construct(CacheItemPoolInterface $pool, $key = 'flysystem', $expire = null)
{
$this->pool = $pool;
$this->key = $key;
$this->expire = $expire;
}
/**
* {@inheritdoc}
*/
public function save()
{
$item = $this->pool->getItem($this->key);
$item->set($this->getForStorage());
$item->expiresAfter($this->expire);
$this->pool->save($item);
}
/**
* {@inheritdoc}
*/
public function load()
{
$item = $this->pool->getItem($this->key);
if ($item->isHit()) {
$this->setFromStorage($item->get());
}
}
}

View File

@ -1,60 +0,0 @@
<?php
namespace League\Flysystem\Cached\Storage;
use Stash\Pool;
class Stash extends AbstractCache
{
/**
* @var string storage key
*/
protected $key;
/**
* @var int|null seconds until cache expiration
*/
protected $expire;
/**
* @var \Stash\Pool Stash pool instance
*/
protected $pool;
/**
* Constructor.
*
* @param \Stash\Pool $pool
* @param string $key storage key
* @param int|null $expire seconds until cache expiration
*/
public function __construct(Pool $pool, $key = 'flysystem', $expire = null)
{
$this->key = $key;
$this->expire = $expire;
$this->pool = $pool;
}
/**
* {@inheritdoc}
*/
public function load()
{
$item = $this->pool->getItem($this->key);
$contents = $item->get();
if ($item->isMiss() === false) {
$this->setFromStorage($contents);
}
}
/**
* {@inheritdoc}
*/
public function save()
{
$contents = $this->getForStorage();
$item = $this->pool->getItem($this->key);
$item->set($contents, $this->expire);
}
}

View File

@ -1,104 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Adapter;
use PHPUnit\Framework\TestCase;
class AdapterCacheTests extends TestCase
{
public function testLoadFail()
{
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(false);
$cache = new Adapter($adapter, 'file.json', 10);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadExpired()
{
$response = ['contents' => json_encode([[], ['' => true], 1234567890]), 'path' => 'file.json'];
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true);
$adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response);
$adapter->shouldReceive('delete')->once()->with('file.json');
$cache = new Adapter($adapter, 'file.json', 10);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = ['contents' => json_encode([[], ['' => true], 9876543210]), 'path' => 'file.json'];
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true);
$adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response);
$cache = new Adapter($adapter, 'file.json', 10);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSaveExists()
{
$response = json_encode([[], [], null]);
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(true);
$adapter->shouldReceive('update')->once()->with('file.json', $response, Mockery::any());
$cache = new Adapter($adapter, 'file.json', null);
$cache->save();
}
public function testSaveNew()
{
$response = json_encode([[], [], null]);
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(false);
$adapter->shouldReceive('write')->once()->with('file.json', $response, Mockery::any());
$cache = new Adapter($adapter, 'file.json', null);
$cache->save();
}
public function testStoreContentsRecursive()
{
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->once()->with('file.json')->andReturn(false);
$adapter->shouldReceive('write')->once()->with('file.json', Mockery::any(), Mockery::any());
$cache = new Adapter($adapter, 'file.json', null);
$contents = [
['path' => 'foo/bar', 'dirname' => 'foo'],
['path' => 'afoo/bang', 'dirname' => 'afoo'],
];
$cache->storeContents('foo', $contents, true);
$this->assertTrue($cache->isComplete('foo', true));
$this->assertFalse($cache->isComplete('afoo', true));
}
public function testDeleteDir()
{
$cache_data = [
'foo' => ['path' => 'foo', 'type' => 'dir', 'dirname' => ''],
'foo/bar' => ['path' => 'foo/bar', 'type' => 'file', 'dirname' => 'foo'],
'foobaz' => ['path' => 'foobaz', 'type' => 'file', 'dirname' => ''],
];
$response = [
'contents' => json_encode([$cache_data, [], null]),
'path' => 'file.json',
];
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$adapter->shouldReceive('has')->zeroOrMoreTimes()->with('file.json')->andReturn(true);
$adapter->shouldReceive('read')->once()->with('file.json')->andReturn($response);
$adapter->shouldReceive('update')->once()->with('file.json', Mockery::any(), Mockery::any())->andReturn(true);
$cache = new Adapter($adapter, 'file.json', null);
$cache->load();
$cache->deleteDir('foo', true);
$this->assertSame(1, count($cache->listContents('', true)));
}
}

View File

@ -1,16 +0,0 @@
<?php
use League\Flysystem\Cached\CachedAdapter;
use PHPUnit\Framework\TestCase;
class InspectionTests extends TestCase {
public function testGetAdapter()
{
$adapter = Mockery::mock('League\Flysystem\AdapterInterface');
$cache = Mockery::mock('League\Flysystem\Cached\CacheInterface');
$cache->shouldReceive('load')->once();
$cached_adapter = new CachedAdapter($adapter, $cache);
$this->assertInstanceOf('League\Flysystem\AdapterInterface', $cached_adapter->getAdapter());
}
}

View File

@ -1,35 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Memcached;
use PHPUnit\Framework\TestCase;
class MemcachedTests extends TestCase
{
public function testLoadFail()
{
$client = Mockery::mock('Memcached');
$client->shouldReceive('get')->once()->andReturn(false);
$cache = new Memcached($client);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = json_encode([[], ['' => true]]);
$client = Mockery::mock('Memcached');
$client->shouldReceive('get')->once()->andReturn($response);
$cache = new Memcached($client);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSave()
{
$response = json_encode([[], []]);
$client = Mockery::mock('Memcached');
$client->shouldReceive('set')->once()->andReturn($response);
$cache = new Memcached($client);
$cache->save();
}
}

View File

@ -1,255 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Memory;
use League\Flysystem\Util;
use PHPUnit\Framework\TestCase;
class MemoryCacheTests extends TestCase
{
public function testAutosave()
{
$cache = new Memory();
$cache->setAutosave(true);
$this->assertTrue($cache->getAutosave());
$cache->setAutosave(false);
$this->assertFalse($cache->getAutosave());
}
public function testCacheMiss()
{
$cache = new Memory();
$cache->storeMiss('path.txt');
$this->assertFalse($cache->has('path.txt'));
}
public function testIsComplete()
{
$cache = new Memory();
$this->assertFalse($cache->isComplete('dirname', false));
$cache->setComplete('dirname', false);
$this->assertFalse($cache->isComplete('dirname', true));
$cache->setComplete('dirname', true);
$this->assertTrue($cache->isComplete('dirname', true));
}
public function testCleanContents()
{
$cache = new Memory();
$input = [[
'path' => 'path.txt',
'visibility' => 'public',
'invalid' => 'thing',
]];
$expected = [[
'path' => 'path.txt',
'visibility' => 'public',
]];
$output = $cache->cleanContents($input);
$this->assertEquals($expected, $output);
}
public function testGetForStorage()
{
$cache = new Memory();
$input = [[
'path' => 'path.txt',
'visibility' => 'public',
'type' => 'file',
]];
$cache->storeContents('', $input, true);
$contents = $cache->listContents('', true);
$cached = [];
foreach ($contents as $item) {
$cached[$item['path']] = $item;
}
$this->assertEquals(json_encode([$cached, ['' => 'recursive']]), $cache->getForStorage());
}
public function testParentCompleteIsUsedDuringHas()
{
$cache = new Memory();
$cache->setComplete('dirname', false);
$this->assertFalse($cache->has('dirname/path.txt'));
}
public function testFlush()
{
$cache = new Memory();
$cache->setComplete('dirname', true);
$cache->updateObject('path.txt', [
'path' => 'path.txt',
'visibility' => 'public',
]);
$cache->flush();
$this->assertFalse($cache->isComplete('dirname', true));
$this->assertNull($cache->has('path.txt'));
}
public function testSetFromStorage()
{
$cache = new Memory();
$json = [[
'path.txt' => ['path' => 'path.txt', 'type' => 'file'],
], ['dirname' => 'recursive']];
$jsonString = json_encode($json);
$cache->setFromStorage($jsonString);
$this->assertTrue($cache->has('path.txt'));
$this->assertTrue($cache->isComplete('dirname', true));
}
public function testGetMetadataFail()
{
$cache = new Memory();
$this->assertFalse($cache->getMetadata('path.txt'));
}
public function metaGetterProvider()
{
return [
['getTimestamp', 'timestamp', 12344],
['getMimetype', 'mimetype', 'text/plain'],
['getSize', 'size', 12],
['getVisibility', 'visibility', 'private'],
['read', 'contents', '__contents__'],
];
}
/**
* @dataProvider metaGetterProvider
*
* @param $method
* @param $key
* @param $value
*/
public function testMetaGetters($method, $key, $value)
{
$cache = new Memory();
$this->assertFalse($cache->{$method}('path.txt'));
$cache->updateObject('path.txt', $object = [
'path' => 'path.txt',
'type' => 'file',
$key => $value,
] + Util::pathinfo('path.txt'), true);
$this->assertEquals($object, $cache->{$method}('path.txt'));
$this->assertEquals($object, $cache->getMetadata('path.txt'));
}
public function testGetDerivedMimetype()
{
$cache = new Memory();
$cache->updateObject('path.txt', [
'contents' => 'something',
]);
$response = $cache->getMimetype('path.txt');
$this->assertEquals('text/plain', $response['mimetype']);
}
public function testCopyFail()
{
$cache = new Memory();
$cache->copy('one', 'two');
$this->assertNull($cache->has('two'));
$this->assertNull($cache->load());
}
public function testStoreContents()
{
$cache = new Memory();
$cache->storeContents('dirname', [
['path' => 'dirname', 'type' => 'dir'],
['path' => 'dirname/nested', 'type' => 'dir'],
['path' => 'dirname/nested/deep', 'type' => 'dir'],
['path' => 'other/nested/deep', 'type' => 'dir'],
], true);
$this->isTrue($cache->isComplete('other/nested', true));
}
public function testDelete()
{
$cache = new Memory();
$cache->updateObject('path.txt', ['type' => 'file']);
$this->assertTrue($cache->has('path.txt'));
$cache->delete('path.txt');
$this->assertFalse($cache->has('path.txt'));
}
public function testDeleteDir()
{
$cache = new Memory();
$cache->storeContents('dirname', [
['path' => 'dirname/path.txt', 'type' => 'file'],
]);
$this->assertTrue($cache->isComplete('dirname', false));
$this->assertTrue($cache->has('dirname/path.txt'));
$cache->deleteDir('dirname');
$this->assertFalse($cache->isComplete('dirname', false));
$this->assertNull($cache->has('dirname/path.txt'));
}
public function testReadStream()
{
$cache = new Memory();
$this->assertFalse($cache->readStream('path.txt'));
}
public function testRename()
{
$cache = new Memory();
$cache->updateObject('path.txt', ['type' => 'file']);
$cache->rename('path.txt', 'newpath.txt');
$this->assertTrue($cache->has('newpath.txt'));
}
public function testCopy()
{
$cache = new Memory();
$cache->updateObject('path.txt', ['type' => 'file']);
$cache->copy('path.txt', 'newpath.txt');
$this->assertTrue($cache->has('newpath.txt'));
}
public function testComplextListContents()
{
$cache = new Memory();
$cache->storeContents('', [
['path' => 'dirname', 'type' => 'dir'],
['path' => 'dirname/file.txt', 'type' => 'file'],
['path' => 'other', 'type' => 'dir'],
['path' => 'other/file.txt', 'type' => 'file'],
['path' => 'other/nested/file.txt', 'type' => 'file'],
]);
$this->assertCount(3, $cache->listContents('other', true));
}
public function testComplextListContentsWithDeletedFile()
{
$cache = new Memory();
$cache->storeContents('', [
['path' => 'dirname', 'type' => 'dir'],
['path' => 'dirname/file.txt', 'type' => 'file'],
['path' => 'other', 'type' => 'dir'],
['path' => 'other/file.txt', 'type' => 'file'],
['path' => 'other/another_file.txt', 'type' => 'file'],
]);
$cache->delete('other/another_file.txt');
$this->assertCount(4, $cache->listContents('', true));
}
public function testCacheMissIfContentsIsFalse()
{
$cache = new Memory();
$cache->updateObject('path.txt', [
'path' => 'path.txt',
'contents' => false,
], true);
$this->assertFalse($cache->read('path.txt'));
}
}

View File

@ -1,35 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Noop;
use PHPUnit\Framework\TestCase;
class NoopCacheTests extends TestCase
{
public function testNoop()
{
$cache = new Noop();
$this->assertEquals($cache, $cache->storeMiss('file.txt'));
$this->assertNull($cache->setComplete('', false));
$this->assertNull($cache->load());
$this->assertNull($cache->flush());
$this->assertNull($cache->has('path.txt'));
$this->assertNull($cache->autosave());
$this->assertFalse($cache->isComplete('', false));
$this->assertFalse($cache->read('something'));
$this->assertFalse($cache->readStream('something'));
$this->assertFalse($cache->getMetadata('something'));
$this->assertFalse($cache->getMimetype('something'));
$this->assertFalse($cache->getSize('something'));
$this->assertFalse($cache->getTimestamp('something'));
$this->assertFalse($cache->getVisibility('something'));
$this->assertEmpty($cache->listContents('', false));
$this->assertFalse($cache->rename('', ''));
$this->assertFalse($cache->copy('', ''));
$this->assertNull($cache->save());
$object = ['path' => 'path.ext'];
$this->assertEquals($object, $cache->updateObject('path.txt', $object));
$this->assertEquals([['path' => 'some/file.txt']], $cache->storeContents('unknwon', [
['path' => 'some/file.txt'],
], false));
}
}

View File

@ -1,45 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\PhpRedis;
use PHPUnit\Framework\TestCase;
class PhpRedisTests extends TestCase
{
public function testLoadFail()
{
$client = Mockery::mock('Redis');
$client->shouldReceive('get')->with('flysystem')->once()->andReturn(false);
$cache = new PhpRedis($client);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = json_encode([[], ['' => true]]);
$client = Mockery::mock('Redis');
$client->shouldReceive('get')->with('flysystem')->once()->andReturn($response);
$cache = new PhpRedis($client);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSave()
{
$data = json_encode([[], []]);
$client = Mockery::mock('Redis');
$client->shouldReceive('set')->with('flysystem', $data)->once();
$cache = new PhpRedis($client);
$cache->save();
}
public function testSaveWithExpire()
{
$data = json_encode([[], []]);
$client = Mockery::mock('Redis');
$client->shouldReceive('set')->with('flysystem', $data)->once();
$client->shouldReceive('expire')->with('flysystem', 20)->once();
$cache = new PhpRedis($client, 'flysystem', 20);
$cache->save();
}
}

View File

@ -1,55 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Predis;
use PHPUnit\Framework\TestCase;
class PredisTests extends TestCase
{
public function testLoadFail()
{
$client = Mockery::mock('Predis\Client');
$command = Mockery::mock('Predis\Command\CommandInterface');
$client->shouldReceive('createCommand')->with('get', ['flysystem'])->once()->andReturn($command);
$client->shouldReceive('executeCommand')->with($command)->andReturn(null);
$cache = new Predis($client);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = json_encode([[], ['' => true]]);
$client = Mockery::mock('Predis\Client');
$command = Mockery::mock('Predis\Command\CommandInterface');
$client->shouldReceive('createCommand')->with('get', ['flysystem'])->once()->andReturn($command);
$client->shouldReceive('executeCommand')->with($command)->andReturn($response);
$cache = new Predis($client);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSave()
{
$data = json_encode([[], []]);
$client = Mockery::mock('Predis\Client');
$command = Mockery::mock('Predis\Command\CommandInterface');
$client->shouldReceive('createCommand')->with('set', ['flysystem', $data])->once()->andReturn($command);
$client->shouldReceive('executeCommand')->with($command)->once();
$cache = new Predis($client);
$cache->save();
}
public function testSaveWithExpire()
{
$data = json_encode([[], []]);
$client = Mockery::mock('Predis\Client');
$command = Mockery::mock('Predis\Command\CommandInterface');
$client->shouldReceive('createCommand')->with('set', ['flysystem', $data])->once()->andReturn($command);
$client->shouldReceive('executeCommand')->with($command)->once();
$expireCommand = Mockery::mock('Predis\Command\CommandInterface');
$client->shouldReceive('createCommand')->with('expire', ['flysystem', 20])->once()->andReturn($expireCommand);
$client->shouldReceive('executeCommand')->with($expireCommand)->once();
$cache = new Predis($client, 'flysystem', 20);
$cache->save();
}
}

View File

@ -1,45 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Psr6Cache;
use PHPUnit\Framework\TestCase;
class Psr6CacheTests extends TestCase
{
public function testLoadFail()
{
$pool = Mockery::mock('Psr\Cache\CacheItemPoolInterface');
$item = Mockery::mock('Psr\Cache\CacheItemInterface');
$item->shouldReceive('isHit')->once()->andReturn(false);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$cache = new Psr6Cache($pool);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = json_encode([[], ['' => true]]);
$pool = Mockery::mock('Psr\Cache\CacheItemPoolInterface');
$item = Mockery::mock('Psr\Cache\CacheItemInterface');
$item->shouldReceive('get')->once()->andReturn($response);
$item->shouldReceive('isHit')->once()->andReturn(true);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$cache = new Psr6Cache($pool);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSave()
{
$response = json_encode([[], []]);
$ttl = 4711;
$pool = Mockery::mock('Psr\Cache\CacheItemPoolInterface');
$item = Mockery::mock('Psr\Cache\CacheItemInterface');
$item->shouldReceive('expiresAfter')->once()->with($ttl);
$item->shouldReceive('set')->once()->andReturn($response);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$pool->shouldReceive('save')->once()->with($item);
$cache = new Psr6Cache($pool, 'foo', $ttl);
$cache->save();
}
}

View File

@ -1,43 +0,0 @@
<?php
use League\Flysystem\Cached\Storage\Stash;
use PHPUnit\Framework\TestCase;
class StashTests extends TestCase
{
public function testLoadFail()
{
$pool = Mockery::mock('Stash\Pool');
$item = Mockery::mock('Stash\Item');
$item->shouldReceive('get')->once()->andReturn(null);
$item->shouldReceive('isMiss')->once()->andReturn(true);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$cache = new Stash($pool);
$cache->load();
$this->assertFalse($cache->isComplete('', false));
}
public function testLoadSuccess()
{
$response = json_encode([[], ['' => true]]);
$pool = Mockery::mock('Stash\Pool');
$item = Mockery::mock('Stash\Item');
$item->shouldReceive('get')->once()->andReturn($response);
$item->shouldReceive('isMiss')->once()->andReturn(false);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$cache = new Stash($pool);
$cache->load();
$this->assertTrue($cache->isComplete('', false));
}
public function testSave()
{
$response = json_encode([[], []]);
$pool = Mockery::mock('Stash\Pool');
$item = Mockery::mock('Stash\Item');
$item->shouldReceive('set')->once()->andReturn($response);
$pool->shouldReceive('getItem')->once()->andReturn($item);
$cache = new Stash($pool);
$cache->save();
}
}

View File

@ -1,19 +0,0 @@
Copyright (c) 2013-2019 Frank de Jonge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,64 +0,0 @@
{
"name": "league/flysystem",
"description": "Filesystem abstraction: Many filesystems, one API.",
"keywords": [
"filesystem", "filesystems", "files", "storage", "dropbox", "aws",
"abstraction", "s3", "ftp", "sftp", "remote", "webdav",
"file systems", "cloud", "cloud files", "rackspace", "copy.com"
],
"license": "MIT",
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frenky.net"
}
],
"require": {
"php": ">=5.5.9",
"ext-fileinfo": "*"
},
"require-dev": {
"phpspec/phpspec": "^3.4",
"phpunit/phpunit": "^5.7.10"
},
"autoload": {
"psr-4": {
"League\\Flysystem\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"League\\Flysystem\\Stub\\": "stub/"
},
"files": [
"tests/PHPUnitHacks.php"
]
},
"suggest": {
"ext-fileinfo": "Required for MimeType",
"league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem",
"league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files",
"league/flysystem-azure": "Allows you to use Windows Azure Blob storage",
"league/flysystem-webdav": "Allows you to use WebDAV storage",
"league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2",
"league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3",
"spatie/flysystem-dropbox": "Allows you to use Dropbox storage",
"srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications",
"league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching",
"ext-ftp": "Allows you to use FTP server storage",
"ext-openssl": "Allows you to use FTPS server storage",
"league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib",
"league/flysystem-ziparchive": "Allows you to use ZipArchive adapter"
},
"conflict": {
"league/flysystem-sftp": "<1.0.6"
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"scripts": {
"phpstan": "php phpstan.php"
}
}

View File

@ -1,19 +0,0 @@
# Deprecations
This document lists all the planned deprecations.
## Handlers will be removed in 2.0
The `Handler` type and associated calls will be removed in version 2.0.
### Upgrade path
You should create your own implementation for handling OOP usage,
but it's recommended to move away from using an OOP-style wrapper entirely.
The reason for this is that it's too easy for implementation details (for
your application this is Flysystem) to leak into the application. The most
important part for Flysystem is that it improves portability and creates a
solid boundary between your application core and the infrastructure you use.
The OOP-style handling breaks this principle, therefore I want to stop
promoting it.

View File

@ -1,72 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
use League\Flysystem\AdapterInterface;
abstract class AbstractAdapter implements AdapterInterface
{
/**
* @var string|null path prefix
*/
protected $pathPrefix;
/**
* @var string
*/
protected $pathSeparator = '/';
/**
* Set the path prefix.
*
* @param string $prefix
*
* @return void
*/
public function setPathPrefix($prefix)
{
$prefix = (string) $prefix;
if ($prefix === '') {
$this->pathPrefix = null;
return;
}
$this->pathPrefix = rtrim($prefix, '\\/') . $this->pathSeparator;
}
/**
* Get the path prefix.
*
* @return string|null path prefix or null if pathPrefix is empty
*/
public function getPathPrefix()
{
return $this->pathPrefix;
}
/**
* Prefix a path.
*
* @param string $path
*
* @return string prefixed path
*/
public function applyPathPrefix($path)
{
return $this->getPathPrefix() . ltrim($path, '\\/');
}
/**
* Remove a path prefix.
*
* @param string $path
*
* @return string path without the prefix
*/
public function removePathPrefix($path)
{
return substr($path, strlen($this->getPathPrefix()));
}
}

View File

@ -1,693 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
use DateTime;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\NotSupportedException;
use League\Flysystem\SafeStorage;
use RuntimeException;
abstract class AbstractFtpAdapter extends AbstractAdapter
{
/**
* @var mixed
*/
protected $connection;
/**
* @var string
*/
protected $host;
/**
* @var int
*/
protected $port = 21;
/**
* @var bool
*/
protected $ssl = false;
/**
* @var int
*/
protected $timeout = 90;
/**
* @var bool
*/
protected $passive = true;
/**
* @var string
*/
protected $separator = '/';
/**
* @var string|null
*/
protected $root;
/**
* @var int
*/
protected $permPublic = 0744;
/**
* @var int
*/
protected $permPrivate = 0700;
/**
* @var array
*/
protected $configurable = [];
/**
* @var string
*/
protected $systemType;
/**
* @var SafeStorage
*/
protected $safeStorage;
/**
* True to enable timestamps for FTP servers that return unix-style listings.
*
* @var bool
*/
protected $enableTimestampsOnUnixListings = false;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config)
{
$this->safeStorage = new SafeStorage();
$this->setConfig($config);
}
/**
* Set the config.
*
* @param array $config
*
* @return $this
*/
public function setConfig(array $config)
{
foreach ($this->configurable as $setting) {
if ( ! isset($config[$setting])) {
continue;
}
$method = 'set' . ucfirst($setting);
if (method_exists($this, $method)) {
$this->$method($config[$setting]);
}
}
return $this;
}
/**
* Returns the host.
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set the host.
*
* @param string $host
*
* @return $this
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Set the public permission value.
*
* @param int $permPublic
*
* @return $this
*/
public function setPermPublic($permPublic)
{
$this->permPublic = $permPublic;
return $this;
}
/**
* Set the private permission value.
*
* @param int $permPrivate
*
* @return $this
*/
public function setPermPrivate($permPrivate)
{
$this->permPrivate = $permPrivate;
return $this;
}
/**
* Returns the ftp port.
*
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* Returns the root folder to work from.
*
* @return string
*/
public function getRoot()
{
return $this->root;
}
/**
* Set the ftp port.
*
* @param int|string $port
*
* @return $this
*/
public function setPort($port)
{
$this->port = (int) $port;
return $this;
}
/**
* Set the root folder to work from.
*
* @param string $root
*
* @return $this
*/
public function setRoot($root)
{
$this->root = rtrim($root, '\\/') . $this->separator;
return $this;
}
/**
* Returns the ftp username.
*
* @return string username
*/
public function getUsername()
{
$username = $this->safeStorage->retrieveSafely('username');
return $username !== null ? $username : 'anonymous';
}
/**
* Set ftp username.
*
* @param string $username
*
* @return $this
*/
public function setUsername($username)
{
$this->safeStorage->storeSafely('username', $username);
return $this;
}
/**
* Returns the password.
*
* @return string password
*/
public function getPassword()
{
return $this->safeStorage->retrieveSafely('password');
}
/**
* Set the ftp password.
*
* @param string $password
*
* @return $this
*/
public function setPassword($password)
{
$this->safeStorage->storeSafely('password', $password);
return $this;
}
/**
* Returns the amount of seconds before the connection will timeout.
*
* @return int
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* Set the amount of seconds before the connection should timeout.
*
* @param int $timeout
*
* @return $this
*/
public function setTimeout($timeout)
{
$this->timeout = (int) $timeout;
return $this;
}
/**
* Return the FTP system type.
*
* @return string
*/
public function getSystemType()
{
return $this->systemType;
}
/**
* Set the FTP system type (windows or unix).
*
* @param string $systemType
*
* @return $this
*/
public function setSystemType($systemType)
{
$this->systemType = strtolower($systemType);
return $this;
}
/**
* True to enable timestamps for FTP servers that return unix-style listings.
*
* @param bool $bool
*
* @return $this
*/
public function setEnableTimestampsOnUnixListings($bool = false)
{
$this->enableTimestampsOnUnixListings = $bool;
return $this;
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
return $this->listDirectoryContents($directory, $recursive);
}
abstract protected function listDirectoryContents($directory, $recursive = false);
/**
* Normalize a directory listing.
*
* @param array $listing
* @param string $prefix
*
* @return array directory listing
*/
protected function normalizeListing(array $listing, $prefix = '')
{
$base = $prefix;
$result = [];
$listing = $this->removeDotDirectories($listing);
while ($item = array_shift($listing)) {
if (preg_match('#^.*:$#', $item)) {
$base = preg_replace('~^\./*|:$~', '', $item);
continue;
}
$result[] = $this->normalizeObject($item, $base);
}
return $this->sortListing($result);
}
/**
* Sort a directory listing.
*
* @param array $result
*
* @return array sorted listing
*/
protected function sortListing(array $result)
{
$compare = function ($one, $two) {
return strnatcmp($one['path'], $two['path']);
};
usort($result, $compare);
return $result;
}
/**
* Normalize a file entry.
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*
* @throws NotSupportedException
*/
protected function normalizeObject($item, $base)
{
$systemType = $this->systemType ?: $this->detectSystemType($item);
if ($systemType === 'unix') {
return $this->normalizeUnixObject($item, $base);
} elseif ($systemType === 'windows') {
return $this->normalizeWindowsObject($item, $base);
}
throw NotSupportedException::forFtpSystemType($systemType);
}
/**
* Normalize a Unix file entry.
*
* Given $item contains:
* '-rw-r--r-- 1 ftp ftp 409 Aug 19 09:01 file1.txt'
*
* This function will return:
* [
* 'type' => 'file',
* 'path' => 'file1.txt',
* 'visibility' => 'public',
* 'size' => 409,
* 'timestamp' => 1566205260
* ]
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*/
protected function normalizeUnixObject($item, $base)
{
$item = preg_replace('#\s+#', ' ', trim($item), 7);
if (count(explode(' ', $item, 9)) !== 9) {
throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
}
list($permissions, /* $number */, /* $owner */, /* $group */, $size, $month, $day, $timeOrYear, $name) = explode(' ', $item, 9);
$type = $this->detectType($permissions);
$path = $base === '' ? $name : $base . $this->separator . $name;
if ($type === 'dir') {
return compact('type', 'path');
}
$permissions = $this->normalizePermissions($permissions);
$visibility = $permissions & 0044 ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE;
$size = (int) $size;
$result = compact('type', 'path', 'visibility', 'size');
if ($this->enableTimestampsOnUnixListings) {
$timestamp = $this->normalizeUnixTimestamp($month, $day, $timeOrYear);
$result += compact('timestamp');
}
return $result;
}
/**
* Only accurate to the minute (current year), or to the day.
*
* Inadequacies in timestamp accuracy are due to limitations of the FTP 'LIST' command
*
* Note: The 'MLSD' command is a machine-readable replacement for 'LIST'
* but many FTP servers do not support it :(
*
* @param string $month e.g. 'Aug'
* @param string $day e.g. '19'
* @param string $timeOrYear e.g. '09:01' OR '2015'
*
* @return int
*/
protected function normalizeUnixTimestamp($month, $day, $timeOrYear)
{
if (is_numeric($timeOrYear)) {
$year = $timeOrYear;
$hour = '00';
$minute = '00';
$seconds = '00';
} else {
$year = date('Y');
list($hour, $minute) = explode(':', $timeOrYear);
$seconds = '00';
}
$dateTime = DateTime::createFromFormat('Y-M-j-G:i:s', "{$year}-{$month}-{$day}-{$hour}:{$minute}:{$seconds}");
return $dateTime->getTimestamp();
}
/**
* Normalize a Windows/DOS file entry.
*
* @param string $item
* @param string $base
*
* @return array normalized file array
*/
protected function normalizeWindowsObject($item, $base)
{
$item = preg_replace('#\s+#', ' ', trim($item), 3);
if (count(explode(' ', $item, 4)) !== 4) {
throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
}
list($date, $time, $size, $name) = explode(' ', $item, 4);
$path = $base === '' ? $name : $base . $this->separator . $name;
// Check for the correct date/time format
$format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
$dt = DateTime::createFromFormat($format, $date . $time);
$timestamp = $dt ? $dt->getTimestamp() : (int) strtotime("$date $time");
if ($size === '<DIR>') {
$type = 'dir';
return compact('type', 'path', 'timestamp');
}
$type = 'file';
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
$size = (int) $size;
return compact('type', 'path', 'visibility', 'size', 'timestamp');
}
/**
* Get the system type from a listing item.
*
* @param string $item
*
* @return string the system type
*/
protected function detectSystemType($item)
{
return preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item) ? 'windows' : 'unix';
}
/**
* Get the file type from the permissions.
*
* @param string $permissions
*
* @return string file type
*/
protected function detectType($permissions)
{
return substr($permissions, 0, 1) === 'd' ? 'dir' : 'file';
}
/**
* Normalize a permissions string.
*
* @param string $permissions
*
* @return int
*/
protected function normalizePermissions($permissions)
{
// remove the type identifier
$permissions = substr($permissions, 1);
// map the string rights to the numeric counterparts
$map = ['-' => '0', 'r' => '4', 'w' => '2', 'x' => '1'];
$permissions = strtr($permissions, $map);
// split up the permission groups
$parts = str_split($permissions, 3);
// convert the groups
$mapper = function ($part) {
return array_sum(str_split($part));
};
// converts to decimal number
return octdec(implode('', array_map($mapper, $parts)));
}
/**
* Filter out dot-directories.
*
* @param array $list
*
* @return array
*/
public function removeDotDirectories(array $list)
{
$filter = function ($line) {
return $line !== '' && ! preg_match('#.* \.(\.)?$|^total#', $line);
};
return array_filter($list, $filter);
}
/**
* @inheritdoc
*/
public function has($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
return $this->getMetadata($path);
}
/**
* Ensure a directory exists.
*
* @param string $dirname
*/
public function ensureDirectory($dirname)
{
$dirname = (string) $dirname;
if ($dirname !== '' && ! $this->has($dirname)) {
$this->createDir($dirname, new Config());
}
}
/**
* @return mixed
*/
public function getConnection()
{
$tries = 0;
while ( ! $this->isConnected() && $tries < 3) {
$tries++;
$this->disconnect();
$this->connect();
}
return $this->connection;
}
/**
* Get the public permission value.
*
* @return int
*/
public function getPermPublic()
{
return $this->permPublic;
}
/**
* Get the private permission value.
*
* @return int
*/
public function getPermPrivate()
{
return $this->permPrivate;
}
/**
* Disconnect on destruction.
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Establish a connection.
*/
abstract public function connect();
/**
* Close the connection.
*/
abstract public function disconnect();
/**
* Check if a connection is active.
*
* @return bool
*/
abstract public function isConnected();
}

View File

@ -1,12 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
/**
* Adapters that implement this interface let the Filesystem know that files can be overwritten using the write
* functions and don't need the update function to be called. This can help improve performance when asserts are disabled.
*/
interface CanOverwriteFiles
{
}

View File

@ -1,572 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
use ErrorException;
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\Util;
use League\Flysystem\Util\MimeType;
use RuntimeException;
class Ftp extends AbstractFtpAdapter
{
use StreamedCopyTrait;
/**
* @var int
*/
protected $transferMode = FTP_BINARY;
/**
* @var null|bool
*/
protected $ignorePassiveAddress = null;
/**
* @var bool
*/
protected $recurseManually = false;
/**
* @var bool
*/
protected $utf8 = false;
/**
* @var array
*/
protected $configurable = [
'host',
'port',
'username',
'password',
'ssl',
'timeout',
'root',
'permPrivate',
'permPublic',
'passive',
'transferMode',
'systemType',
'ignorePassiveAddress',
'recurseManually',
'utf8',
'enableTimestampsOnUnixListings',
];
/**
* @var bool
*/
protected $isPureFtpd;
/**
* Set the transfer mode.
*
* @param int $mode
*
* @return $this
*/
public function setTransferMode($mode)
{
$this->transferMode = $mode;
return $this;
}
/**
* Set if Ssl is enabled.
*
* @param bool $ssl
*
* @return $this
*/
public function setSsl($ssl)
{
$this->ssl = (bool) $ssl;
return $this;
}
/**
* Set if passive mode should be used.
*
* @param bool $passive
*/
public function setPassive($passive = true)
{
$this->passive = $passive;
}
/**
* @param bool $ignorePassiveAddress
*/
public function setIgnorePassiveAddress($ignorePassiveAddress)
{
$this->ignorePassiveAddress = $ignorePassiveAddress;
}
/**
* @param bool $recurseManually
*/
public function setRecurseManually($recurseManually)
{
$this->recurseManually = $recurseManually;
}
/**
* @param bool $utf8
*/
public function setUtf8($utf8)
{
$this->utf8 = (bool) $utf8;
}
/**
* Connect to the FTP server.
*/
public function connect()
{
if ($this->ssl) {
$this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
} else {
$this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
}
if ( ! $this->connection) {
throw new RuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort());
}
$this->login();
$this->setUtf8Mode();
$this->setConnectionPassiveMode();
$this->setConnectionRoot();
$this->isPureFtpd = $this->isPureFtpdServer();
}
/**
* Set the connection to UTF-8 mode.
*/
protected function setUtf8Mode()
{
if ($this->utf8) {
$response = ftp_raw($this->connection, "OPTS UTF8 ON");
if (substr($response[0], 0, 3) !== '200') {
throw new RuntimeException(
'Could not set UTF-8 mode for connection: ' . $this->getHost() . '::' . $this->getPort()
);
}
}
}
/**
* Set the connections to passive mode.
*
* @throws RuntimeException
*/
protected function setConnectionPassiveMode()
{
if (is_bool($this->ignorePassiveAddress) && defined('FTP_USEPASVADDRESS')) {
ftp_set_option($this->connection, FTP_USEPASVADDRESS, ! $this->ignorePassiveAddress);
}
if ( ! ftp_pasv($this->connection, $this->passive)) {
throw new RuntimeException(
'Could not set passive mode for connection: ' . $this->getHost() . '::' . $this->getPort()
);
}
}
/**
* Set the connection root.
*/
protected function setConnectionRoot()
{
$root = $this->getRoot();
$connection = $this->connection;
if ($root && ! ftp_chdir($connection, $root)) {
throw new RuntimeException('Root is invalid or does not exist: ' . $this->getRoot());
}
// Store absolute path for further reference.
// This is needed when creating directories and
// initial root was a relative path, else the root
// would be relative to the chdir'd path.
$this->root = ftp_pwd($connection);
}
/**
* Login.
*
* @throws RuntimeException
*/
protected function login()
{
set_error_handler(function () {
});
$isLoggedIn = ftp_login(
$this->connection,
$this->getUsername(),
$this->getPassword()
);
restore_error_handler();
if ( ! $isLoggedIn) {
$this->disconnect();
throw new RuntimeException(
'Could not login with connection: ' . $this->getHost() . '::' . $this->getPort(
) . ', username: ' . $this->getUsername()
);
}
}
/**
* Disconnect from the FTP server.
*/
public function disconnect()
{
if (is_resource($this->connection)) {
ftp_close($this->connection);
}
$this->connection = null;
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$stream = fopen('php://temp', 'w+b');
fwrite($stream, $contents);
rewind($stream);
$result = $this->writeStream($path, $stream, $config);
fclose($stream);
if ($result === false) {
return false;
}
$result['contents'] = $contents;
$result['mimetype'] = $config->get('mimetype') ?: Util::guessMimeType($path, $contents);
return $result;
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, Config $config)
{
$this->ensureDirectory(Util::dirname($path));
if ( ! ftp_fput($this->getConnection(), $path, $resource, $this->transferMode)) {
return false;
}
if ($visibility = $config->get('visibility')) {
$this->setVisibility($path, $visibility);
}
$type = 'file';
return compact('type', 'path', 'visibility');
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
return $this->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, Config $config)
{
return $this->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
return ftp_rename($this->getConnection(), $path, $newpath);
}
/**
* @inheritdoc
*/
public function delete($path)
{
return ftp_delete($this->getConnection(), $path);
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$connection = $this->getConnection();
$contents = array_reverse($this->listDirectoryContents($dirname, false));
foreach ($contents as $object) {
if ($object['type'] === 'file') {
if ( ! ftp_delete($connection, $object['path'])) {
return false;
}
} elseif ( ! $this->deleteDir($object['path'])) {
return false;
}
}
return ftp_rmdir($connection, $dirname);
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
$connection = $this->getConnection();
$directories = explode('/', $dirname);
foreach ($directories as $directory) {
if (false === $this->createActualDirectory($directory, $connection)) {
$this->setConnectionRoot();
return false;
}
ftp_chdir($connection, $directory);
}
$this->setConnectionRoot();
return ['type' => 'dir', 'path' => $dirname];
}
/**
* Create a directory.
*
* @param string $directory
* @param resource $connection
*
* @return bool
*/
protected function createActualDirectory($directory, $connection)
{
// List the current directory
$listing = ftp_nlist($connection, '.') ?: [];
foreach ($listing as $key => $item) {
if (preg_match('~^\./.*~', $item)) {
$listing[$key] = substr($item, 2);
}
}
if (in_array($directory, $listing, true)) {
return true;
}
return (boolean) ftp_mkdir($connection, $directory);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
if ($path === '') {
return ['type' => 'dir', 'path' => ''];
}
if (@ftp_chdir($this->getConnection(), $path) === true) {
$this->setConnectionRoot();
return ['type' => 'dir', 'path' => $path];
}
$listing = $this->ftpRawlist('-A', str_replace('*', '\\*', $path));
if (empty($listing) || in_array('total 0', $listing, true)) {
return false;
}
if (preg_match('/.* not found/', $listing[0])) {
return false;
}
if (preg_match('/^total [0-9]*$/', $listing[0])) {
array_shift($listing);
}
return $this->normalizeObject($listing[0], '');
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
if ( ! $metadata = $this->getMetadata($path)) {
return false;
}
$metadata['mimetype'] = MimeType::detectByFilename($path);
return $metadata;
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
$timestamp = ftp_mdtm($this->getConnection(), $path);
return ($timestamp !== -1) ? ['path' => $path, 'timestamp' => $timestamp] : false;
}
/**
* @inheritdoc
*/
public function read($path)
{
if ( ! $object = $this->readStream($path)) {
return false;
}
$object['contents'] = stream_get_contents($object['stream']);
fclose($object['stream']);
unset($object['stream']);
return $object;
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$stream = fopen('php://temp', 'w+b');
$result = ftp_fget($this->getConnection(), $stream, $path, $this->transferMode);
rewind($stream);
if ( ! $result) {
fclose($stream);
return false;
}
return ['type' => 'file', 'path' => $path, 'stream' => $stream];
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$mode = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? $this->getPermPublic() : $this->getPermPrivate();
if ( ! ftp_chmod($this->getConnection(), $mode, $path)) {
return false;
}
return compact('path', 'visibility');
}
/**
* @inheritdoc
*
* @param string $directory
*/
protected function listDirectoryContents($directory, $recursive = true)
{
$directory = str_replace('*', '\\*', $directory);
if ($recursive && $this->recurseManually) {
return $this->listDirectoryContentsRecursive($directory);
}
$options = $recursive ? '-alnR' : '-aln';
$listing = $this->ftpRawlist($options, $directory);
return $listing ? $this->normalizeListing($listing, $directory) : [];
}
/**
* @inheritdoc
*
* @param string $directory
*/
protected function listDirectoryContentsRecursive($directory)
{
$listing = $this->normalizeListing($this->ftpRawlist('-aln', $directory) ?: [], $directory);
$output = [];
foreach ($listing as $item) {
$output[] = $item;
if ($item['type'] !== 'dir') {
continue;
}
$output = array_merge($output, $this->listDirectoryContentsRecursive($item['path']));
}
return $output;
}
/**
* Check if the connection is open.
*
* @return bool
*
* @throws ErrorException
*/
public function isConnected()
{
try {
return is_resource($this->connection) && ftp_rawlist($this->connection, $this->getRoot()) !== false;
} catch (ErrorException $e) {
if (strpos($e->getMessage(), 'ftp_rawlist') === false) {
throw $e;
}
return false;
}
}
/**
* @return bool
*/
protected function isPureFtpdServer()
{
$response = ftp_raw($this->connection, 'HELP');
return stripos(implode(' ', $response), 'Pure-FTPd') !== false;
}
/**
* The ftp_rawlist function with optional escaping.
*
* @param string $options
* @param string $path
*
* @return array
*/
protected function ftpRawlist($options, $path)
{
$connection = $this->getConnection();
if ($this->isPureFtpd) {
$path = str_replace(' ', '\ ', $path);
}
return ftp_rawlist($connection, $options . ' ' . $path);
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
class Ftpd extends Ftp
{
/**
* @inheritdoc
*/
public function getMetadata($path)
{
if ($path === '') {
return ['type' => 'dir', 'path' => ''];
}
if (@ftp_chdir($this->getConnection(), $path) === true) {
$this->setConnectionRoot();
return ['type' => 'dir', 'path' => $path];
}
if ( ! ($object = ftp_raw($this->getConnection(), 'STAT ' . $path)) || count($object) < 3) {
return false;
}
if (substr($object[1], 0, 5) === "ftpd:") {
return false;
}
return $this->normalizeObject($object[1], '');
}
/**
* @inheritdoc
*/
protected function listDirectoryContents($directory, $recursive = true)
{
$listing = ftp_rawlist($this->getConnection(), $directory, $recursive);
if ($listing === false || ( ! empty($listing) && substr($listing[0], 0, 5) === "ftpd:")) {
return [];
}
return $this->normalizeListing($listing, $directory);
}
}

View File

@ -1,532 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
use DirectoryIterator;
use FilesystemIterator;
use finfo as Finfo;
use League\Flysystem\Config;
use League\Flysystem\Exception;
use League\Flysystem\NotSupportedException;
use League\Flysystem\UnreadableFileException;
use League\Flysystem\Util;
use LogicException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
class Local extends AbstractAdapter
{
/**
* @var int
*/
const SKIP_LINKS = 0001;
/**
* @var int
*/
const DISALLOW_LINKS = 0002;
/**
* @var array
*/
protected static $permissions = [
'file' => [
'public' => 0644,
'private' => 0600,
],
'dir' => [
'public' => 0755,
'private' => 0700,
],
];
/**
* @var string
*/
protected $pathSeparator = DIRECTORY_SEPARATOR;
/**
* @var array
*/
protected $permissionMap;
/**
* @var int
*/
protected $writeFlags;
/**
* @var int
*/
private $linkHandling;
/**
* Constructor.
*
* @param string $root
* @param int $writeFlags
* @param int $linkHandling
* @param array $permissions
*
* @throws LogicException
*/
public function __construct($root, $writeFlags = LOCK_EX, $linkHandling = self::DISALLOW_LINKS, array $permissions = [])
{
$root = is_link($root) ? realpath($root) : $root;
$this->permissionMap = array_replace_recursive(static::$permissions, $permissions);
$this->ensureDirectory($root);
if ( ! is_dir($root) || ! is_readable($root)) {
throw new LogicException('The root path ' . $root . ' is not readable.');
}
$this->setPathPrefix($root);
$this->writeFlags = $writeFlags;
$this->linkHandling = $linkHandling;
}
/**
* Ensure the root directory exists.
*
* @param string $root root directory path
*
* @return void
*
* @throws Exception in case the root directory can not be created
*/
protected function ensureDirectory($root)
{
if ( ! is_dir($root)) {
$umask = umask(0);
if ( ! @mkdir($root, $this->permissionMap['dir']['public'], true)) {
$mkdirError = error_get_last();
}
umask($umask);
clearstatcache(false, $root);
if ( ! is_dir($root)) {
$errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage));
}
}
}
/**
* @inheritdoc
*/
public function has($path)
{
$location = $this->applyPathPrefix($path);
return file_exists($location);
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$location = $this->applyPathPrefix($path);
$this->ensureDirectory(dirname($location));
if (($size = file_put_contents($location, $contents, $this->writeFlags)) === false) {
return false;
}
$type = 'file';
$result = compact('contents', 'type', 'size', 'path');
if ($visibility = $config->get('visibility')) {
$result['visibility'] = $visibility;
$this->setVisibility($path, $visibility);
}
return $result;
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, Config $config)
{
$location = $this->applyPathPrefix($path);
$this->ensureDirectory(dirname($location));
$stream = fopen($location, 'w+b');
if ( ! $stream || stream_copy_to_stream($resource, $stream) === false || ! fclose($stream)) {
return false;
}
$type = 'file';
$result = compact('type', 'path');
if ($visibility = $config->get('visibility')) {
$this->setVisibility($path, $visibility);
$result['visibility'] = $visibility;
}
return $result;
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$location = $this->applyPathPrefix($path);
$stream = fopen($location, 'rb');
return ['type' => 'file', 'path' => $path, 'stream' => $stream];
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, Config $config)
{
return $this->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
$location = $this->applyPathPrefix($path);
$size = file_put_contents($location, $contents, $this->writeFlags);
if ($size === false) {
return false;
}
$type = 'file';
$result = compact('type', 'path', 'size', 'contents');
if ($mimetype = $config->get('mimetype') ?: Util::guessMimeType($path, $contents)) {
$result['mimetype'] = $mimetype;
}
return $result;
}
/**
* @inheritdoc
*/
public function read($path)
{
$location = $this->applyPathPrefix($path);
$contents = @file_get_contents($location);
if ($contents === false) {
return false;
}
return ['type' => 'file', 'path' => $path, 'contents' => $contents];
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
$location = $this->applyPathPrefix($path);
$destination = $this->applyPathPrefix($newpath);
$parentDirectory = $this->applyPathPrefix(Util::dirname($newpath));
$this->ensureDirectory($parentDirectory);
return rename($location, $destination);
}
/**
* @inheritdoc
*/
public function copy($path, $newpath)
{
$location = $this->applyPathPrefix($path);
$destination = $this->applyPathPrefix($newpath);
$this->ensureDirectory(dirname($destination));
return copy($location, $destination);
}
/**
* @inheritdoc
*/
public function delete($path)
{
$location = $this->applyPathPrefix($path);
return @unlink($location);
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
$result = [];
$location = $this->applyPathPrefix($directory);
if ( ! is_dir($location)) {
return [];
}
$iterator = $recursive ? $this->getRecursiveDirectoryIterator($location) : $this->getDirectoryIterator($location);
foreach ($iterator as $file) {
$path = $this->getFilePath($file);
if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) {
continue;
}
$result[] = $this->normalizeFileInfo($file);
}
unset($iterator);
return array_filter($result);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
$location = $this->applyPathPrefix($path);
clearstatcache(false, $location);
$info = new SplFileInfo($location);
return $this->normalizeFileInfo($info);
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
$location = $this->applyPathPrefix($path);
$finfo = new Finfo(FILEINFO_MIME_TYPE);
$mimetype = $finfo->file($location);
if (in_array($mimetype, ['application/octet-stream', 'inode/x-empty', 'application/x-empty'])) {
$mimetype = Util\MimeType::detectByFilename($location);
}
return ['path' => $path, 'type' => 'file', 'mimetype' => $mimetype];
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
return $this->getMetadata($path);
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
$location = $this->applyPathPrefix($path);
clearstatcache(false, $location);
$permissions = octdec(substr(sprintf('%o', fileperms($location)), -4));
$type = is_dir($location) ? 'dir' : 'file';
foreach ($this->permissionMap[$type] as $visibility => $visibilityPermissions) {
if ($visibilityPermissions == $permissions) {
return compact('path', 'visibility');
}
}
$visibility = substr(sprintf('%o', fileperms($location)), -4);
return compact('path', 'visibility');
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$location = $this->applyPathPrefix($path);
$type = is_dir($location) ? 'dir' : 'file';
$success = chmod($location, $this->permissionMap[$type][$visibility]);
if ($success === false) {
return false;
}
return compact('path', 'visibility');
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
$location = $this->applyPathPrefix($dirname);
$umask = umask(0);
$visibility = $config->get('visibility', 'public');
$return = ['path' => $dirname, 'type' => 'dir'];
if ( ! is_dir($location)) {
if (false === @mkdir($location, $this->permissionMap['dir'][$visibility], true)
|| false === is_dir($location)) {
$return = false;
}
}
umask($umask);
return $return;
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$location = $this->applyPathPrefix($dirname);
if ( ! is_dir($location)) {
return false;
}
$contents = $this->getRecursiveDirectoryIterator($location, RecursiveIteratorIterator::CHILD_FIRST);
/** @var SplFileInfo $file */
foreach ($contents as $file) {
$this->guardAgainstUnreadableFileInfo($file);
$this->deleteFileInfoObject($file);
}
unset($contents);
return rmdir($location);
}
/**
* @param SplFileInfo $file
*/
protected function deleteFileInfoObject(SplFileInfo $file)
{
switch ($file->getType()) {
case 'dir':
rmdir($file->getRealPath());
break;
case 'link':
unlink($file->getPathname());
break;
default:
unlink($file->getRealPath());
}
}
/**
* Normalize the file info.
*
* @param SplFileInfo $file
*
* @return array|void
*
* @throws NotSupportedException
*/
protected function normalizeFileInfo(SplFileInfo $file)
{
if ( ! $file->isLink()) {
return $this->mapFileInfo($file);
}
if ($this->linkHandling & self::DISALLOW_LINKS) {
throw NotSupportedException::forLink($file);
}
}
/**
* Get the normalized path from a SplFileInfo object.
*
* @param SplFileInfo $file
*
* @return string
*/
protected function getFilePath(SplFileInfo $file)
{
$location = $file->getPathname();
$path = $this->removePathPrefix($location);
return trim(str_replace('\\', '/', $path), '/');
}
/**
* @param string $path
* @param int $mode
*
* @return RecursiveIteratorIterator
*/
protected function getRecursiveDirectoryIterator($path, $mode = RecursiveIteratorIterator::SELF_FIRST)
{
return new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
$mode
);
}
/**
* @param string $path
*
* @return DirectoryIterator
*/
protected function getDirectoryIterator($path)
{
$iterator = new DirectoryIterator($path);
return $iterator;
}
/**
* @param SplFileInfo $file
*
* @return array
*/
protected function mapFileInfo(SplFileInfo $file)
{
$normalized = [
'type' => $file->getType(),
'path' => $this->getFilePath($file),
];
$normalized['timestamp'] = $file->getMTime();
if ($normalized['type'] === 'file') {
$normalized['size'] = $file->getSize();
}
return $normalized;
}
/**
* @param SplFileInfo $file
*
* @throws UnreadableFileException
*/
protected function guardAgainstUnreadableFileInfo(SplFileInfo $file)
{
if ( ! $file->isReadable()) {
throw UnreadableFileException::forFileInfo($file);
}
}
}

View File

@ -1,144 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
use League\Flysystem\Adapter\Polyfill\StreamedTrait;
use League\Flysystem\Config;
class NullAdapter extends AbstractAdapter
{
use StreamedTrait;
use StreamedCopyTrait;
/**
* Check whether a file is present.
*
* @param string $path
*
* @return bool
*/
public function has($path)
{
return false;
}
/**
* @inheritdoc
*/
public function write($path, $contents, Config $config)
{
$type = 'file';
$result = compact('contents', 'type', 'path');
if ($visibility = $config->get('visibility')) {
$result['visibility'] = $visibility;
}
return $result;
}
/**
* @inheritdoc
*/
public function update($path, $contents, Config $config)
{
return false;
}
/**
* @inheritdoc
*/
public function read($path)
{
return false;
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
return false;
}
/**
* @inheritdoc
*/
public function delete($path)
{
return false;
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
return [];
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getSize($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
return false;
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
return false;
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
return compact('visibility');
}
/**
* @inheritdoc
*/
public function createDir($dirname, Config $config)
{
return ['path' => $dirname, 'type' => 'dir'];
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
return false;
}
}

View File

@ -1,33 +0,0 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use LogicException;
trait NotSupportingVisibilityTrait
{
/**
* Get the visibility of a file.
*
* @param string $path
*
* @throws LogicException
*/
public function getVisibility($path)
{
throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path);
}
/**
* Set the visibility for a file.
*
* @param string $path
* @param string $visibility
*
* @throws LogicException
*/
public function setVisibility($path, $visibility)
{
throw new LogicException(get_class($this) . ' does not support visibility. Path: ' . $path . ', visibility: ' . $visibility);
}
}

View File

@ -1,51 +0,0 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use League\Flysystem\Config;
trait StreamedCopyTrait
{
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function copy($path, $newpath)
{
$response = $this->readStream($path);
if ($response === false || ! is_resource($response['stream'])) {
return false;
}
$result = $this->writeStream($newpath, $response['stream'], new Config());
if ($result !== false && is_resource($response['stream'])) {
fclose($response['stream']);
}
return $result !== false;
}
// Required abstract method
/**
* @param string $path
*
* @return resource
*/
abstract public function readStream($path);
/**
* @param string $path
* @param resource $resource
* @param Config $config
*
* @return resource
*/
abstract public function writeStream($path, $resource, Config $config);
}

View File

@ -1,44 +0,0 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
/**
* A helper for adapters that only handle strings to provide read streams.
*/
trait StreamedReadingTrait
{
/**
* Reads a file as a stream.
*
* @param string $path
*
* @return array|false
*
* @see League\Flysystem\ReadInterface::readStream()
*/
public function readStream($path)
{
if ( ! $data = $this->read($path)) {
return false;
}
$stream = fopen('php://temp', 'w+b');
fwrite($stream, $data['contents']);
rewind($stream);
$data['stream'] = $stream;
unset($data['contents']);
return $data;
}
/**
* Reads a file.
*
* @param string $path
*
* @return array|false
*
* @see League\Flysystem\ReadInterface::read()
*/
abstract public function read($path);
}

View File

@ -1,9 +0,0 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
trait StreamedTrait
{
use StreamedReadingTrait;
use StreamedWritingTrait;
}

View File

@ -1,60 +0,0 @@
<?php
namespace League\Flysystem\Adapter\Polyfill;
use League\Flysystem\Config;
use League\Flysystem\Util;
trait StreamedWritingTrait
{
/**
* Stream fallback delegator.
*
* @param string $path
* @param resource $resource
* @param Config $config
* @param string $fallback
*
* @return mixed fallback result
*/
protected function stream($path, $resource, Config $config, $fallback)
{
Util::rewindStream($resource);
$contents = stream_get_contents($resource);
$fallbackCall = [$this, $fallback];
return call_user_func($fallbackCall, $path, $contents, $config);
}
/**
* Write using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config
*
* @return mixed false or file metadata
*/
public function writeStream($path, $resource, Config $config)
{
return $this->stream($path, $resource, $config, 'write');
}
/**
* Update a file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object or visibility setting
*
* @return mixed false of file metadata
*/
public function updateStream($path, $resource, Config $config)
{
return $this->stream($path, $resource, $config, 'update');
}
// Required abstract methods
abstract public function write($pash, $contents, Config $config);
abstract public function update($pash, $contents, Config $config);
}

View File

@ -1,8 +0,0 @@
<?php
namespace League\Flysystem\Adapter;
class SynologyFtp extends Ftpd
{
// This class merely exists because of BC.
}

View File

@ -1,118 +0,0 @@
<?php
namespace League\Flysystem;
interface AdapterInterface extends ReadInterface
{
/**
* @const VISIBILITY_PUBLIC public visibility
*/
const VISIBILITY_PUBLIC = 'public';
/**
* @const VISIBILITY_PRIVATE private visibility
*/
const VISIBILITY_PRIVATE = 'private';
/**
* Write a new file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function write($path, $contents, Config $config);
/**
* Write a new file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function writeStream($path, $resource, Config $config);
/**
* Update a file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function update($path, $contents, Config $config);
/**
* Update a file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function updateStream($path, $resource, Config $config);
/**
* Rename a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function rename($path, $newpath);
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function copy($path, $newpath);
/**
* Delete a file.
*
* @param string $path
*
* @return bool
*/
public function delete($path);
/**
* Delete a directory.
*
* @param string $dirname
*
* @return bool
*/
public function deleteDir($dirname);
/**
* Create a directory.
*
* @param string $dirname directory name
* @param Config $config
*
* @return array|false
*/
public function createDir($dirname, Config $config);
/**
* Set the visibility for a file.
*
* @param string $path
* @param string $visibility
*
* @return array|false file meta data
*/
public function setVisibility($path, $visibility);
}

View File

@ -1,107 +0,0 @@
<?php
namespace League\Flysystem;
class Config
{
/**
* @var array
*/
protected $settings = [];
/**
* @var Config|null
*/
protected $fallback;
/**
* Constructor.
*
* @param array $settings
*/
public function __construct(array $settings = [])
{
$this->settings = $settings;
}
/**
* Get a setting.
*
* @param string $key
* @param mixed $default
*
* @return mixed config setting or default when not found
*/
public function get($key, $default = null)
{
if ( ! array_key_exists($key, $this->settings)) {
return $this->getDefault($key, $default);
}
return $this->settings[$key];
}
/**
* Check if an item exists by key.
*
* @param string $key
*
* @return bool
*/
public function has($key)
{
if (array_key_exists($key, $this->settings)) {
return true;
}
return $this->fallback instanceof Config
? $this->fallback->has($key)
: false;
}
/**
* Try to retrieve a default setting from a config fallback.
*
* @param string $key
* @param mixed $default
*
* @return mixed config setting or default when not found
*/
protected function getDefault($key, $default)
{
if ( ! $this->fallback) {
return $default;
}
return $this->fallback->get($key, $default);
}
/**
* Set a setting.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function set($key, $value)
{
$this->settings[$key] = $value;
return $this;
}
/**
* Set the fallback.
*
* @param Config $fallback
*
* @return $this
*/
public function setFallback(Config $fallback)
{
$this->fallback = $fallback;
return $this;
}
}

View File

@ -1,49 +0,0 @@
<?php
namespace League\Flysystem;
/**
* @internal
*/
trait ConfigAwareTrait
{
/**
* @var Config
*/
protected $config;
/**
* Set the config.
*
* @param Config|array|null $config
*/
protected function setConfig($config)
{
$this->config = $config ? Util::ensureConfig($config) : new Config;
}
/**
* Get the Config.
*
* @return Config config object
*/
public function getConfig()
{
return $this->config;
}
/**
* Convert a config array to a Config object with the correct fallback.
*
* @param array $config
*
* @return Config
*/
protected function prepareConfig(array $config)
{
$config = new Config($config);
$config->setFallback($this->getConfig());
return $config;
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace League\Flysystem;
/**
* @deprecated
*/
class Directory extends Handler
{
/**
* Delete the directory.
*
* @return bool
*/
public function delete()
{
return $this->filesystem->deleteDir($this->path);
}
/**
* List the directory contents.
*
* @param bool $recursive
*
* @return array|bool directory contents or false
*/
public function getContents($recursive = false)
{
return $this->filesystem->listContents($this->path, $recursive);
}
}

View File

@ -1,8 +0,0 @@
<?php
namespace League\Flysystem;
class Exception extends \Exception
{
//
}

View File

@ -1,205 +0,0 @@
<?php
namespace League\Flysystem;
/**
* @deprecated
*/
class File extends Handler
{
/**
* Check whether the file exists.
*
* @return bool
*/
public function exists()
{
return $this->filesystem->has($this->path);
}
/**
* Read the file.
*
* @return string|false file contents
*/
public function read()
{
return $this->filesystem->read($this->path);
}
/**
* Read the file as a stream.
*
* @return resource|false file stream
*/
public function readStream()
{
return $this->filesystem->readStream($this->path);
}
/**
* Write the new file.
*
* @param string $content
*
* @return bool success boolean
*/
public function write($content)
{
return $this->filesystem->write($this->path, $content);
}
/**
* Write the new file using a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function writeStream($resource)
{
return $this->filesystem->writeStream($this->path, $resource);
}
/**
* Update the file contents.
*
* @param string $content
*
* @return bool success boolean
*/
public function update($content)
{
return $this->filesystem->update($this->path, $content);
}
/**
* Update the file contents with a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function updateStream($resource)
{
return $this->filesystem->updateStream($this->path, $resource);
}
/**
* Create the file or update if exists.
*
* @param string $content
*
* @return bool success boolean
*/
public function put($content)
{
return $this->filesystem->put($this->path, $content);
}
/**
* Create the file or update if exists using a stream.
*
* @param resource $resource
*
* @return bool success boolean
*/
public function putStream($resource)
{
return $this->filesystem->putStream($this->path, $resource);
}
/**
* Rename the file.
*
* @param string $newpath
*
* @return bool success boolean
*/
public function rename($newpath)
{
if ($this->filesystem->rename($this->path, $newpath)) {
$this->path = $newpath;
return true;
}
return false;
}
/**
* Copy the file.
*
* @param string $newpath
*
* @return File|false new file or false
*/
public function copy($newpath)
{
if ($this->filesystem->copy($this->path, $newpath)) {
return new File($this->filesystem, $newpath);
}
return false;
}
/**
* Get the file's timestamp.
*
* @return string|false The timestamp or false on failure.
*/
public function getTimestamp()
{
return $this->filesystem->getTimestamp($this->path);
}
/**
* Get the file's mimetype.
*
* @return string|false The file mime-type or false on failure.
*/
public function getMimetype()
{
return $this->filesystem->getMimetype($this->path);
}
/**
* Get the file's visibility.
*
* @return string|false The visibility (public|private) or false on failure.
*/
public function getVisibility()
{
return $this->filesystem->getVisibility($this->path);
}
/**
* Get the file's metadata.
*
* @return array|false The file metadata or false on failure.
*/
public function getMetadata()
{
return $this->filesystem->getMetadata($this->path);
}
/**
* Get the file size.
*
* @return int|false The file size or false on failure.
*/
public function getSize()
{
return $this->filesystem->getSize($this->path);
}
/**
* Delete the file.
*
* @return bool success boolean
*/
public function delete()
{
return $this->filesystem->delete($this->path);
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace League\Flysystem;
use Exception as BaseException;
class FileExistsException extends Exception
{
/**
* @var string
*/
protected $path;
/**
* Constructor.
*
* @param string $path
* @param int $code
* @param BaseException $previous
*/
public function __construct($path, $code = 0, BaseException $previous = null)
{
$this->path = $path;
parent::__construct('File already exists at path: ' . $this->getPath(), $code, $previous);
}
/**
* Get the path which was found.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace League\Flysystem;
use Exception as BaseException;
class FileNotFoundException extends Exception
{
/**
* @var string
*/
protected $path;
/**
* Constructor.
*
* @param string $path
* @param int $code
* @param \Exception $previous
*/
public function __construct($path, $code = 0, BaseException $previous = null)
{
$this->path = $path;
parent::__construct('File not found at path: ' . $this->getPath(), $code, $previous);
}
/**
* Get the path which was not found.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
}

View File

@ -1,408 +0,0 @@
<?php
namespace League\Flysystem;
use InvalidArgumentException;
use League\Flysystem\Adapter\CanOverwriteFiles;
use League\Flysystem\Plugin\PluggableTrait;
use League\Flysystem\Util\ContentListingFormatter;
/**
* @method array getWithMetadata(string $path, array $metadata)
* @method bool forceCopy(string $path, string $newpath)
* @method bool forceRename(string $path, string $newpath)
* @method array listFiles(string $path = '', boolean $recursive = false)
* @method array listPaths(string $path = '', boolean $recursive = false)
* @method array listWith(array $keys = [], $directory = '', $recursive = false)
*/
class Filesystem implements FilesystemInterface
{
use PluggableTrait;
use ConfigAwareTrait;
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* Constructor.
*
* @param AdapterInterface $adapter
* @param Config|array $config
*/
public function __construct(AdapterInterface $adapter, $config = null)
{
$this->adapter = $adapter;
$this->setConfig($config);
}
/**
* Get the Adapter.
*
* @return AdapterInterface adapter
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* @inheritdoc
*/
public function has($path)
{
$path = Util::normalizePath($path);
return strlen($path) === 0 ? false : (bool) $this->getAdapter()->has($path);
}
/**
* @inheritdoc
*/
public function write($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$this->assertAbsent($path);
$config = $this->prepareConfig($config);
return (bool) $this->getAdapter()->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function writeStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$this->assertAbsent($path);
$config = $this->prepareConfig($config);
Util::rewindStream($resource);
return (bool) $this->getAdapter()->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function put($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
if ( ! $this->getAdapter() instanceof CanOverwriteFiles && $this->has($path)) {
return (bool) $this->getAdapter()->update($path, $contents, $config);
}
return (bool) $this->getAdapter()->write($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function putStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
Util::rewindStream($resource);
if ( ! $this->getAdapter() instanceof CanOverwriteFiles && $this->has($path)) {
return (bool) $this->getAdapter()->updateStream($path, $resource, $config);
}
return (bool) $this->getAdapter()->writeStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function readAndDelete($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
$contents = $this->read($path);
if ($contents === false) {
return false;
}
$this->delete($path);
return $contents;
}
/**
* @inheritdoc
*/
public function update($path, $contents, array $config = [])
{
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
$this->assertPresent($path);
return (bool) $this->getAdapter()->update($path, $contents, $config);
}
/**
* @inheritdoc
*/
public function updateStream($path, $resource, array $config = [])
{
if ( ! is_resource($resource)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #2 to be a valid resource.');
}
$path = Util::normalizePath($path);
$config = $this->prepareConfig($config);
$this->assertPresent($path);
Util::rewindStream($resource);
return (bool) $this->getAdapter()->updateStream($path, $resource, $config);
}
/**
* @inheritdoc
*/
public function read($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if ( ! ($object = $this->getAdapter()->read($path))) {
return false;
}
return $object['contents'];
}
/**
* @inheritdoc
*/
public function readStream($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if ( ! $object = $this->getAdapter()->readStream($path)) {
return false;
}
return $object['stream'];
}
/**
* @inheritdoc
*/
public function rename($path, $newpath)
{
$path = Util::normalizePath($path);
$newpath = Util::normalizePath($newpath);
$this->assertPresent($path);
$this->assertAbsent($newpath);
return (bool) $this->getAdapter()->rename($path, $newpath);
}
/**
* @inheritdoc
*/
public function copy($path, $newpath)
{
$path = Util::normalizePath($path);
$newpath = Util::normalizePath($newpath);
$this->assertPresent($path);
$this->assertAbsent($newpath);
return $this->getAdapter()->copy($path, $newpath);
}
/**
* @inheritdoc
*/
public function delete($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
return $this->getAdapter()->delete($path);
}
/**
* @inheritdoc
*/
public function deleteDir($dirname)
{
$dirname = Util::normalizePath($dirname);
if ($dirname === '') {
throw new RootViolationException('Root directories can not be deleted.');
}
return (bool) $this->getAdapter()->deleteDir($dirname);
}
/**
* @inheritdoc
*/
public function createDir($dirname, array $config = [])
{
$dirname = Util::normalizePath($dirname);
$config = $this->prepareConfig($config);
return (bool) $this->getAdapter()->createDir($dirname, $config);
}
/**
* @inheritdoc
*/
public function listContents($directory = '', $recursive = false)
{
$directory = Util::normalizePath($directory);
$contents = $this->getAdapter()->listContents($directory, $recursive);
return (new ContentListingFormatter($directory, $recursive, $this->config->get('case_sensitive', true)))
->formatListing($contents);
}
/**
* @inheritdoc
*/
public function getMimetype($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getMimetype($path)) || ! array_key_exists('mimetype', $object)) {
return false;
}
return $object['mimetype'];
}
/**
* @inheritdoc
*/
public function getTimestamp($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getTimestamp($path)) || ! array_key_exists('timestamp', $object)) {
return false;
}
return $object['timestamp'];
}
/**
* @inheritdoc
*/
public function getVisibility($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getVisibility($path)) || ! array_key_exists('visibility', $object)) {
return false;
}
return $object['visibility'];
}
/**
* @inheritdoc
*/
public function getSize($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
if (( ! $object = $this->getAdapter()->getSize($path)) || ! array_key_exists('size', $object)) {
return false;
}
return (int) $object['size'];
}
/**
* @inheritdoc
*/
public function setVisibility($path, $visibility)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
return (bool) $this->getAdapter()->setVisibility($path, $visibility);
}
/**
* @inheritdoc
*/
public function getMetadata($path)
{
$path = Util::normalizePath($path);
$this->assertPresent($path);
return $this->getAdapter()->getMetadata($path);
}
/**
* @inheritdoc
*/
public function get($path, Handler $handler = null)
{
$path = Util::normalizePath($path);
if ( ! $handler) {
$metadata = $this->getMetadata($path);
$handler = ($metadata && $metadata['type'] === 'file') ? new File($this, $path) : new Directory($this, $path);
}
$handler->setPath($path);
$handler->setFilesystem($this);
return $handler;
}
/**
* Assert a file is present.
*
* @param string $path path to file
*
* @throws FileNotFoundException
*
* @return void
*/
public function assertPresent($path)
{
if ($this->config->get('disable_asserts', false) === false && ! $this->has($path)) {
throw new FileNotFoundException($path);
}
}
/**
* Assert a file is absent.
*
* @param string $path path to file
*
* @throws FileExistsException
*
* @return void
*/
public function assertAbsent($path)
{
if ($this->config->get('disable_asserts', false) === false && $this->has($path)) {
throw new FileExistsException($path);
}
}
}

View File

@ -1,284 +0,0 @@
<?php
namespace League\Flysystem;
use InvalidArgumentException;
interface FilesystemInterface
{
/**
* Check whether a file exists.
*
* @param string $path
*
* @return bool
*/
public function has($path);
/**
* Read a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents or false on failure.
*/
public function read($path);
/**
* Retrieves a read-stream for a path.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return resource|false The path resource or false on failure.
*/
public function readStream($path);
/**
* List contents of a directory.
*
* @param string $directory The directory to list.
* @param bool $recursive Whether to list recursively.
*
* @return array A list of file metadata.
*/
public function listContents($directory = '', $recursive = false);
/**
* Get a file's metadata.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return array|false The file metadata or false on failure.
*/
public function getMetadata($path);
/**
* Get a file's size.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return int|false The file size or false on failure.
*/
public function getSize($path);
/**
* Get a file's mime-type.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file mime-type or false on failure.
*/
public function getMimetype($path);
/**
* Get a file's timestamp.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The timestamp or false on failure.
*/
public function getTimestamp($path);
/**
* Get a file's visibility.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The visibility (public|private) or false on failure.
*/
public function getVisibility($path);
/**
* Write a new file.
*
* @param string $path The path of the new file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function write($path, $contents, array $config = []);
/**
* Write a new file using a stream.
*
* @param string $path The path of the new file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException If $resource is not a file handle.
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function writeStream($path, $resource, array $config = []);
/**
* Update an existing file.
*
* @param string $path The path of the existing file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function update($path, $contents, array $config = []);
/**
* Update an existing file using a stream.
*
* @param string $path The path of the existing file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException If $resource is not a file handle.
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function updateStream($path, $resource, array $config = []);
/**
* Rename a file.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileExistsException Thrown if $newpath exists.
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function rename($path, $newpath);
/**
* Copy a file.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileExistsException Thrown if $newpath exists.
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function copy($path, $newpath);
/**
* Delete a file.
*
* @param string $path
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function delete($path);
/**
* Delete a directory.
*
* @param string $dirname
*
* @throws RootViolationException Thrown if $dirname is empty.
*
* @return bool True on success, false on failure.
*/
public function deleteDir($dirname);
/**
* Create a directory.
*
* @param string $dirname The name of the new directory.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function createDir($dirname, array $config = []);
/**
* Set the visibility for a file.
*
* @param string $path The path to the file.
* @param string $visibility One of 'public' or 'private'.
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function setVisibility($path, $visibility);
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function put($path, $contents, array $config = []);
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException Thrown if $resource is not a resource.
*
* @return bool True on success, false on failure.
*/
public function putStream($path, $resource, array $config = []);
/**
* Read and delete a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents, or false on failure.
*/
public function readAndDelete($path);
/**
* Get a file/directory handler.
*
* @deprecated
*
* @param string $path The path to the file.
* @param Handler $handler An optional existing handler to populate.
*
* @return Handler Either a file or directory handler.
*/
public function get($path, Handler $handler = null);
/**
* Register a plugin.
*
* @param PluginInterface $plugin The plugin to register.
*
* @return $this
*/
public function addPlugin(PluginInterface $plugin);
}

View File

@ -1,12 +0,0 @@
<?php
namespace League\Flysystem;
use LogicException;
/**
* Thrown when the MountManager cannot find a filesystem.
*/
class FilesystemNotFoundException extends LogicException
{
}

View File

@ -1,137 +0,0 @@
<?php
namespace League\Flysystem;
use BadMethodCallException;
/**
* @deprecated
*/
abstract class Handler
{
/**
* @var string
*/
protected $path;
/**
* @var FilesystemInterface
*/
protected $filesystem;
/**
* Constructor.
*
* @param FilesystemInterface $filesystem
* @param string $path
*/
public function __construct(FilesystemInterface $filesystem = null, $path = null)
{
$this->path = $path;
$this->filesystem = $filesystem;
}
/**
* Check whether the entree is a directory.
*
* @return bool
*/
public function isDir()
{
return $this->getType() === 'dir';
}
/**
* Check whether the entree is a file.
*
* @return bool
*/
public function isFile()
{
return $this->getType() === 'file';
}
/**
* Retrieve the entree type (file|dir).
*
* @return string file or dir
*/
public function getType()
{
$metadata = $this->filesystem->getMetadata($this->path);
return $metadata ? $metadata['type'] : 'dir';
}
/**
* Set the Filesystem object.
*
* @param FilesystemInterface $filesystem
*
* @return $this
*/
public function setFilesystem(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
return $this;
}
/**
* Retrieve the Filesystem object.
*
* @return FilesystemInterface
*/
public function getFilesystem()
{
return $this->filesystem;
}
/**
* Set the entree path.
*
* @param string $path
*
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Retrieve the entree path.
*
* @return string path
*/
public function getPath()
{
return $this->path;
}
/**
* Plugins pass-through.
*
* @param string $method
* @param array $arguments
*
* @return mixed
*/
public function __call($method, array $arguments)
{
array_unshift($arguments, $this->path);
$callback = [$this->filesystem, $method];
try {
return call_user_func_array($callback, $arguments);
} catch (BadMethodCallException $e) {
throw new BadMethodCallException(
'Call to undefined method '
. get_called_class()
. '::' . $method
);
}
}
}

View File

@ -1,648 +0,0 @@
<?php
namespace League\Flysystem;
use InvalidArgumentException;
use League\Flysystem\Plugin\PluggableTrait;
use League\Flysystem\Plugin\PluginNotFoundException;
/**
* Class MountManager.
*
* Proxies methods to Filesystem (@see __call):
*
* @method AdapterInterface getAdapter($prefix)
* @method Config getConfig($prefix)
* @method array listFiles($directory = '', $recursive = false)
* @method array listPaths($directory = '', $recursive = false)
* @method array getWithMetadata($path, array $metadata)
* @method Filesystem flushCache()
* @method void assertPresent($path)
* @method void assertAbsent($path)
* @method Filesystem addPlugin(PluginInterface $plugin)
*/
class MountManager implements FilesystemInterface
{
use PluggableTrait;
/**
* @var FilesystemInterface[]
*/
protected $filesystems = [];
/**
* Constructor.
*
* @param FilesystemInterface[] $filesystems [:prefix => Filesystem,]
*
* @throws InvalidArgumentException
*/
public function __construct(array $filesystems = [])
{
$this->mountFilesystems($filesystems);
}
/**
* Mount filesystems.
*
* @param FilesystemInterface[] $filesystems [:prefix => Filesystem,]
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function mountFilesystems(array $filesystems)
{
foreach ($filesystems as $prefix => $filesystem) {
$this->mountFilesystem($prefix, $filesystem);
}
return $this;
}
/**
* Mount filesystems.
*
* @param string $prefix
* @param FilesystemInterface $filesystem
*
* @throws InvalidArgumentException
*
* @return $this
*/
public function mountFilesystem($prefix, FilesystemInterface $filesystem)
{
if ( ! is_string($prefix)) {
throw new InvalidArgumentException(__METHOD__ . ' expects argument #1 to be a string.');
}
$this->filesystems[$prefix] = $filesystem;
return $this;
}
/**
* Get the filesystem with the corresponding prefix.
*
* @param string $prefix
*
* @throws FilesystemNotFoundException
*
* @return FilesystemInterface
*/
public function getFilesystem($prefix)
{
if ( ! isset($this->filesystems[$prefix])) {
throw new FilesystemNotFoundException('No filesystem mounted with prefix ' . $prefix);
}
return $this->filesystems[$prefix];
}
/**
* Retrieve the prefix from an arguments array.
*
* @param array $arguments
*
* @throws InvalidArgumentException
*
* @return array [:prefix, :arguments]
*/
public function filterPrefix(array $arguments)
{
if (empty($arguments)) {
throw new InvalidArgumentException('At least one argument needed');
}
$path = array_shift($arguments);
if ( ! is_string($path)) {
throw new InvalidArgumentException('First argument should be a string');
}
list($prefix, $path) = $this->getPrefixAndPath($path);
array_unshift($arguments, $path);
return [$prefix, $arguments];
}
/**
* @param string $directory
* @param bool $recursive
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return array
*/
public function listContents($directory = '', $recursive = false)
{
list($prefix, $directory) = $this->getPrefixAndPath($directory);
$filesystem = $this->getFilesystem($prefix);
$result = $filesystem->listContents($directory, $recursive);
foreach ($result as &$file) {
$file['filesystem'] = $prefix;
}
return $result;
}
/**
* Call forwarder.
*
* @param string $method
* @param array $arguments
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return mixed
*/
public function __call($method, $arguments)
{
list($prefix, $arguments) = $this->filterPrefix($arguments);
return $this->invokePluginOnFilesystem($method, $arguments, $prefix);
}
/**
* @param string $from
* @param string $to
* @param array $config
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
* @throws FileExistsException
*
* @return bool
*/
public function copy($from, $to, array $config = [])
{
list($prefixFrom, $from) = $this->getPrefixAndPath($from);
$buffer = $this->getFilesystem($prefixFrom)->readStream($from);
if ($buffer === false) {
return false;
}
list($prefixTo, $to) = $this->getPrefixAndPath($to);
$result = $this->getFilesystem($prefixTo)->writeStream($to, $buffer, $config);
if (is_resource($buffer)) {
fclose($buffer);
}
return $result;
}
/**
* List with plugin adapter.
*
* @param array $keys
* @param string $directory
* @param bool $recursive
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return array
*/
public function listWith(array $keys = [], $directory = '', $recursive = false)
{
list($prefix, $directory) = $this->getPrefixAndPath($directory);
$arguments = [$keys, $directory, $recursive];
return $this->invokePluginOnFilesystem('listWith', $arguments, $prefix);
}
/**
* Move a file.
*
* @param string $from
* @param string $to
* @param array $config
*
* @throws InvalidArgumentException
* @throws FilesystemNotFoundException
*
* @return bool
*/
public function move($from, $to, array $config = [])
{
list($prefixFrom, $pathFrom) = $this->getPrefixAndPath($from);
list($prefixTo, $pathTo) = $this->getPrefixAndPath($to);
if ($prefixFrom === $prefixTo) {
$filesystem = $this->getFilesystem($prefixFrom);
$renamed = $filesystem->rename($pathFrom, $pathTo);
if ($renamed && isset($config['visibility'])) {
return $filesystem->setVisibility($pathTo, $config['visibility']);
}
return $renamed;
}
$copied = $this->copy($from, $to, $config);
if ($copied) {
return $this->delete($from);
}
return false;
}
/**
* Invoke a plugin on a filesystem mounted on a given prefix.
*
* @param string $method
* @param array $arguments
* @param string $prefix
*
* @throws FilesystemNotFoundException
*
* @return mixed
*/
public function invokePluginOnFilesystem($method, $arguments, $prefix)
{
$filesystem = $this->getFilesystem($prefix);
try {
return $this->invokePlugin($method, $arguments, $filesystem);
} catch (PluginNotFoundException $e) {
// Let it pass, it's ok, don't panic.
}
$callback = [$filesystem, $method];
return call_user_func_array($callback, $arguments);
}
/**
* @param string $path
*
* @throws InvalidArgumentException
*
* @return string[] [:prefix, :path]
*/
protected function getPrefixAndPath($path)
{
if (strpos($path, '://') < 1) {
throw new InvalidArgumentException('No prefix detected in path: ' . $path);
}
return explode('://', $path, 2);
}
/**
* Check whether a file exists.
*
* @param string $path
*
* @return bool
*/
public function has($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->has($path);
}
/**
* Read a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents or false on failure.
*/
public function read($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->read($path);
}
/**
* Retrieves a read-stream for a path.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return resource|false The path resource or false on failure.
*/
public function readStream($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readStream($path);
}
/**
* Get a file's metadata.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return array|false The file metadata or false on failure.
*/
public function getMetadata($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getMetadata($path);
}
/**
* Get a file's size.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return int|false The file size or false on failure.
*/
public function getSize($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getSize($path);
}
/**
* Get a file's mime-type.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file mime-type or false on failure.
*/
public function getMimetype($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getMimetype($path);
}
/**
* Get a file's timestamp.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The timestamp or false on failure.
*/
public function getTimestamp($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getTimestamp($path);
}
/**
* Get a file's visibility.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The visibility (public|private) or false on failure.
*/
public function getVisibility($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->getVisibility($path);
}
/**
* Write a new file.
*
* @param string $path The path of the new file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function write($path, $contents, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->write($path, $contents, $config);
}
/**
* Write a new file using a stream.
*
* @param string $path The path of the new file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException If $resource is not a file handle.
* @throws FileExistsException
*
* @return bool True on success, false on failure.
*/
public function writeStream($path, $resource, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->writeStream($path, $resource, $config);
}
/**
* Update an existing file.
*
* @param string $path The path of the existing file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function update($path, $contents, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->update($path, $contents, $config);
}
/**
* Update an existing file using a stream.
*
* @param string $path The path of the existing file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException If $resource is not a file handle.
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function updateStream($path, $resource, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->updateStream($path, $resource, $config);
}
/**
* Rename a file.
*
* @param string $path Path to the existing file.
* @param string $newpath The new path of the file.
*
* @throws FileExistsException Thrown if $newpath exists.
* @throws FileNotFoundException Thrown if $path does not exist.
*
* @return bool True on success, false on failure.
*/
public function rename($path, $newpath)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->rename($path, $newpath);
}
/**
* Delete a file.
*
* @param string $path
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function delete($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->delete($path);
}
/**
* Delete a directory.
*
* @param string $dirname
*
* @throws RootViolationException Thrown if $dirname is empty.
*
* @return bool True on success, false on failure.
*/
public function deleteDir($dirname)
{
list($prefix, $dirname) = $this->getPrefixAndPath($dirname);
return $this->getFilesystem($prefix)->deleteDir($dirname);
}
/**
* Create a directory.
*
* @param string $dirname The name of the new directory.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function createDir($dirname, array $config = [])
{
list($prefix, $dirname) = $this->getPrefixAndPath($dirname);
return $this->getFilesystem($prefix)->createDir($dirname);
}
/**
* Set the visibility for a file.
*
* @param string $path The path to the file.
* @param string $visibility One of 'public' or 'private'.
*
* @throws FileNotFoundException
*
* @return bool True on success, false on failure.
*/
public function setVisibility($path, $visibility)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->setVisibility($path, $visibility);
}
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param string $contents The file contents.
* @param array $config An optional configuration array.
*
* @return bool True on success, false on failure.
*/
public function put($path, $contents, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->put($path, $contents, $config);
}
/**
* Create a file or update if exists.
*
* @param string $path The path to the file.
* @param resource $resource The file handle.
* @param array $config An optional configuration array.
*
* @throws InvalidArgumentException Thrown if $resource is not a resource.
*
* @return bool True on success, false on failure.
*/
public function putStream($path, $resource, array $config = [])
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->putStream($path, $resource, $config);
}
/**
* Read and delete a file.
*
* @param string $path The path to the file.
*
* @throws FileNotFoundException
*
* @return string|false The file contents, or false on failure.
*/
public function readAndDelete($path)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->readAndDelete($path);
}
/**
* Get a file/directory handler.
*
* @deprecated
*
* @param string $path The path to the file.
* @param Handler $handler An optional existing handler to populate.
*
* @return Handler Either a file or directory handler.
*/
public function get($path, Handler $handler = null)
{
list($prefix, $path) = $this->getPrefixAndPath($path);
return $this->getFilesystem($prefix)->get($path);
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace League\Flysystem;
use RuntimeException;
use SplFileInfo;
class NotSupportedException extends RuntimeException
{
/**
* Create a new exception for a link.
*
* @param SplFileInfo $file
*
* @return static
*/
public static function forLink(SplFileInfo $file)
{
$message = 'Links are not supported, encountered link at ';
return new static($message . $file->getPathname());
}
/**
* Create a new exception for a link.
*
* @param string $systemType
*
* @return static
*/
public static function forFtpSystemType($systemType)
{
$message = "The FTP system type '$systemType' is currently not supported.";
return new static($message);
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace League\Flysystem\Plugin;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;
abstract class AbstractPlugin implements PluginInterface
{
/**
* @var FilesystemInterface
*/
protected $filesystem;
/**
* Set the Filesystem object.
*
* @param FilesystemInterface $filesystem
*/
public function setFilesystem(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
}
}

Some files were not shown because too many files have changed in this diff Show More