Commit ff93fe2b by 杨树贤

Initial commit

parents
Showing with 3471 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=PRC
//系统编码,用于生成错误码
SYSTEM_CODE=04
//系统名称,用于告警识别
SYSTEM_NAME=商品信息处理服务(开发环境)
//laravels监听IP和端口
LARAVELS_LISTEN_IP=0.0.0.0
LARAVELS_LISTEN_PORT=60004
//基石自营商品主库
DB_Self_HOST=192.168.1.234
DB_Self_DATABASE=liexin_data
DB_Self_USERNAME=spu
DB_Self_PASSWORD=spu
DB_Self_PORT=3306
DB_Self_PREFIX=lie_
//采购系统数据库
DB_Pur_HOST=192.168.1.232
DB_Pur_DATABASE=liexin_wms
DB_Pur_USERNAME=root
DB_Pur_PASSWORD=123456
DB_Pur_PORT=3306
DB_Pur_PREFIX=lie_
//基石联营SPU数据库
DB_SPU_HOST=192.168.1.234
DB_SPU_DATABASE=liexin_spu
DB_SPU_USERNAME=spu
DB_SPU_PASSWORD=spu
DB_SPU_PORT=3306
DB_SPU_PREFIX=lie_
//基石数据库名字配置
SPU_DB_DATABASE=liexin_spu
SKU_0_DB_DATABASE=liexin_sku_0
SKU_1_DB_DATABASE=liexin_sku_1
SKU_2_DB_DATABASE=liexin_sku_2
SKU_3_DB_DATABASE=liexin_sku_3
SKU_4_DB_DATABASE=liexin_sku_4
SKU_5_DB_DATABASE=liexin_sku_5
SKU_6_DB_DATABASE=liexin_sku_6
SKU_7_DB_DATABASE=liexin_sku_7
SKU_8_DB_DATABASE=liexin_sku_8
SKU_9_DB_DATABASE=liexin_sku_9
DB_CONNECTION=mysql
DB_HOST=192.168.1.235
DB_USERNAME=icDb29mLy2s
DB_PASSWORD=icDb29mLy2s
DB_PORT=3306
DB_DATABASE=0
REDIS_HOST=192.168.1.235
REDIS_PASSWORD=icDb29mLy2s
REDIS_PORT=6379
REDIS_READ_HOST=192.168.1.237
REDIS_READ_PASSWORD=icDb29mLy2s
REDIS_READ_PORT=6379
MONG_DB_SPU_ATTRS_HOST=192.168.1.237
MONG_DB_SPU_ATTRS_USERNAME=ichunt
MONG_DB_SPU_ATTRS_PASSWORD=huntmon6699
MONG_DB_SPU_ATTRS_DATABASE=ichunt
CACHE_DRIVER=file
QUEUE_DRIVER=sync
APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
QUEUE_DRIVER=sync
/.idea
Homestead.json
Homestead.yaml
[submodule "common"]
path = common
url = ssh://git@119.23.72.7:22611/yyc/Common.git
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
abstract class Event
{
use SerializesModels;
}
<?php
namespace App\Events;
class ExampleEvent extends Event
{
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
}
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use PDOException;
use Predis\Connection\ConnectionException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
$report = [
'code' => $this->getCode($e),
'message' => toUtf8($e->getMessage()),
'file' => $e->getFile(),
'line' => $e->getLine(),
'request' => json_encode(Request::input()),
];
\LogReport::write(\LogReport::anlyError($report));
if (!env('APP_DEBUG')) {
SendAlarm($e,true,config('website.SystemName'));
}
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
$code = $this->getCode($e);
$msg = '系统错误,请联系客服处理';
$data = '';
if (env('APP_DEBUG')) {
$log = [toUtf8($e->getMessage()), $e->getFile(), $e->getLine()];
$data = implode(" ", $log);
}
return Response()->json(['errcode' => $code, 'errmsg' => $msg.' #'.getUnique(true), 'data' => $data]);
// return parent::render($request, $e);
}
private function getCode($e)
{
$systemcode = config('website.SystemCode');
if ($e instanceof PDOException) {
$code = errCode(001, 9, $systemcode);
} elseif ($e instanceof ConnectionException) {
$code = errCode(002, 9, $systemcode);
} elseif ($e instanceof FatalThrowableError) {
$code = errCode(003, 9, $systemcode);
} elseif (strpos($e->getFile(), 'RoutesRequests') !== false) {
$code = 404;
} else {
$code = $e->getCode() ? $e->getCode() : '';
}
return $code;
}
}
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
public function Export( $Errcode=0, $ErrMsg='', $dataArr=[]) {
if(!empty($dataArr) && !is_array($dataArr)) return json_encode(['errcode'=>-1,'errmsg'=>'系统错误']);
$data=['errcode'=>$Errcode, 'errmsg'=>$ErrMsg];
if(!empty($dataArr)) foreach ($dataArr as $k=>$v) $data[$k]=$v;
return json_encode($data);
}
/**
* @param int $code 错误码
* @param int $level 错误级别 1普通错误 5需关注错误 9致命错误,急需解决
* @return int
*/
protected function ProduceErrcode( $code='0',$level=1){
if($code=='0') return 0;
$SystemCode=config('website.SystemCode');
return errCode($code,$level,$SystemCode);
}
}
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
//
}
<?php
namespace App\Http\Controllers;
use App\Model\SelfSampleClassModel;
use App\Model\SelfSampleModel;
use Common\Model\RedisModel;
use App\Model\SelfGoodsModel;
use App\Model\SkuModel;
use App\Model\SpuModel;
use Illuminate\Http\Request;
class ServicesController extends Controller
{
public function synchronization(){
$collert=TrimX(['goods_id','power'], false);
if(empty($collert['goods_id'])) return $this->Export($this->ProduceErrcode(001,1),'没有SKUID');
if(empty($collert['power']))
$collert['power'] = false;
$SkuId=$collert['goods_id'];
$Redis=new RedisModel();
$GoodsModel=new SelfGoodsModel();
$SkuModel=new SkuModel();
$SpuModel=new SpuModel();
if(is_string($SkuId) && stripos($SkuId,',')!==false) $SkuId=explode(',',$SkuId);//兼容逗号方式
$data=[];
if(is_array($SkuId)){
foreach ($SkuId as $k=>$v){
$data[$v]=false;
if(strlen($v)==19) {//联营或者专卖
$data[$v] = $SkuModel->combination($v,$collert['power'], $Redis,$SpuModel);
}else $data[$v]=$GoodsModel->WebSelfGoodsDetail($v, $collert['power'], $Redis);
}
}else{
$data[$SkuId]=false;
if(strlen($SkuId)==19) {//联营或者专卖
$data[$SkuId] = $SkuModel->combination($SkuId,$collert['power'], $Redis,$SpuModel);
}else $data[$SkuId]=$GoodsModel->WebSelfGoodsDetail($SkuId, $collert['power'], $Redis);
}
return $this->Export(0,'success',['data'=>$data]);
}
/**
* 指定数量从阶梯中选择价格
* @param [type] $ladder 价格阶梯
* @param [type] $num 购买数量
* @param integer $currency 币种 1人民币 2美元
* @return [type]
*/
public function ladderprice(){//获取对应阶梯价
$collert=TrimX(['goods_id','num','currency','costly']);
if(empty($collert['goods_id'])) return $this->Export($this->ProduceErrcode(004,1),'缺少参数goods_id');
if(empty($collert['num'])) return $this->Export($this->ProduceErrcode(005,1),'缺少参数num');
if(empty($collert['currency'])) return $this->Export($this->ProduceErrcode(006,1),'缺少参数currency');
$GoodsInfo=json_decode($this->synchronization(),true);
if(!isset($GoodsInfo['errcode']) || $GoodsInfo['errcode']!==0 || empty($GoodsInfo['data'][$collert['goods_id']])) return $this->Export(20001,'未找到对应SKU');
$GoodsInfo=$GoodsInfo['data'][$collert['goods_id']];
if(empty($GoodsInfo['ladder_price'])) return $this->Export($this->ProduceErrcode(002,1),'这个SKU没有阶梯价');
//提取出对应的阶梯
foreach ($GoodsInfo['ladder_price'] as $k=>$v){
if($k==0) $price=$v;
if(!empty($collert['costly']) && ($collert['costly'] ===true || $collert['costly'] ==='true' ||
$collert['costly'] ==='1'))
break;
if($v['purchases'] <= $collert['num']) $price=$v;
else break;
}
if(empty($price)) throw new \Exception('这个SKU没有阶梯价',$this->ProduceErrcode(003,5));
$num = $collert['num']<$price['purchases'] ? $price['purchases']:$collert['num'];
$num = (int)$num;
$price['price_cn'] = $price['price_cn'] ?? 0;
$data=[
'price_cn'=>$price['price_cn'],
'price_cn_total'=>round($price['price_cn']*$num,4),//人民币原价总价
'ladder_price'=>$GoodsInfo['ladder_price'],
'num'=>$num
];
if(!empty($price['price_ac'])){
$data['price_ac'] = $price['price_ac'];
$data['price_ac_total'] = round($price['price_ac']*$num,4);//人民币活动总价
}
if(($GoodsInfo['goods_type'] == 1 || $GoodsInfo['goods_type'] == 2) && $GoodsInfo['ac_type'] != 1 && $collert['currency'] !=1 ){//获取美金
$price['price_us'] = $price['price_us'] ?? 0;
$data=[
'price_us'=>$price['price_us'],
'price_us_total'=>round($price['price_us']*$num,4),
'ladder_price'=>$GoodsInfo['ladder_price'],
'num'=>$num
];
$GoodsInfo['ac_type'] = 0;
}
$data['goods_info']=$GoodsInfo;
return $this->Export(0,'success',['data'=>$data]);
}
//自营样片分类列表
public function SelfSampleClassList(){
$sampleClassModel = new SelfSampleClassModel();
$list = $sampleClassModel->getSampleClassList();
return $this->Export(0,'ok', ['data'=>$list]);
}
//自营样片
public function SelfSampleList(Request $request)
{
$sampleModel = new SelfSampleModel();
$list = $sampleModel->getSampleList($request->all(), $request->input('limit', 10));
$GoodsModel = new SelfGoodsModel();
$Redis = new RedisModel(false);
$SampleClassModel = new SelfSampleClassModel();
if (!empty($list['data'])) {
foreach ($list['data'] as $k => &$v) {
$v['goods_info'] = $GoodsModel->WebSelfGoodsDetail($v['goods_id'], false, $Redis);
$sampleClaasInfo = $SampleClassModel->getSampleClass($v['class_id']);
$v['class_name'] = empty($sampleClaasInfo['class_name']) ? '' : $sampleClaasInfo['class_name'];
}
}
return $this->Export(0, 'ok', ['data' => $list]);
}
public function getnewCustomerLimit(Request $request){
$Redis = new RedisModel();
$info = $Redis->get('cube_newCustomerLimit');
if(!$info)
$info = 0;
return $this->Export(0, 'ok', ['data'=>$info]);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use App\Model\TokenModel;
class UniqueMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//设置唯一追踪值
$request->offsetSet('unique', getUnique(true));
return $next($request);
}
}
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-03-28
* Time: 18:51
*/
//解析SPU和SKU的ID
function resolve($id){
$data['db']=false;
$data['table']=false;
$type=substr($id,0,1);
$dbcode=substr($id,-2,1);
$tablecode=substr($id,-1);
if($type==1){
$data['db']='sku_'.$dbcode;
$data['table']='sku_'.$tablecode;
}
if($type==2){
$data['db']='spu';
$data['table']='spu_'.$tablecode;
}
return $data;
}
/**
* 获取税务信息,对接税务系统
* @return string
*/
function HDErpTax($GoodsName,$BrandName,$Redis=''){
if(empty($Redis)) $Redis=new \App\Model\RedisModel();
$info=$Redis->hget('tax_customs_info',md5(strtoupper($GoodsName.$BrandName)));
if(!$info) return false;
$info=json_decode($info,true);
$data['tariffRate']=!empty($info['tax_rate_low'])?$info['tax_rate_low']:'';
$data['types']=!empty($info['supervision_con'])?$info['supervision_con']:0;
return $data;
}
//获取联营供应商的名字
function HdCachePoolSupplier($SupplierID,$Redis=''){
if(empty($Redis)) $Redis=new \App\Model\RedisModel();
$Find=$Redis->hget('supplier',$SupplierID);
if($Find) return $Find;
$Find=DB::connection('spu')->table('supplier')->where('supplier_id','=',$SupplierID)->select('supplier_name')->first();
if(!$Find) return false;
$Find = (array)$Find;
$Redis->hset('supplier',$SupplierID,$Find['supplier_name']);
ErrorLog(0000,'SKU供应商缓存丢失,SupplierID:'.$SupplierID);
return $Find['supplier_name'];
}
//获取附加费
function HdExtendFee($supplierID,$canal='',$Redis=''){
if(empty($Redis)) $Redis=new \Common\Model\RedisModel();
if($supplierID!=17) $supp_extend_fee=json_decode($Redis->hget('supp_extend_fee',$supplierID),true);
else $supp_extend_fee=json_decode($Redis->hget('supp_extend_fee','17.'.$canal),true);
if(empty($supp_extend_fee)) return false;
return reset($supp_extend_fee);
}
/**
* 获取联营活动价
*/
function HDActivityPrice($info,$suffix,$Redis){
if(empty($info['ladder_price'])) return false;
if(empty($suffix) && $info['supplier_id']==14){//判断活动价
if(!empty($info['cp_time']) && ($info['cp_time']+60*60*48)>time()){
foreach ($info['ladder_price'] as $k=>$v){
if(!empty($v['cost_price'])){
$data['ac_type']=2;
return $data;
}
}
}
return false;
}
$GoodsActivityPrice=$Redis->get('Self_ActivityPrice_'.$info['supplier_id'].$suffix);
if(!empty($GoodsActivityPrice)){
$GoodsActivityPrice=json_decode($GoodsActivityPrice,true);
//在活动范围内
if(!empty($GoodsActivityPrice['start_time']) && $GoodsActivityPrice['start_time']<time() && !empty($GoodsActivityPrice['end_time']) && $GoodsActivityPrice['end_time']>time()){
$Ratio=true;
if($suffix=='_Discount'){//折扣价
if(!empty($GoodsActivityPrice['brand_id'])){
if(in_array($info['brand_name'],$GoodsActivityPrice['brand_id'])) $Ratio=false;//如果是不参与折扣的品牌
}
if(!empty($GoodsActivityPrice['goods_name'])){
if(in_array($info['goods_name'],$GoodsActivityPrice['goods_name'])) $Ratio=false;//如果是不参与折扣的型号
}
}elseif ($suffix=='_NewCustomer'){//新客价
//判断是否符合条件
if(!empty($GoodsActivityPrice['goods_id'])){
$GoodsActivityPrice['goods_id'] = $GoodsActivityPrice['goods_id'].',';//为了用字符串匹配
if(false === stripos($GoodsActivityPrice['goods_id'],$info['goods_id'].','))
$Ratio = false;
}else{
if (!empty($GoodsActivityPrice['brand_id'])) {
$GoodsActivityPrice['brand_id'] = $GoodsActivityPrice['brand_id'].',';
if(false === stripos($GoodsActivityPrice['brand_id'],$info['brand_id'].','))
$Ratio = false;
}
if (!empty($GoodsActivityPrice['canal']) && $info['goods_type'] == 2) {//专卖
$GoodsActivityPrice['canal'] = $GoodsActivityPrice['canal'].',';
if(false === stripos($GoodsActivityPrice['canal'],$info['canal'].','))
$Ratio = false;
}
if (!empty($GoodsActivityPrice['class_id']) && ($info['goods_type'] == 0 || $info['goods_type'] ==3
|| $info['goods_type'] ==4)) {
$GoodsActivityPrice['class_id'] = $GoodsActivityPrice['class_id'].',';
if(false === stripos($GoodsActivityPrice['class_id'],$info['class_id2'].','))
$Ratio = false;
}
}
}else {
if (!empty($GoodsActivityPrice['brand_id'])) {
if (!in_array($info['brand_id'], $GoodsActivityPrice['brand_id'])) $Ratio = false;
}
if (!empty($GoodsActivityPrice['canal']) && $info['goods_type'] == 2) {
if (!in_array($info['canal'], $GoodsActivityPrice['canal'])) $Ratio = false;
}
}
if($Ratio===true && !empty($info['ladder_price'])){
$data['ratio']=(float)$GoodsActivityPrice['ratio'];
switch ($suffix){
case '_Member'://会员价
$data['ac_type']=3;
break;
case '_NewCustomer'://新客价
$data['ac_type']=5;
break;
case '_Discount'://折扣价
$data['ac_type']=4;
break;
default ://活动价
$data['ac_type']=2;
break;
}
$data['allow_coupon']=empty($GoodsActivityPrice['allow_coupon'])?1:$GoodsActivityPrice['allow_coupon'];
$data['activity_end_time'] = $GoodsActivityPrice['end_time'];
return $data;
}
}
}
return false;
}
//获取供应商货期
function HdDelivery($SupplierID,$canal='',$Redis=''){
if(empty($SupplierID)) return false;
if(empty($Redis)) $Redis=new \App\Model\RedisModel();
if(!empty($canal)){
$supp_ratio=json_decode($Redis->hget('supp_ratio',$canal),true);
$info=[];
if(!empty($supp_ratio)) $info['cn_delivery']=$supp_ratio['cn_delivery_time'];
if(!empty($supp_ratio)) $info['hk_delivery']=$supp_ratio['us_delivery_time'];
return $info;
}
$Find=json_decode($Redis->hget('SUPPLIER_REDIS_INFO_',$SupplierID),true);
if(empty($Find['cn_delivery']) && empty($Find['hk_delivery'])) return false;
return ['cn_delivery'=>$Find['cn_delivery'],'hk_delivery'=>$Find['hk_delivery']];
}
function SendDingTalk($message){
return SendRobot(config('website.RobotUrl'),$message,[config('website.at')],config('website.SystemName'));
}
\ No newline at end of file
<?php
namespace App\Jobs;
class ExampleJob extends Job
{
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
abstract class Job implements ShouldQueue
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "queueOn" and "delay" queue helper methods.
|
*/
use InteractsWithQueue, Queueable, SerializesModels;
}
<?php
namespace App\Listeners;
use App\Events\ExampleEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ExampleListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ExampleEvent $event
* @return void
*/
public function handle(ExampleEvent $event)
{
//
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class PoolBrandModel extends Model
{
protected $connection = 'spu';
protected $table = 'brand';
public $timestamps = false;
//从redis获取分类数据
public function HdCacheBrand($BrandID,$Redis=''){
if(empty($BrandID)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$Find=$Redis->hget('brand',$BrandID);
if($Find) return $Find;
$Find=$this->where('brand_id','=',$BrandID)->select('brand_name')->first();
if(!$Find) return false;
$Find=$Find->toArray();
$Redis->hset('brand',$BrandID,$Find['brand_name']);
$Redis->hset('brand_name_all',md5(strtolower($Find['brand_name'])),$BrandID);
ErrorLog('',0000,'SPU品牌缓存丢失,BrandID:'.$BrandID);
return $Find['brand_name'];
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class PoolClassModel extends Model
{
protected $connection = 'spu';
protected $table = 'classify';
public $timestamps = false;
//从redis获取分类数据
public function HdCacheClass($ClassID,$Redis=''){
if(empty($ClassID)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$Find=$Redis->hget('class',$ClassID);
if($Find) return $Find;
$Find=$this->where('class_id','=',$ClassID)->select('class_name')->first();
if(!$Find) return false;
$Find=$Find->toArray();
$Redis->hset('class',$ClassID,$Find['class_name']);
//需要记录一下日志
ErrorLog('',0000,'SPU分类缓存丢失,CLASSID:'.$ClassID);
return $Find['class_name'];
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class RedisModel extends Model
{
const WRITE_CONNECT_METHOD = ['set', 'del', 'rpush','lpush', 'expire', 'hset', 'hmset', 'hdel','hsetnx'];
private $read = [];
private $write = [];
public function __construct($ConnectWrite = 'default', $ConnectRead = 'read')
{
parent::__construct();
$this->read = Redis::connection($ConnectRead);
$this->write = Redis::connection($ConnectWrite);
}
public function __call($method, $args)
{
if (in_array($method, self::WRITE_CONNECT_METHOD)) {
return $this->write->$method(...$args);
} else {
try {
return $this->read->$method(...$args);
} catch (ConnectionException $e) {
return $this->write->$method(...$args);
}
}
}
//管道
public function pipeline_to_hset($data){
return $this->write->pipeline(function ($pipe) use ($data) {
foreach ($data['data'] as $k => $v) {
$pipe->hset($data['key'],$k,$v);
}
});
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class ResourceModel extends Model
{
protected $connection=false;
protected $table='resource';
public $timestamps = false;
public function GetResourceInfoById($resourceId, $Redis=''){
if(empty($resourceId)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$data=json_decode($Redis->hget('Self_SelfGoodsSource',$resourceId),true);
if(!empty($data['url'])) return $data['url'];
//需要更新redis
if(empty($this->connection)) $this->connection='self';
$data = $this->where('id', '=', $resourceId)->select('url')->first();
if(!$data) return false;
$data=$data->toArray();
$Redis->hset('Self_SelfGoodsSource',$resourceId,json_encode($data));
return $data['url'];
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class SelfBrandModel extends Model
{
protected $connection=false;
protected $table='brand';
public $timestamps = false;
public function HDBrandName($BrandID='',$Redis=''){
if(empty($BrandID)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$BrandName=$Redis->hget('Self_Brand',$BrandID);
if(!$BrandName){
$result=$this->ToRedis($BrandID,$Redis);
if(!$result) return false;
return $result['brand_name'];
}else{
$BrandName=json_decode($BrandName,true);
return $BrandName['brand_name'];
}
}
public function ToRedis($BrandID,$Redis=''){
if(empty($BrandID)) return false;
if(empty($Redis)) $Redis=new RedisModel;
if(empty($this->connection)) $this->connection='self';
$Find=$this->where('brand_id','=',$BrandID)->select('brand_logo','brand_id','brand_name','brand_area','status')->first();
if(!$Find) return false;
$Find=$Find->toArray();
$Redis->hset('Self_Brand',$BrandID,json_encode($Find));
return $Find;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class SelfClassifyModel extends Model
{
protected $connection=false;
protected $table='self_classify';
public $timestamps = false;
//生成自营分类redis
public function ProduceClassRedis($class_id='',$Redis=''){
if(empty($class_id)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$info=json_decode($Redis->hget('Self_SelfClassInfo',$class_id),true);
if(!$info){
if(empty($this->connection)) $this->connection='self';
$info=$this->where('class_id','=',$class_id)->select('class_id','class_name','parent_id','sort','status','class_icon','ladder', 'is_dc')->first();
if($info){
$info=$info->toArray();
if(!empty($info['ladder'])) $info['ladder']=json_decode($info['ladder'],true);
$Redis->hset('Self_SelfClassInfo',$class_id,json_encode($info));
}else return false;
}
return $info;
}
}
<?php
namespace App\Model;
use Common\Model\RedisModel;
use Illuminate\Database\Eloquent\Model;
class SelfSampleClassModel extends Model
{
protected $connection='self';
protected $table='sample_class';
public $timestamps = false;
//获取分类列表,给前端用
public function getSampleClassList(){
$Redis = new RedisModel();
$pre = 'Self_sample_class_list_web';
$Cache = json_decode($Redis->get($pre),true);
if(!$Cache){//重新生成缓存
$Cache = $this->where('status', '=', 1)->orderBy('sort', 'desc')->select('id','class_name','class_icon','parent_id')
->limit(100)->get();
if(!$Cache)
return false;
$Cache = $Cache->toArray();
$Redis->set($pre, json_encode($Cache));
$Redis->expire($pre, 60);
}
return $Cache;
}
//获取分类信息
public function getSampleClass($class_id){
$Redis = new RedisModel();
$findCache = json_decode($Redis->hget('Self_sample_class_list', $class_id),true);
if(!$findCache){
$find = $this->where('id', '=', $class_id)->select('id','class_name','parent_id','sort','class_icon','status')->first();
if(!$find)
return false;
$find = $find->toArray();
$findCache = $this->setSampleClassToCache($class_id, $find);
}
return $findCache;
}
//将分类信息写进redis
public function setSampleClassToCache($id, $data){
$field = ['id','class_name','parent_id','sort','class_icon','status'];
$data = array_only($data, $field);
$Redis = new RedisModel();
$findCache = json_decode($Redis->hget('Self_sample_class_list', $id),true);
if(!empty($findCache))
$data = array_merge($findCache, $data);
$Redis->hset('Self_sample_class_list', $id, json_encode($data));
return $data;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class SelfSampleModel extends Model
{
protected $connection='self';
protected $table='sample';
public $timestamps = false;
public function getSampleList($map, $limit = 10){
$mapArr = [];
if(!empty($map['goods_id'])){
$mapArr[] = ['sample.goods_id', '=', $map['goods_id']];
}
if(!empty($map['class_id'])){
$mapArr[] = ['class_id', '=', $map['class_id']];
}
if(!empty($map['id'])){
$mapArr[] = ['id', '=', $map['id']];
}
$list = $this->where($mapArr)->where('sample.status', '=', 1)->select('sample.goods_id','id','class_id','max_number')
->orderBy('sample.update_time', 'desc')->paginate($limit)->toArray();
$field = ['data','total'];
$list = array_only($list, $field);
$list['data'] = array_column($list['data'],null, 'goods_id');
$sampleClassModel = new SelfSampleClassModel();
foreach ($list['data'] as $k=>&$v){
//获取商品信息
if(!empty($result['data'][$k])){
$v = array_merge($v, $result['data'][$k]);
}
//获取分类信息
$sampleClassInfo = $sampleClassModel->getSampleClass($v['class_id']);
if(!empty($sampleClassInfo['class_name'])){
$v['class_name'] = $sampleClassInfo['class_name'];
}
}
return $list;
}
//新增样片
public function addSample($data){
//去除不新增的字段
$field = ['goods_id','class_id','max_number'];
$data = array_only($data, $field);
$data['add_time'] = time();
$data['update_time'] = $data['add_time'];
$result = $this->insertGetId($data);
if(!$result)
return false;
$data['id'] = $result;
$this->addSampleToCache($result, $data);
return true;
}
//更新样片
public function saveSample($data){
$id = $data['id'];
$field = ['class_id','max_number'];
$data = array_only($data, $field);
$data['update_time'] = time();
$result = $this->where('id', '=', $id)->update($data);
if(!$result)
return false;
$this->addSampleToCache($id, $data);
return true;
}
//新增样片到Redis
public function addSampleToCache($id, $data){
$field = ['id','goods_id','class_id','max_number','status'];
$data = array_only($data, $field);
$Redis = new RedisModel();
$findCache = json_decode($Redis->hget('Self_sample_list', $id), true);
if(!empty($findCache))
$data = array_merge($findCache, $data);
$Redis->hset('Self_sample_list', $id, json_encode($data));
return $data;
}
//删除样片
public function deleteSample($id){
$result = $this->where('id', '=', $id)->update(['status'=>3,'update_time'=>time()]);
if(!$result)
return false;
$Redis = new RedisModel();
$Redis->hdel('Self_sample_list', $id);
return true;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
class SpuAttrsModel extends Model
{
protected $connection = 'mongodb';
protected $table = 'spu_attrs';
public $timestamps = false;
public function HdCacheAttrs($SpuID){
$Find=DB::connection('mongodb')->table('spu_attrs')->where('spu_id','=',(int)$SpuID)->select('attrs')->first();
if(!$Find) return false;
$info=json_decode($Find['attrs'],true);
if(!$info) return false;
$Attrs=false;
foreach ($info as $k=>$v){
$Attrs[]=[
'attr_name'=>$k,
'attr_value'=>$v
];
}
return $Attrs;
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class SpuModel extends Model
{
protected $connection = false;
protected $table = false;
public $timestamps = false;
//生成数据库连接
public function ConnectDB($SpuId)
{
if (strlen($SpuId) !== 19) return false;
$dt = resolve($SpuId);
$this->connection = $dt['db'];
$this->table = $dt['table'];
return true;
}
//从redis获取spu数据
public function HdCacheSpu($SpuID,$Redis=''){
if(empty($SpuID)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$Find=json_decode($Redis->hget('spu',$SpuID),true);
if($Find) return $Find;
$this->ConnectDB($SpuID);
$Find=$this->where('spu_id',$SpuID)
->select('spu_id','class_id1','class_id2','class_id3','spu_name','brand_id','status','update_time','images_l','encap','pdf','spu_brief','attrs','spu_detail')
->first();
if(!$Find) return false;
$Find=$Find->toArray();
$Find['attrs']=json_decode($Find['attrs'],true);
//更新redis
$Redis->hset('spu',$SpuID,json_encode($Find));
//需要记录一下日志
ErrorLog('',0000,'SPU缓存丢失,SPUID:'.$SpuID);
return $Find;
}
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class SupplierChannelModel extends Model
{
protected $connection=false;
protected $table='supplier_channel';
public function ObSupplierName($SupplierID='',$Redis=''){
if(empty($SupplierID)) return false;
if(empty($Redis)) $Redis=new RedisModel();
$FindCache=json_decode($Redis->hget('Self_SelfSupplierInfo',$SupplierID),true);
if(!empty($FindCache['supplier_name'])) return $FindCache['supplier_name'];
if(empty($this->connection)) $this->connection='Pur';
$info=$this->where('supplier_id','=',$SupplierID)->select('supplier_name')->first();
if(!$info) return false;
$info=$info->toArray();
//更新一份缓存
$Redis->hset('Self_SelfSupplierInfo',$SupplierID,json_encode(
[
'supplier_name'=>$info['supplier_name']
],JSON_UNESCAPED_UNICODE)); //设置值
return $info['supplier_name'];
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class UUIDModel extends Model
{
const EPOCH = 1479533469598;
const max12bit = 4095;
const max41bit = 1099511627775;
static $machineId = null;
protected $connection=false;
protected $table=false;
public $timestamps = false;
/*
* $type str ic_goods=商品 ic_offer=报价 ic_inquiry=询价
*/
public function generateParticle($type='ic_goods')
{
/*
* Time - 42 bits
*/
$time = floor(microtime(true) * 1000);
/*
* Substract custom epoch from current time
*/
$time -= self::EPOCH;
/*
* Create a base and add time to it
*/
$base = decbin(self::max41bit + $time);
/*
* Configured machine id - 10 bits - up to 1024 machines
*/
if(!self::$machineId) {
$machineid = self::$machineId;
} else {
$machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
}
/*
* sequence number - 12 bits - up to 4096 random numbers per machine
*/
$random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);
/*
* Pack
*/
$base = $base.$machineid.$random;
/*
* Return unique time id no
*/
$UUID=(string)bindec($base);
return $this->Occupy($type,$UUID);
}
private function Occupy($type,$UUID)
{
$Redis = new RedisModel();
if($Redis->hsetnx($type,$UUID,1))
return $UUID;
return false;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class UnitModel extends Model
{
protected $connection=false;
protected $table='unit';
public $timestamps = false;
public function OBUnitInfo($UnitID='',$Redis=''){
if(empty($UnitID)) return false;
empty($Redis) && $Redis=new RedisModel();
$Find=$Redis->hget('Self_Unit',$UnitID);
if(!$Find){
if(empty($this->connection)) $this->connection='self';
$list=$this->lists('unit_name','unit_id')->toArray();
$Redis->hmset('Self_Unit',$list);
return empty($list[$UnitID])? '':$list[$UnitID];
}else{
return $Find;
}
}
public function OBUnitInfoAlias($UnitID='',$Redis=''){
if(empty($UnitID)) return false;
empty($Redis) && $Redis=new RedisModel;
$Find=$Redis->hget('Self_UnitAlias',$UnitID);
if(!$Find){
if(empty($this->connection)) $this->connection='self';
$list=$this->lists('unit_name_alias','unit_id')->toArray();
$Redis->hmset('Self_UnitAlias',$list);
return empty($list[$UnitID])? '':$list[$UnitID];
}else{
return $Find;
}
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
<?php
namespace App\Providers;
use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}
#!/usr/bin/env php
<?php
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| First we need to get an application instance. This creates an instance
| of the application / container and bootstraps the application so it
| is ready to receive HTTP / Console requests from the environment.
|
*/
$app = require __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(
'Illuminate\Contracts\Console\Kernel'
);
exit($kernel->handle(new ArgvInput, new ConsoleOutput));
#!/usr/bin/env bash
WORK_DIR=$1
if [ ! -n "${WORK_DIR}" ] ;then
WORK_DIR="."
fi
echo "Restarting LaravelS..."
./bin/laravels restart -d -i
echo "Starting fswatch..."
LOCKING=0
fswatch -e ".*" -i "\\.php$" -m poll_monitor -r ${WORK_DIR} | while read file
do
if [[ ! ${file} =~ .php$ ]] ;then
continue
fi
if [ ${LOCKING} -eq 1 ] ;then
echo "Reloading, skipped."
continue
fi
echo "File ${file} has been modified."
LOCKING=1
./bin/laravels reload
LOCKING=0
done
exit 0
\ No newline at end of file
#!/usr/bin/env php
<?php
$basePath = realpath(__DIR__ . '/../');
include $basePath . '/vendor/autoload.php';
$command = new Hhxsv5\LaravelS\Console\Portal($basePath);
$input = new Symfony\Component\Console\Input\ArgvInput();
$output = new Symfony\Component\Console\Output\ConsoleOutput();
$code = $command->run($input, $output);
exit($code);
\ No newline at end of file
<?php
use Common\Exceptions\Handler;
require_once __DIR__.'/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->withFacades();
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
// App\Exceptions\Handler::class
Common\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
$app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
App\Http\Middleware\UniqueMiddleware::class,
]);
// $app->routeMiddleware([
// 'auth' => App\Http\Middleware\Authenticate::class,
// ]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
$app->register(Illuminate\Redis\RedisServiceProvider::class);
$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->register(Hhxsv5\LaravelS\Illuminate\LaravelSServiceProvider::class);
$app->withEloquent();
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->configure('website');
$app->configure('database');
LogReport::$suffix = '_'.env('LARAVELS_LISTEN_PORT', '');
LogReport::$app_name = env('ELK_NAME','');
LogReport::$log_path = realpath(__DIR__ . '/../').'/storage/logs/LogReport/';
require_once __DIR__.'/../app/Http/function.php';
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.6.4",
"laravel/lumen-framework": "5.5.*",
"vlucas/phpdotenv": "~2.2",
"hprose/hprose": ">=2.0.0",
"predis/predis": "^1.1",
"illuminate/redis": "^5.5",
"jenssegers/mongodb": "3.3",
"hhxsv5/laravel-s": "~3.4.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~6.0",
"mockery/mockery": "~0.9"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Common\\": "common/"
},
"files": [
"common/function.php",
"common/LogReport.php"
]
},
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"optimize-autoloader": true,
"repositories": {
"packagist": {
"type": "composer",
"url": "https://packagist.laravel-china.org"
}
}
}
This diff could not be displayed because it is too large.
<?php
/**
* @see https://github.com/hhxsv5/laravel-s/blob/master/Settings-CN.md Chinese
* @see https://github.com/hhxsv5/laravel-s/blob/master/Settings.md English
*/
return [
'listen_ip' => env('LARAVELS_LISTEN_IP', '0.0.0.0'),
'listen_port' => env('LARAVELS_LISTEN_PORT', 60001),
'socket_type' => defined('SWOOLE_SOCK_TCP') ? SWOOLE_SOCK_TCP : 1,
'enable_coroutine_runtime' => false,
'server' => env('LARAVELS_SERVER', 'LaravelS'),
'handle_static' => env('LARAVELS_HANDLE_STATIC', false),
'laravel_base_path' => env('LARAVEL_BASE_PATH', base_path()),
'inotify_reload' => [
'enable' => env('LARAVELS_INOTIFY_RELOAD', false),
'watch_path' => base_path(),
'file_types' => ['.php'],
'excluded_dirs' => [],
'log' => true,
],
'event_handlers' => [],
'websocket' => [
'enable' => false,
//'handler' => XxxWebSocketHandler::class,
],
'sockets' => [],
'processes' => [],
'timer' => [
'enable' => false,
'jobs' => [
// Enable LaravelScheduleJob to run `php artisan schedule:run` every 1 minute, replace Linux Crontab
//\Hhxsv5\LaravelS\Illuminate\LaravelScheduleJob::class,
// Two ways to configure parameters:
// [\App\Jobs\XxxCronJob::class, [1000, true]], // Pass in parameters when registering
// \App\Jobs\XxxCronJob::class, // Override the corresponding method to return the configuration
],
'pid_file' => storage_path('laravels-timer.pid'),
'max_wait_time' => 5,
],
'events' => [],
'swoole_tables' => [],
'register_providers' => [],
'cleaners' => [
//Hhxsv5\LaravelS\Illuminate\Cleaners\SessionCleaner::class, // If you use the session/authentication in your project, please uncomment this line
//Hhxsv5\LaravelS\Illuminate\Cleaners\AuthCleaner::class, // If you use the authentication/passport in your project, please uncomment this line
//Hhxsv5\LaravelS\Illuminate\Cleaners\JWTCleaner::class, // If you use the package "tymon/jwt-auth" in your project, please uncomment this line
// ...
],
'swoole' => [
'daemonize' => env('LARAVELS_DAEMONIZE', false),
'dispatch_mode' => 2,
'reactor_num' => 4,
'worker_num' => 8,
//'task_worker_num' => function_exists('swoole_cpu_num') ? swoole_cpu_num() * 2 : 8,
'task_ipc_mode' => 1,
'task_max_request' => 8000,
'task_tmpdir' => @is_writable('/dev/shm/') ? '/dev/shm' : '/tmp',
'max_request' => 8000,
'open_tcp_nodelay' => true,
'pid_file' => storage_path('laravels.pid'),
'log_file' => storage_path(sprintf('logs/swoole-%s.log', date('Y-m'))),
'log_level' => 4,
'document_root' => base_path('public'),
'buffer_output_size' => 2 * 1024 * 1024,
'socket_buffer_size' => 128 * 1024 * 1024,
'package_max_length' => 4 * 1024 * 1024,
'reload_async' => true,
'max_wait_time' => 60,
'enable_reuse_port' => true,
'enable_coroutine' => false,
'http_compression' => false,
/**
* More settings of Swoole
* @see https://wiki.swoole.com/wiki/page/274.html Chinese
* @see https://www.swoole.co.uk/docs/modules/swoole-server/configuration English
*/
],
];
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-03-29
* Time: 10:58
*/
return [
'SecretKey'=>'fh6y5t4rr351d2c3bryi',//接口加密密钥,与oss相同
'UploadKey'=>'fh6y5t4rr351d2c3bryi',//api的秘钥
'SystemCode'=>env('SYSTEM_CODE','00'),//系统编码,需要在tapd维护,请勿占用已使用的编码
'SystemName'=>env('SYSTEM_NAME','这家伙没设置系统'),//系统名称
'path'=>realpath(__DIR__ . '/../').'/storage/logs/LogReport/',
'tax'=>1.13
];
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
];
});
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call('UsersTableSeeder');
}
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/app.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
</phpunit>
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| First we need to get an application instance. This creates an instance
| of the application / container and bootstraps the application so it
| is ready to receive HTTP / Console requests from the environment.
|
*/
$app = require __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$app->run();
# Lumen PHP Framework
[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework)
[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)
Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Lumen attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as routing, database abstraction, queueing, and caching.
## Official Documentation
Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs).
## Security Vulnerabilities
If you discover a security vulnerability within Lumen, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
## License
The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', function () use ($router) {
return swoole_get_local_ip();
return $router->app->version();
});
$router->post('/synchronization', 'ServicesController@synchronization');
$router->post('/ladderprice', 'ServicesController@ladderprice');
$router->post('/uuid', 'ServicesController@uuid');
$router->post('/self/sample/class/list', 'ServicesController@SelfSampleClassList');
$router->post('/self/sample/list', 'ServicesController@SelfSampleList');
$router->post('/get_new_customer_limit', 'ServicesController@getnewCustomerLimit');
{"server":{"listen_ip":"0.0.0.0","listen_port":"60004","socket_type":1,"enable_coroutine_runtime":false,"server":"LaravelS","handle_static":false,"laravel_base_path":"/root/www/GoodsMachining","inotify_reload":{"enable":false,"watch_path":"/root/www/GoodsMachining","file_types":[".php"],"excluded_dirs":[],"log":true},"event_handlers":[],"websocket":{"enable":false},"sockets":[],"processes":[],"timer":{"enable":false,"jobs":[],"pid_file":"/root/www/GoodsMachining/storage/laravels-timer.pid","max_wait_time":5},"events":[],"swoole_tables":[],"register_providers":[],"cleaners":[],"swoole":{"daemonize":false,"dispatch_mode":2,"reactor_num":4,"worker_num":8,"task_ipc_mode":1,"task_max_request":8000,"task_tmpdir":"/dev/shm","max_request":8000,"open_tcp_nodelay":true,"pid_file":"/root/www/GoodsMachining/storage/laravels.pid","log_file":"/root/www/GoodsMachining/storage/logs/swoole-2019-05.log","log_level":4,"document_root":"/root/www/GoodsMachining/public","buffer_output_size":2097152,"socket_buffer_size":134217728,"package_max_length":4194304,"reload_async":true,"max_wait_time":60,"enable_reuse_port":true,"enable_coroutine":false,"http_compression":false},"enable_gzip":false,"process_prefix":"/root/www/GoodsMachining","ignore_check_pid":true},"laravel":{"root_path":"/root/www/GoodsMachining","static_path":"/root/www/GoodsMachining/public","cleaners":[],"register_providers":[],"is_lumen":true,"_SERVER":{"XDG_SESSION_ID":"1","HOSTNAME":"localhost.localdomain","SELINUX_ROLE_REQUESTED":"","SHELL":"/bin/bash","TERM":"xterm","HISTSIZE":"1000","SSH_CLIENT":"192.168.117.1 50292 22","SELINUX_USE_CURRENT_RANGE":"","SSH_TTY":"/dev/pts/0","USER":"root","LS_COLORS":"rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:","MAIL":"/var/spool/mail/root","PATH":"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin","_":"/usr/bin/php","SUPERVISOR_GROUP_NAME":"goodsm","PWD":"/root","LANG":"en_US.UTF-8","SELINUX_LEVEL_REQUESTED":"","HISTCONTROL":"ignoredups","SUPERVISOR_ENABLED":"1","SHLVL":"2","HOME":"/root","LOGNAME":"root","SSH_CONNECTION":"192.168.117.1 50292 192.168.117.128 22","SUPERVISOR_SERVER_URL":"unix:///var/run/supervisor/supervisor.sock","SUPERVISOR_PROCESS_NAME":"goodsm","LESSOPEN":"||/usr/bin/lesspipe.sh %s","XDG_RUNTIME_DIR":"/run/user/0","PHP_SELF":"/root/www/GoodsMachining/artisan","SCRIPT_NAME":"/root/www/GoodsMachining/artisan","SCRIPT_FILENAME":"/root/www/GoodsMachining/artisan","PATH_TRANSLATED":"/root/www/GoodsMachining/artisan","DOCUMENT_ROOT":"","REQUEST_TIME_FLOAT":1557385187.647738,"REQUEST_TIME":1557385187,"argv":["/root/www/GoodsMachining/artisan","laravels","config","--ignore"],"argc":4,"APP_ENV":"local","APP_DEBUG":"true","APP_KEY":"","APP_TIMEZONE":"PRC","SYSTEM_CODE":"04","SYSTEM_NAME":"商品信息处理服务","LARAVELS_LISTEN_IP":"0.0.0.0","LARAVELS_LISTEN_PORT":"60004","DB_Self_HOST":"192.168.1.234","DB_Self_DATABASE":"liexin_data","DB_Self_USERNAME":"spu","DB_Self_PASSWORD":"spu","DB_Self_PORT":"3306","DB_Self_PREFIX":"lie_","DB_Pur_HOST":"192.168.1.232","DB_Pur_DATABASE":"liexin_wms","DB_Pur_USERNAME":"root","DB_Pur_PASSWORD":"123456","DB_Pur_PORT":"3306","DB_Pur_PREFIX":"lie_","DB_SPU_HOST":"192.168.1.234","DB_SPU_DATABASE":"liexin_spu","DB_SPU_USERNAME":"spu","DB_SPU_PASSWORD":"spu","DB_SPU_PORT":"3306","DB_SPU_PREFIX":"lie_","SPU_DB_DATABASE":"liexin_spu","SKU_0_DB_DATABASE":"liexin_sku_0","SKU_1_DB_DATABASE":"liexin_sku_1","SKU_2_DB_DATABASE":"liexin_sku_2","SKU_3_DB_DATABASE":"liexin_sku_3","SKU_4_DB_DATABASE":"liexin_sku_4","SKU_5_DB_DATABASE":"liexin_sku_5","SKU_6_DB_DATABASE":"liexin_sku_6","SKU_7_DB_DATABASE":"liexin_sku_7","SKU_8_DB_DATABASE":"liexin_sku_8","SKU_9_DB_DATABASE":"liexin_sku_9","DB_CONNECTION":"mysql","DB_HOST":"192.168.1.235","DB_USERNAME":"icDb29mLy2s","DB_PASSWORD":"icDb29mLy2s","DB_PORT":"3306","DB_DATABASE":"0","REDIS_HOST":"192.168.1.235","REDIS_PASSWORD":"icDb29mLy2s","REDIS_PORT":"6379","REDIS_READ_HOST":"192.168.1.237","REDIS_READ_PASSWORD":"icDb29mLy2s","REDIS_READ_PORT":"6379","MONG_DB_SPU_ATTRS_HOST":"192.168.1.237","MONG_DB_SPU_ATTRS_USERNAME":"","MONG_DB_SPU_ATTRS_PASSWORD":"","MONG_DB_SPU_ATTRS_DATABASE":"ichunt","CACHE_DRIVER":"file","QUEUE_DRIVER":"sync","SHELL_VERBOSITY":0},"_ENV":{"APP_ENV":"local","APP_DEBUG":"true","APP_KEY":"","APP_TIMEZONE":"PRC","SYSTEM_CODE":"04","SYSTEM_NAME":"商品信息处理服务","LARAVELS_LISTEN_IP":"0.0.0.0","LARAVELS_LISTEN_PORT":"60004","DB_Self_HOST":"192.168.1.234","DB_Self_DATABASE":"liexin_data","DB_Self_USERNAME":"spu","DB_Self_PASSWORD":"spu","DB_Self_PORT":"3306","DB_Self_PREFIX":"lie_","DB_Pur_HOST":"192.168.1.232","DB_Pur_DATABASE":"liexin_wms","DB_Pur_USERNAME":"root","DB_Pur_PASSWORD":"123456","DB_Pur_PORT":"3306","DB_Pur_PREFIX":"lie_","DB_SPU_HOST":"192.168.1.234","DB_SPU_DATABASE":"liexin_spu","DB_SPU_USERNAME":"spu","DB_SPU_PASSWORD":"spu","DB_SPU_PORT":"3306","DB_SPU_PREFIX":"lie_","SPU_DB_DATABASE":"liexin_spu","SKU_0_DB_DATABASE":"liexin_sku_0","SKU_1_DB_DATABASE":"liexin_sku_1","SKU_2_DB_DATABASE":"liexin_sku_2","SKU_3_DB_DATABASE":"liexin_sku_3","SKU_4_DB_DATABASE":"liexin_sku_4","SKU_5_DB_DATABASE":"liexin_sku_5","SKU_6_DB_DATABASE":"liexin_sku_6","SKU_7_DB_DATABASE":"liexin_sku_7","SKU_8_DB_DATABASE":"liexin_sku_8","SKU_9_DB_DATABASE":"liexin_sku_9","DB_CONNECTION":"mysql","DB_HOST":"192.168.1.235","DB_USERNAME":"icDb29mLy2s","DB_PASSWORD":"icDb29mLy2s","DB_PORT":"3306","DB_DATABASE":"0","REDIS_HOST":"192.168.1.235","REDIS_PASSWORD":"icDb29mLy2s","REDIS_PORT":"6379","REDIS_READ_HOST":"192.168.1.237","REDIS_READ_PASSWORD":"icDb29mLy2s","REDIS_READ_PORT":"6379","MONG_DB_SPU_ATTRS_HOST":"192.168.1.237","MONG_DB_SPU_ATTRS_USERNAME":"","MONG_DB_SPU_ATTRS_PASSWORD":"","MONG_DB_SPU_ATTRS_DATABASE":"ichunt","CACHE_DRIVER":"file","QUEUE_DRIVER":"sync","SHELL_VERBOSITY":0}}}
\ No newline at end of file
40102
\ No newline at end of file
<?php
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->get('/');
$this->assertEquals(
$this->app->version(), $this->response->getContent()
);
}
}
<?php
abstract class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
}
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit5c9707cde9ea4e3942300fe24293f04f::getLoader();
#!/usr/bin/env sh
dir=$(cd "${0%[/\\]*}" > /dev/null; cd '../hhxsv5/laravel-s/bin' && pwd)
if [ -d /proc/cygdrive ]; then
case $(which php) in
$(readlink -n /proc/cygdrive)/*)
# We are in Cygwin using Windows php, so the path must be translated
dir=$(cygpath -m "$dir");
;;
esac
fi
"${dir}/fswatch" "$@"
#!/usr/bin/env sh
dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../phpunit/phpunit" && pwd)
if [ -d /proc/cygdrive ] && [[ $(which php) == $(readlink -n /proc/cygdrive)/* ]]; then
# We are in Cgywin using Windows php, so the path must be translated
dir=$(cygpath -m "$dir");
fi
"${dir}/phpunit" "$@"
@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/../phpunit/phpunit/phpunit
php "%BIN_TARGET%" %*
Copyright (c) Nils Adermann, Jordi Boggiano
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.
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'72579e7bd17821bb1321b87411366eae' => $vendorDir . '/illuminate/support/helpers.php',
'023d27dca8066ef29e6739335ea73bad' => $vendorDir . '/symfony/polyfill-php70/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'1d1b89d124cc9cb8219922c9d5569199' => $vendorDir . '/hamcrest/hamcrest-php/hamcrest/Hamcrest.php',
'3a37ebac017bc098e9a86b35401e7a68' => $vendorDir . '/mongodb/mongodb/src/functions.php',
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
'd7f4f7522f962c095f835c50e6136087' => $vendorDir . '/hprose/hprose/src/init.php',
'bee9632da3ca00a99623b9c35d0c4f8b' => $vendorDir . '/laravel/lumen-framework/src/helpers.php',
'7039eb1b48735a2a2905d88c22d84a48' => $baseDir . '/common/function.php',
'c71e5a39a1f58c05a11e8537318d6d3d' => $baseDir . '/common/LogReport.php',
);
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src'),
'Mockery' => array($vendorDir . '/mockery/mockery/library'),
'Jenssegers\\Mongodb' => array($vendorDir . '/jenssegers/mongodb/src'),
);
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/reflection-docblock/src', $vendorDir . '/phpdocumentor/type-resolver/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'Symfony\\Polyfill\\Php70\\' => array($vendorDir . '/symfony/polyfill-php70'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'),
'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Predis\\' => array($vendorDir . '/predis/predis/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'MongoDB\\' => array($vendorDir . '/mongodb/mongodb/src'),
'Laravel\\Lumen\\' => array($vendorDir . '/laravel/lumen-framework/src'),
'Illuminate\\View\\' => array($vendorDir . '/illuminate/view'),
'Illuminate\\Validation\\' => array($vendorDir . '/illuminate/validation'),
'Illuminate\\Translation\\' => array($vendorDir . '/illuminate/translation'),
'Illuminate\\Support\\' => array($vendorDir . '/illuminate/support'),
'Illuminate\\Session\\' => array($vendorDir . '/illuminate/session'),
'Illuminate\\Redis\\' => array($vendorDir . '/illuminate/redis'),
'Illuminate\\Queue\\' => array($vendorDir . '/illuminate/queue'),
'Illuminate\\Pipeline\\' => array($vendorDir . '/illuminate/pipeline'),
'Illuminate\\Pagination\\' => array($vendorDir . '/illuminate/pagination'),
'Illuminate\\Http\\' => array($vendorDir . '/illuminate/http'),
'Illuminate\\Hashing\\' => array($vendorDir . '/illuminate/hashing'),
'Illuminate\\Filesystem\\' => array($vendorDir . '/illuminate/filesystem'),
'Illuminate\\Events\\' => array($vendorDir . '/illuminate/events'),
'Illuminate\\Encryption\\' => array($vendorDir . '/illuminate/encryption'),
'Illuminate\\Database\\' => array($vendorDir . '/illuminate/database'),
'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'),
'Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'),
'Illuminate\\Console\\' => array($vendorDir . '/illuminate/console'),
'Illuminate\\Config\\' => array($vendorDir . '/illuminate/config'),
'Illuminate\\Cache\\' => array($vendorDir . '/illuminate/cache'),
'Illuminate\\Bus\\' => array($vendorDir . '/illuminate/bus'),
'Illuminate\\Broadcasting\\' => array($vendorDir . '/illuminate/broadcasting'),
'Illuminate\\Auth\\' => array($vendorDir . '/illuminate/auth'),
'Hprose\\' => array($vendorDir . '/hprose/hprose/src/Hprose'),
'Hhxsv5\\LaravelS\\' => array($vendorDir . '/hhxsv5/laravel-s/src'),
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Common/Inflector'),
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
'Cron\\' => array($vendorDir . '/mtdowling/cron-expression/src/Cron'),
'Common\\' => array($baseDir . '/common'),
'App\\' => array($baseDir . '/app'),
'' => array($vendorDir . '/nesbot/carbon/src'),
);
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit5c9707cde9ea4e3942300fe24293f04f
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit5c9707cde9ea4e3942300fe24293f04f', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit5c9707cde9ea4e3942300fe24293f04f', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit5c9707cde9ea4e3942300fe24293f04f::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit5c9707cde9ea4e3942300fe24293f04f::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire5c9707cde9ea4e3942300fe24293f04f($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire5c9707cde9ea4e3942300fe24293f04f($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
This diff could not be displayed because it is too large.
Copyright (c) 2006-2015 Doctrine Project
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.
# Doctrine Inflector
Doctrine Inflector is a small library that can perform string manipulations
with regard to upper-/lowercase and singular/plural forms of words.
[![Build Status](https://travis-ci.org/doctrine/inflector.svg?branch=master)](https://travis-ci.org/doctrine/inflector)
{
"name": "doctrine/inflector",
"type": "library",
"description": "Common String Manipulations with regard to casing and singular/plural rules.",
"keywords": ["string", "inflection", "singularize", "pluralize"],
"homepage": "http://www.doctrine-project.org",
"license": "MIT",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"},
{"name": "Jonathan Wage", "email": "jonwage@gmail.com"},
{"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"}
],
"require": {
"php": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.2"
},
"autoload": {
"psr-4": { "Doctrine\\Common\\Inflector\\": "lib/Doctrine/Common/Inflector" }
},
"autoload-dev": {
"psr-4": { "Doctrine\\Tests\\Common\\Inflector\\": "tests/Doctrine/Common/Inflector" }
},
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
}
}
}
phpunit.xml
composer.lock
build
vendor
coverage.clover
before_commands:
- "composer install --prefer-source"
tools:
external_code_coverage:
timeout: 600
php_code_coverage:
enabled: true
test_command: ./vendor/bin/phpunit
php_code_sniffer:
enabled: true
config:
standard: PSR2
filter:
paths: ["src/*", "tests/*"]
php_cpd:
enabled: true
excluded_dirs: ["build/*", "tests", "vendor"]
php_cs_fixer:
enabled: true
config:
level: all
filter:
paths: ["src/*", "tests/*"]
php_loc:
enabled: true
excluded_dirs: ["build", "tests", "vendor"]
php_mess_detector:
enabled: true
config:
ruleset: phpmd.xml.dist
design_rules: { eval_expression: false }
filter:
paths: ["src/*"]
php_pdepend:
enabled: true
excluded_dirs: ["build", "tests", "vendor"]
php_analyzer:
enabled: true
filter:
paths: ["src/*", "tests/*"]
php_hhvm:
enabled: true
filter:
paths: ["src/*", "tests/*"]
sensiolabs_security_checker: true
#!/bin/sh
set -x
if [ "$TRAVIS_PHP_VERSION" = 'hhvm' ] || [ "$TRAVIS_PHP_VERSION" = 'hhvm-nightly' ] ; then
curl -sS https://getcomposer.org/installer > composer-installer.php
hhvm composer-installer.php
hhvm -v ResourceLimit.SocketDefaultTimeout=30 -v Http.SlowQueryThreshold=30000 composer.phar update --prefer-source
elif [ "$TRAVIS_PHP_VERSION" = '5.3.3' ] ; then
composer self-update
composer update --prefer-source --no-dev
composer dump-autoload
else
composer self-update
composer update --prefer-source
fi
language: php
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
before_script:
- ./.travis.install.sh
- if [ $TRAVIS_PHP_VERSION = '5.6' ]; then PHPUNIT_FLAGS="--coverage-clover coverage.clover"; else PHPUNIT_FLAGS=""; fi
script:
- if [ $TRAVIS_PHP_VERSION = '5.3.3' ]; then phpunit; fi
- if [ $TRAVIS_PHP_VERSION != '5.3.3' ]; then ./vendor/bin/phpunit $PHPUNIT_FLAGS; fi
- if [ $TRAVIS_PHP_VERSION != '5.3.3' ]; then ./vendor/bin/phpcs --standard=PSR2 ./src/ ./tests/; fi
- if [[ $TRAVIS_PHP_VERSION != '5.3.3' && $TRAVIS_PHP_VERSION != '5.4.29' && $TRAVIS_PHP_VERSION != '5.5.13' ]]; then php -n ./vendor/bin/athletic -p ./tests/DoctrineTest/InstantiatorPerformance/ -f GroupedFormatter; fi
after_script:
- if [ $TRAVIS_PHP_VERSION = '5.6' ]; then wget https://scrutinizer-ci.com/ocular.phar; php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi
# Contributing
* Coding standard for the project is [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
* The project will follow strict [object calisthenics](http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php)
* Any contribution must provide tests for additional introduced conditions
* Any un-confirmed issue needs a failing test case before being accepted
* Pull requests must be sent from a new hotfix/feature branch, not from `master`.
## Installation
To install the project and run the tests, you need to clone it first:
```sh
$ git clone git://github.com/doctrine/instantiator.git
```
You will then need to run a composer installation:
```sh
$ cd Instantiator
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar update
```
## Testing
The PHPUnit version to be used is the one installed as a dev- dependency via composer:
```sh
$ ./vendor/bin/phpunit
```
Accepted coverage for new contributions is 80%. Any contribution not satisfying this requirement
won't be merged.
Copyright (c) 2014 Doctrine Project
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.
# Instantiator
This library provides a way of avoiding usage of constructors when instantiating PHP classes.
[![Build Status](https://travis-ci.org/doctrine/instantiator.svg?branch=master)](https://travis-ci.org/doctrine/instantiator)
[![Code Coverage](https://scrutinizer-ci.com/g/doctrine/instantiator/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/doctrine/instantiator/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/doctrine/instantiator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/doctrine/instantiator/?branch=master)
[![Dependency Status](https://www.versioneye.com/package/php--doctrine--instantiator/badge.svg)](https://www.versioneye.com/package/php--doctrine--instantiator)
[![HHVM Status](http://hhvm.h4cc.de/badge/doctrine/instantiator.png)](http://hhvm.h4cc.de/package/doctrine/instantiator)
[![Latest Stable Version](https://poser.pugx.org/doctrine/instantiator/v/stable.png)](https://packagist.org/packages/doctrine/instantiator)
[![Latest Unstable Version](https://poser.pugx.org/doctrine/instantiator/v/unstable.png)](https://packagist.org/packages/doctrine/instantiator)
## Installation
The suggested installation method is via [composer](https://getcomposer.org/):
```sh
php composer.phar require "doctrine/instantiator:~1.0.3"
```
## Usage
The instantiator is able to create new instances of any class without using the constructor or any API of the class
itself:
```php
$instantiator = new \Doctrine\Instantiator\Instantiator();
$instance = $instantiator->instantiate('My\\ClassName\\Here');
```
## Contributing
Please read the [CONTRIBUTING.md](CONTRIBUTING.md) contents if you wish to help out!
## Credits
This library was migrated from [ocramius/instantiator](https://github.com/Ocramius/Instantiator), which
has been donated to the doctrine organization, and which is now deprecated in favour of this package.
{
"name": "doctrine/instantiator",
"description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
"type": "library",
"license": "MIT",
"homepage": "https://github.com/doctrine/instantiator",
"keywords": [
"instantiate",
"constructor"
],
"authors": [
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com",
"homepage": "http://ocramius.github.com/"
}
],
"require": {
"php": ">=5.3,<8.0-DEV"
},
"require-dev": {
"ext-phar": "*",
"ext-pdo": "*",
"phpunit/phpunit": "~4.0",
"squizlabs/php_codesniffer": "~2.0",
"athletic/athletic": "~0.1.8"
},
"autoload": {
"psr-4": {
"Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
}
},
"autoload-dev": {
"psr-0": {
"DoctrineTest\\InstantiatorPerformance\\": "tests",
"DoctrineTest\\InstantiatorTest\\": "tests",
"DoctrineTest\\InstantiatorTestAsset\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<ruleset
name="Instantiator rules"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
>
<rule ref="rulesets/cleancode.xml">
<!-- static access is used for caching purposes -->
<exclude name="StaticAccess"/>
</rule>
<rule ref="rulesets/codesize.xml"/>
<rule ref="rulesets/controversial.xml"/>
<rule ref="rulesets/design.xml"/>
<rule ref="rulesets/naming.xml"/>
<rule ref="rulesets/unusedcode.xml"/>
<rule
name="NPathComplexity"
message="The {0} {1}() has an NPath complexity of {2}. The configured NPath complexity threshold is {3}."
class="PHP_PMD_Rule_Design_NpathComplexity"
>
<properties>
<property name="minimum" description="The npath reporting threshold" value="10"/>
</properties>
</rule>
</ruleset>
<?xml version="1.0"?>
<phpunit
bootstrap="./vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
verbose="true"
stopOnFailure="false"
processIsolation="false"
backupGlobals="false"
syntaxCheck="true"
>
<testsuite name="Doctrine\Instantiator tests">
<directory>./tests/DoctrineTest/InstantiatorTest</directory>
</testsuite>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Instantiator\Exception;
/**
* Base exception marker interface for the instantiator component
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
interface ExceptionInterface
{
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
/**
* Exception for invalid arguments provided to the instantiator
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
/**
* @param string $className
*
* @return self
*/
public static function fromNonExistingClass($className)
{
if (interface_exists($className)) {
return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
}
if (PHP_VERSION_ID >= 50400 && trait_exists($className)) {
return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
}
return new self(sprintf('The provided class "%s" does not exist', $className));
}
/**
* @param ReflectionClass $reflectionClass
*
* @return self
*/
public static function fromAbstractClass(ReflectionClass $reflectionClass)
{
return new self(sprintf(
'The provided class "%s" is abstract, and can not be instantiated',
$reflectionClass->getName()
));
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Instantiator\Exception;
use Exception;
use ReflectionClass;
use UnexpectedValueException as BaseUnexpectedValueException;
/**
* Exception for given parameters causing invalid/unexpected state on instantiation
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
class UnexpectedValueException extends BaseUnexpectedValueException implements ExceptionInterface
{
/**
* @param ReflectionClass $reflectionClass
* @param Exception $exception
*
* @return self
*/
public static function fromSerializationTriggeredException(ReflectionClass $reflectionClass, Exception $exception)
{
return new self(
sprintf(
'An exception was raised while trying to instantiate an instance of "%s" via un-serialization',
$reflectionClass->getName()
),
0,
$exception
);
}
/**
* @param ReflectionClass $reflectionClass
* @param string $errorString
* @param int $errorCode
* @param string $errorFile
* @param int $errorLine
*
* @return UnexpectedValueException
*/
public static function fromUncleanUnSerialization(
ReflectionClass $reflectionClass,
$errorString,
$errorCode,
$errorFile,
$errorLine
) {
return new self(
sprintf(
'Could not produce an instance of "%s" via un-serialization, since an error was triggered '
. 'in file "%s" at line "%d"',
$reflectionClass->getName(),
$errorFile,
$errorLine
),
0,
new Exception($errorString, $errorCode)
);
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Instantiator;
use Closure;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Exception;
use ReflectionClass;
/**
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
final class Instantiator implements InstantiatorInterface
{
/**
* Markers used internally by PHP to define whether {@see \unserialize} should invoke
* the method {@see \Serializable::unserialize()} when dealing with classes implementing
* the {@see \Serializable} interface.
*/
const SERIALIZATION_FORMAT_USE_UNSERIALIZER = 'C';
const SERIALIZATION_FORMAT_AVOID_UNSERIALIZER = 'O';
/**
* @var \Closure[] of {@see \Closure} instances used to instantiate specific classes
*/
private static $cachedInstantiators = array();
/**
* @var object[] of objects that can directly be cloned
*/
private static $cachedCloneables = array();
/**
* {@inheritDoc}
*/
public function instantiate($className)
{
if (isset(self::$cachedCloneables[$className])) {
return clone self::$cachedCloneables[$className];
}
if (isset(self::$cachedInstantiators[$className])) {
$factory = self::$cachedInstantiators[$className];
return $factory();
}
return $this->buildAndCacheFromFactory($className);
}
/**
* Builds the requested object and caches it in static properties for performance
*
* @param string $className
*
* @return object
*/
private function buildAndCacheFromFactory($className)
{
$factory = self::$cachedInstantiators[$className] = $this->buildFactory($className);
$instance = $factory();
if ($this->isSafeToClone(new ReflectionClass($instance))) {
self::$cachedCloneables[$className] = clone $instance;
}
return $instance;
}
/**
* Builds a {@see \Closure} capable of instantiating the given $className without
* invoking its constructor.
*
* @param string $className
*
* @return Closure
*/
private function buildFactory($className)
{
$reflectionClass = $this->getReflectionClass($className);
if ($this->isInstantiableViaReflection($reflectionClass)) {
return function () use ($reflectionClass) {
return $reflectionClass->newInstanceWithoutConstructor();
};
}
$serializedString = sprintf(
'%s:%d:"%s":0:{}',
$this->getSerializationFormat($reflectionClass),
strlen($className),
$className
);
$this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);
return function () use ($serializedString) {
return unserialize($serializedString);
};
}
/**
* @param string $className
*
* @return ReflectionClass
*
* @throws InvalidArgumentException
*/
private function getReflectionClass($className)
{
if (! class_exists($className)) {
throw InvalidArgumentException::fromNonExistingClass($className);
}
$reflection = new ReflectionClass($className);
if ($reflection->isAbstract()) {
throw InvalidArgumentException::fromAbstractClass($reflection);
}
return $reflection;
}
/**
* @param ReflectionClass $reflectionClass
* @param string $serializedString
*
* @throws UnexpectedValueException
*
* @return void
*/
private function checkIfUnSerializationIsSupported(ReflectionClass $reflectionClass, $serializedString)
{
set_error_handler(function ($code, $message, $file, $line) use ($reflectionClass, & $error) {
$error = UnexpectedValueException::fromUncleanUnSerialization(
$reflectionClass,
$message,
$code,
$file,
$line
);
});
$this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
restore_error_handler();
if ($error) {
throw $error;
}
}
/**
* @param ReflectionClass $reflectionClass
* @param string $serializedString
*
* @throws UnexpectedValueException
*
* @return void
*/
private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, $serializedString)
{
try {
unserialize($serializedString);
} catch (Exception $exception) {
restore_error_handler();
throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception);
}
}
/**
* @param ReflectionClass $reflectionClass
*
* @return bool
*/
private function isInstantiableViaReflection(ReflectionClass $reflectionClass)
{
if (\PHP_VERSION_ID >= 50600) {
return ! ($this->hasInternalAncestors($reflectionClass) && $reflectionClass->isFinal());
}
return \PHP_VERSION_ID >= 50400 && ! $this->hasInternalAncestors($reflectionClass);
}
/**
* Verifies whether the given class is to be considered internal
*
* @param ReflectionClass $reflectionClass
*
* @return bool
*/
private function hasInternalAncestors(ReflectionClass $reflectionClass)
{
do {
if ($reflectionClass->isInternal()) {
return true;
}
} while ($reflectionClass = $reflectionClass->getParentClass());
return false;
}
/**
* Verifies if the given PHP version implements the `Serializable` interface serialization
* with an incompatible serialization format. If that's the case, use serialization marker
* "C" instead of "O".
*
* @link http://news.php.net/php.internals/74654
*
* @param ReflectionClass $reflectionClass
*
* @return string the serialization format marker, either self::SERIALIZATION_FORMAT_USE_UNSERIALIZER
* or self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER
*/
private function getSerializationFormat(ReflectionClass $reflectionClass)
{
if ($this->isPhpVersionWithBrokenSerializationFormat()
&& $reflectionClass->implementsInterface('Serializable')
) {
return self::SERIALIZATION_FORMAT_USE_UNSERIALIZER;
}
return self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER;
}
/**
* Checks whether the current PHP runtime uses an incompatible serialization format
*
* @return bool
*/
private function isPhpVersionWithBrokenSerializationFormat()
{
return PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513;
}
/**
* Checks if a class is cloneable
*
* @param ReflectionClass $reflection
*
* @return bool
*/
private function isSafeToClone(ReflectionClass $reflection)
{
if (method_exists($reflection, 'isCloneable') && ! $reflection->isCloneable()) {
return false;
}
// not cloneable if it implements `__clone`, as we want to avoid calling it
return ! $reflection->hasMethod('__clone');
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Instantiator;
/**
* Instantiator provides utility methods to build objects without invoking their constructors
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
interface InstantiatorInterface
{
/**
* @param string $className
*
* @return object
*
* @throws \Doctrine\Instantiator\Exception\ExceptionInterface
*/
public function instantiate($className);
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace DoctrineTest\InstantiatorPerformance;
use Athletic\AthleticEvent;
use Doctrine\Instantiator\Instantiator;
/**
* Performance tests for {@see \Doctrine\Instantiator\Instantiator}
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
class InstantiatorPerformanceEvent extends AthleticEvent
{
/**
* @var \Doctrine\Instantiator\Instantiator
*/
private $instantiator;
/**
* {@inheritDoc}
*/
protected function setUp()
{
$this->instantiator = new Instantiator();
$this->instantiator->instantiate(__CLASS__);
$this->instantiator->instantiate('ArrayObject');
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\SimpleSerializableAsset');
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\SerializableArrayObjectAsset');
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\UnCloneableAsset');
}
/**
* @iterations 20000
* @baseline
* @group instantiation
*/
public function testInstantiateSelf()
{
$this->instantiator->instantiate(__CLASS__);
}
/**
* @iterations 20000
* @group instantiation
*/
public function testInstantiateInternalClass()
{
$this->instantiator->instantiate('ArrayObject');
}
/**
* @iterations 20000
* @group instantiation
*/
public function testInstantiateSimpleSerializableAssetClass()
{
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\SimpleSerializableAsset');
}
/**
* @iterations 20000
* @group instantiation
*/
public function testInstantiateSerializableArrayObjectAsset()
{
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\SerializableArrayObjectAsset');
}
/**
* @iterations 20000
* @group instantiation
*/
public function testInstantiateUnCloneableAsset()
{
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\UnCloneableAsset');
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace DoctrineTest\InstantiatorTest\Exception;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use PHPUnit_Framework_TestCase;
use ReflectionClass;
/**
* Tests for {@see \Doctrine\Instantiator\Exception\InvalidArgumentException}
*
* @author Marco Pivetta <ocramius@gmail.com>
*
* @covers \Doctrine\Instantiator\Exception\InvalidArgumentException
*/
class InvalidArgumentExceptionTest extends PHPUnit_Framework_TestCase
{
public function testFromNonExistingTypeWithNonExistingClass()
{
$className = __CLASS__ . uniqid();
$exception = InvalidArgumentException::fromNonExistingClass($className);
$this->assertInstanceOf('Doctrine\\Instantiator\\Exception\\InvalidArgumentException', $exception);
$this->assertSame('The provided class "' . $className . '" does not exist', $exception->getMessage());
}
public function testFromNonExistingTypeWithTrait()
{
if (PHP_VERSION_ID < 50400) {
$this->markTestSkipped('Need at least PHP 5.4.0, as this test requires traits support to run');
}
$exception = InvalidArgumentException::fromNonExistingClass(
'DoctrineTest\\InstantiatorTestAsset\\SimpleTraitAsset'
);
$this->assertSame(
'The provided type "DoctrineTest\\InstantiatorTestAsset\\SimpleTraitAsset" is a trait, '
. 'and can not be instantiated',
$exception->getMessage()
);
}
public function testFromNonExistingTypeWithInterface()
{
$exception = InvalidArgumentException::fromNonExistingClass('Doctrine\\Instantiator\\InstantiatorInterface');
$this->assertSame(
'The provided type "Doctrine\\Instantiator\\InstantiatorInterface" is an interface, '
. 'and can not be instantiated',
$exception->getMessage()
);
}
public function testFromAbstractClass()
{
$reflection = new ReflectionClass('DoctrineTest\\InstantiatorTestAsset\\AbstractClassAsset');
$exception = InvalidArgumentException::fromAbstractClass($reflection);
$this->assertSame(
'The provided class "DoctrineTest\\InstantiatorTestAsset\\AbstractClassAsset" is abstract, '
. 'and can not be instantiated',
$exception->getMessage()
);
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace DoctrineTest\InstantiatorTest\Exception;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Exception;
use PHPUnit_Framework_TestCase;
use ReflectionClass;
/**
* Tests for {@see \Doctrine\Instantiator\Exception\UnexpectedValueException}
*
* @author Marco Pivetta <ocramius@gmail.com>
*
* @covers \Doctrine\Instantiator\Exception\UnexpectedValueException
*/
class UnexpectedValueExceptionTest extends PHPUnit_Framework_TestCase
{
public function testFromSerializationTriggeredException()
{
$reflectionClass = new ReflectionClass($this);
$previous = new Exception();
$exception = UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $previous);
$this->assertInstanceOf('Doctrine\\Instantiator\\Exception\\UnexpectedValueException', $exception);
$this->assertSame($previous, $exception->getPrevious());
$this->assertSame(
'An exception was raised while trying to instantiate an instance of "'
. __CLASS__ . '" via un-serialization',
$exception->getMessage()
);
}
public function testFromUncleanUnSerialization()
{
$reflection = new ReflectionClass('DoctrineTest\\InstantiatorTestAsset\\AbstractClassAsset');
$exception = UnexpectedValueException::fromUncleanUnSerialization($reflection, 'foo', 123, 'bar', 456);
$this->assertInstanceOf('Doctrine\\Instantiator\\Exception\\UnexpectedValueException', $exception);
$this->assertSame(
'Could not produce an instance of "DoctrineTest\\InstantiatorTestAsset\\AbstractClassAsset" '
. 'via un-serialization, since an error was triggered in file "bar" at line "456"',
$exception->getMessage()
);
$previous = $exception->getPrevious();
$this->assertInstanceOf('Exception', $previous);
$this->assertSame('foo', $previous->getMessage());
$this->assertSame(123, $previous->getCode());
}
}
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace DoctrineTest\InstantiatorTest;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Doctrine\Instantiator\Instantiator;
use PHPUnit_Framework_TestCase;
use ReflectionClass;
/**
* Tests for {@see \Doctrine\Instantiator\Instantiator}
*
* @author Marco Pivetta <ocramius@gmail.com>
*
* @covers \Doctrine\Instantiator\Instantiator
*/
class InstantiatorTest extends PHPUnit_Framework_TestCase
{
/**
* @var Instantiator
*/
private $instantiator;
/**
* {@inheritDoc}
*/
protected function setUp()
{
$this->instantiator = new Instantiator();
}
/**
* @param string $className
*
* @dataProvider getInstantiableClasses
*/
public function testCanInstantiate($className)
{
$this->assertInstanceOf($className, $this->instantiator->instantiate($className));
}
/**
* @param string $className
*
* @dataProvider getInstantiableClasses
*/
public function testInstantiatesSeparateInstances($className)
{
$instance1 = $this->instantiator->instantiate($className);
$instance2 = $this->instantiator->instantiate($className);
$this->assertEquals($instance1, $instance2);
$this->assertNotSame($instance1, $instance2);
}
public function testExceptionOnUnSerializationException()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped(
'As of facebook/hhvm#3432, HHVM has no PDORow, and therefore '
. ' no internal final classes that cannot be instantiated'
);
}
$className = 'DoctrineTest\\InstantiatorTestAsset\\UnserializeExceptionArrayObjectAsset';
if (\PHP_VERSION_ID >= 50600) {
$className = 'PDORow';
}
if (\PHP_VERSION_ID === 50429 || \PHP_VERSION_ID === 50513) {
$className = 'DoctrineTest\\InstantiatorTestAsset\\SerializableArrayObjectAsset';
}
$this->setExpectedException('Doctrine\\Instantiator\\Exception\\UnexpectedValueException');
$this->instantiator->instantiate($className);
}
public function testNoticeOnUnSerializationException()
{
if (\PHP_VERSION_ID >= 50600) {
$this->markTestSkipped(
'PHP 5.6 supports `ReflectionClass#newInstanceWithoutConstructor()` for some internal classes'
);
}
try {
$this->instantiator->instantiate('DoctrineTest\\InstantiatorTestAsset\\WakeUpNoticesAsset');
$this->fail('No exception was raised');
} catch (UnexpectedValueException $exception) {
$wakeUpNoticesReflection = new ReflectionClass('DoctrineTest\\InstantiatorTestAsset\\WakeUpNoticesAsset');
$previous = $exception->getPrevious();
$this->assertInstanceOf('Exception', $previous);
// in PHP 5.4.29 and PHP 5.5.13, this case is not a notice, but an exception being thrown
if (! (\PHP_VERSION_ID === 50429 || \PHP_VERSION_ID === 50513)) {
$this->assertSame(
'Could not produce an instance of "DoctrineTest\\InstantiatorTestAsset\WakeUpNoticesAsset" '
. 'via un-serialization, since an error was triggered in file "'
. $wakeUpNoticesReflection->getFileName() . '" at line "36"',
$exception->getMessage()
);
$this->assertSame('Something went bananas while un-serializing this instance', $previous->getMessage());
$this->assertSame(\E_USER_NOTICE, $previous->getCode());
}
}
}
/**
* @param string $invalidClassName
*
* @dataProvider getInvalidClassNames
*/
public function testInstantiationFromNonExistingClass($invalidClassName)
{
$this->setExpectedException('Doctrine\\Instantiator\\Exception\\InvalidArgumentException');
$this->instantiator->instantiate($invalidClassName);
}
public function testInstancesAreNotCloned()
{
$className = 'TemporaryClass' . uniqid();
eval('namespace ' . __NAMESPACE__ . '; class ' . $className . '{}');
$instance = $this->instantiator->instantiate(__NAMESPACE__ . '\\' . $className);
$instance->foo = 'bar';
$instance2 = $this->instantiator->instantiate(__NAMESPACE__ . '\\' . $className);
$this->assertObjectNotHasAttribute('foo', $instance2);
}
/**
* Provides a list of instantiable classes (existing)
*
* @return string[][]
*/
public function getInstantiableClasses()
{
$classes = array(
array('stdClass'),
array(__CLASS__),
array('Doctrine\\Instantiator\\Instantiator'),
array('Exception'),
array('PharException'),
array('DoctrineTest\\InstantiatorTestAsset\\SimpleSerializableAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\ExceptionAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\FinalExceptionAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\PharExceptionAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\UnCloneableAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\XMLReaderAsset'),
);
if (\PHP_VERSION_ID === 50429 || \PHP_VERSION_ID === 50513) {
return $classes;
}
$classes = array_merge(
$classes,
array(
array('PharException'),
array('ArrayObject'),
array('DoctrineTest\\InstantiatorTestAsset\\ArrayObjectAsset'),
array('DoctrineTest\\InstantiatorTestAsset\\SerializableArrayObjectAsset'),
)
);
if (\PHP_VERSION_ID >= 50600) {
$classes[] = array('DoctrineTest\\InstantiatorTestAsset\\WakeUpNoticesAsset');
$classes[] = array('DoctrineTest\\InstantiatorTestAsset\\UnserializeExceptionArrayObjectAsset');
}
return $classes;
}
/**
* Provides a list of instantiable classes (existing)
*
* @return string[][]
*/
public function getInvalidClassNames()
{
$classNames = array(
array(__CLASS__ . uniqid()),
array('Doctrine\\Instantiator\\InstantiatorInterface'),
array('DoctrineTest\\InstantiatorTestAsset\\AbstractClassAsset'),
);
if (\PHP_VERSION_ID >= 50400) {
$classNames[] = array('DoctrineTest\\InstantiatorTestAsset\\SimpleTraitAsset');
}
return $classNames;
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment