Commit d1f304b3 by yeran

remove someothers dependence

1 parent 259c97b1
......@@ -3,7 +3,7 @@
"description": "Phalcon",
"keywords": ["phwoolcon"],
"type": "library",
"version": "1.0.3",
"version": "1.0.4",
"license": "proprietary",
"authors": [
{
......@@ -17,12 +17,14 @@
"php": ">=7.1",
"ext-curl": "*",
"ext-json": "*",
"ext-xml": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-PDO": "*",
"ext-mbstring": "*",
"symfony/console": "~3.0",
"pda/pheanstalk": "~3.1",
"swiftmailer/swiftmailer": "~5.4|~6.0"
"swiftmailer/swiftmailer": "~5.4|~6.0",
},
"require-dev": {
},
......
......@@ -80,7 +80,7 @@ class Cache
$di->remove('cache');
static::$cache = null;
$di->setShared('cache', function () {
$frontend = new Data(['lifetime' => static::TTL_ONE_DAY]);
$frontend = new Data(['lifetime' => static::TTL_ONE_WEEK]);
$default = Config::get('cache.default');
$config = Config::get('cache.drivers.' . $default);
$class = $config['adapter'];
......@@ -105,6 +105,9 @@ class Cache
/**
* @param string $key
* @param $value
* @param null $ttl
* @throws \Phalcon\Cache\Exception
*/
public static function set($key, $value, $ttl = null)
{
......
......@@ -2,13 +2,12 @@
namespace Phwoolcon;
use core\base\Exception\ApiException;
use core\common\ErrorCode;
use core\service\security\AES;
use core\service\security\KeyConfig;
use core\service\security\Secret;
use Phalcon\Mvc\Controller as PhalconController;
use Phwoolcon\Controller\Api;
use Phwoolcon\Crypt\AES;
use Phwoolcon\Crypt\KeyConfig;
use Phwoolcon\Exception\Http\ApiException;
use Phwoolcon\Util\Common;
/**
* Class Controllers
......@@ -18,6 +17,10 @@ use Phwoolcon\Controller\Api;
* @property Session|Session\AdapterTrait $session
* @property View $view
*/
defined('IS_DEBUG') or define('IS_DEBUG', false);
defined('ENCRYPT_FIELD_NAME') or define('ENCRYPT_FIELD_NAME', false);
abstract class Controller extends PhalconController
{
......@@ -71,10 +74,10 @@ abstract class Controller extends PhalconController
$contents = AES::aes128Decrypt($encrypt_string, Config::get('security.secret_key.data') ?: KeyConfig::SECRET_KEY_AES_LESTORE, Config::get('security.secret_iv.data') ?: KeyConfig::SECRET_KEY_AES_LESTORE);
unset($encrypt_string);
if (!empty($contents)) {
if (is_json($contents)) {
if (Common::is_json($contents)) {
$decrypt_data = json_decode($contents, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} elseif (is_xml($contents)) {
$decrypt_data = xml_decode($contents);
} elseif (Common::is_xml($contents)) {
$decrypt_data = Common::xml_decode($contents);
} else {
$decrypt_data = null;
}
......@@ -94,7 +97,7 @@ abstract class Controller extends PhalconController
$filters = explode(',', $filters);
}
foreach ($filters as $filter) {
$data = array_map_recursive($filter, $data); //参数过滤
$data = Common::array_map_recursive($filter, $data); //参数过滤
}
}
} elseif ((is_array($input) && isset($input[$name])) || is_string($input)) { //取值操作
......@@ -110,7 +113,7 @@ abstract class Controller extends PhalconController
if (1 !== preg_match($filters, (string)$data)) { //支持正则验证
if (false !== $is_validate) {
self::idebug('[ApiException] 参数获取异常,参数名称:' . $name);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', ErrorCode::INVALID_PARAMETER);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', 40001);
}
return isset($default) ? $default : null;
}
......@@ -123,13 +126,13 @@ abstract class Controller extends PhalconController
if (is_array($filters)) {
foreach ($filters as $filter) {
if (function_exists($filter)) {
$data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data); //参数过滤
$data = is_array($data) ? Common::array_map_recursive($filter, $data) : $filter($data); //参数过滤
} else {
$data = filter_var($data, is_int($filter) ? $filter : filter_id($filter));
if (false === $data) {
if (false !== $is_validate) {
self::idebug('[ApiException] 参数获取异常,参数名称:' . $name);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', ErrorCode::INVALID_PARAMETER);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', 40001);
}
return isset($default) ? $default : null;
}
......@@ -144,7 +147,7 @@ abstract class Controller extends PhalconController
}
if (false !== $is_validate) {
self::idebug('[ApiException] 参数获取异常,参数名称:' . $name);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', ErrorCode::INVALID_PARAMETER);
throw new ApiException((true !== $is_validate && null !== $is_validate) ? $is_validate : '参数值校验失败', 40001);
}
$data = isset($default) ? $default : null; //变量默认值
}
......@@ -310,7 +313,7 @@ abstract class Controller extends PhalconController
private static function idebug($message, $type = 'DEBUG')
{
if (IS_DEBUG) {
debug($message, $type);
Log::debug($message);
}
}
}
......@@ -2,13 +2,9 @@
namespace Phwoolcon\Controller;
use core\service\security\AES;
use core\service\security\KeyConfig;
use InvalidArgumentException;
use Phwoolcon\Config;
use phwoolcon\core\common\CodeMsg;
use Phwoolcon\Crypt\AES;
use Phwoolcon\ErrorCodes;
use Phwoolcon\Log;
use Phwoolcon\Router;
/**
......@@ -112,7 +108,6 @@ trait Api
$extraData['data'] = $data;
}
}
// $extraData['error'] = $errorCode ?: 1;
$extraData['error'] = $errorCode;
if (!$errorMsg) {
$errorCode = ErrorCodes::getCodeMsg($errorCode);
......
......@@ -88,6 +88,7 @@ class Cookies
/**
* @return Http\Cookie[]
* @throws \ReflectionException
*/
public static function toArray()
{
......
<?php
namespace Phwoolcon\Crypt;
class AES implements Crypt
{
/**
* 加密
* @param string $str
* @param $key
* @return string
*/
static function encrypt($str, $key)
{
//AES, 256 cbc模式加密数据
$encrypt_str = openssl_encrypt($str, 'aes-256-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode(KeyConfig::$iv));
return base64_encode($encrypt_str);
}
/**
* 解密
* @param string $str
* @param $key
* @return string
*/
static function decrypt($str, $key)
{
//AES, 256 cbc模式解密数据
$str = base64_decode($str);
return openssl_decrypt($str, 'aes-256-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode(KeyConfig::$iv));
}
/**
* 填充算法(chr()用于返回ASCII指定的字符,如chr(97)返回a)
* @param string $source
* @return string
*/
static function addPKCS7Padding($source)
{
$source = trim($source);
$block = mcrypt_get_block_size('rijndael-128', 'cbc');
$pad = $block - (strlen($source) % $block);
if ($pad <= $block) {
$char = chr($pad);
$source .= str_repeat($char, $pad);
}
return $source;
}
/**
* 移去填充算法(ord()函数用于返回一个字符的ASCII值)
* @param string $source
* @return string
*/
static function stripPKSC7Padding($source)
{
$char = substr($source, -1);
$num = ord($char);
$source = substr($source, 0, -$num);
return $source;
}
/**
* aes128加密
* @param mixed $data 数据
* @param string $key 加密key
* @param string $iv 加密向量
* @return string
* @author wangyu <wangyu@ledouya.com>
* @createTime 2018/5/30 14:23
*/
public static function aes128Encrypt($data, $key, $iv)
{
if (is_array($data)) {
$encrypt_data = json_encode($data);
} elseif (is_object($data)) {
$encrypt_data = json_encode($data, JSON_FORCE_OBJECT);
} else {
$encrypt_data = $data;
}
$encrypted = openssl_encrypt($encrypt_data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($encrypted);
}
/**
* aes128解密
* @param string $data 字符串
* @param string $key 加密key
* @param string $iv 加密向量
* @return string
* @author wangyu <wangyu@ledouya.com>
* @createTime 2018/5/30 14:23
*/
public static function aes128Decrypt($data, $key, $iv)
{
return rtrim(openssl_decrypt(base64_decode($data), 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv));
}
}
<?php
/**
* Created by IntelliJ IDEA.
* User: yeran
* Date: 2018/1/8
* Time: 上午1:51
*/
namespace Phwoolcon\Crypt;
interface Crypt{
public static function encrypt($str,$key);
public static function decrypt($str,$key);
}
<?php
/**
* Created by IntelliJ IDEA.
* User: yeran
* Date: 2018/1/8
* Time: 上午2:04
*/
namespace Phwoolcon\Crypt;
class KeyConfig
{
public static $iv = '9jpn9nWucZtQT3+k114gpg==';
const SECRET_KEY_AES_LESCENE = 'lexianchangyeran';
const SECRET_KEY_AES_LESTORE = 'ledianyeran12345';
const SECRET_KEY_AES_AUTH = 'lestoreyeran1234';
}
<?php
/**
* Created by IntelliJ IDEA.
*
* 加解密算法
*
* User: yeran
* Date: 2018/1/8
* Time: 上午1:46
*/
namespace Phwoolcon\Crypt;
class Secret{
public static function encrypt($way,$str,$key){
switch ($way){
case 'AES':{
return AES::encrypt($str,$key);
}
case 'MD5':{
return md5($str);
}
default:
return AES::encrypt($str,$key);
}
}
public static function decrypt($way,$str,$key){
switch ($way){
case 'AES':{
return AES::decrypt($str,$key);
}
default:
return AES::decrypt($str,$key);
}
}
}
......@@ -3,9 +3,9 @@
namespace Phwoolcon\Daemon;
use Closure;
use core\base\Exception\ApiException;
use ErrorException;
use Phwoolcon\Db;
use Phwoolcon\Exception\Http\ApiException;
use Phwoolcon\Util\Timer;
use Swoole\Server as SwooleServer;
use Phalcon\Di;
......@@ -17,7 +17,6 @@ use Phwoolcon\Cookies;
use Phwoolcon\Events;
use Phwoolcon\Router;
use Phwoolcon\Session;
use XHProfRuns_Default;
class Service
{
......@@ -59,6 +58,11 @@ class Service
protected $serviceAwareComponents = [];
protected $debugData = [];
/**
* Service constructor.
* @param $config
* @throws ErrorException
*/
public function __construct($config)
{
// @codeCoverageIgnoreStart
......@@ -386,28 +390,6 @@ class Service
return $result;
}
/**
* @param SwooleServer $server
* @param $fd
* @param $fromId
* @param $data
* @codeCoverageIgnore
*/
public function profileReceive(SwooleServer $server, $fd, $fromId, $data)
{
xhprof_enable(0, [
'ignored_functions' => [
'call_user_func',
'call_user_func_array',
],
]);
$this->onReceive($server, $fd, $fromId, $data);
$microTime = explode(' ', microtime());
$pathInfo = strtr(Router::getCurrentUri(), ['/' => '|']);
$reportFile = $microTime[1] . '-' . substr($microTime[0], 2) . '-' . $_SERVER['REQUEST_METHOD'] . $pathInfo;
$this->profiler or $this->profiler = new XHProfRuns_Default($this->profilerDir);
$this->profiler->save_run(xhprof_disable(), 'service', $reportFile);
}
public static function register(Di $di)
{
......
......@@ -29,6 +29,7 @@ class Db extends PhalconDb
protected $connections = [];
protected $config;
public function __construct($config)
{
//PHP_SAPI == 'cli' ? $config['connections']['mysql']['persistent'] = true : $config['connections']['mysql']['persistent'] = false;
......@@ -36,15 +37,19 @@ class Db extends PhalconDb
$ormOptions = $config['orm_options'];
$ormOptions['distributed'] = $config['distributed'];
Model::setup($ormOptions);
if (fnGet($this->config, 'query_log')) {
Events::attach('db', function ($event, $connection) {
Log::debug('---db--event--');
$adapter = $event->getSource();
Events::attach('db', function (Event $event) {
/* @var Adapter $adapter */
$adapter = $event->getSource();
$eventType = $event->getType();
// $eventType == 'beginTransaction' ||
if ((PHP_SAPI == 'cli') && $adapter && ($eventType == 'beforeQuery')) {
$adapter->connect();
}
if (fnGet($this->config, 'query_log')) {
$binds = $adapter->getSqlVariables();
Log::debug(json_encode($adapter->getDescriptor()));
Log::debug($adapter->getRealSQLStatement() . '; binds = ' . var_export($binds, 1));
});
}
Log::debug($adapter->getSQLStatement() . '; binds = ' . var_export($binds, 1));
}
});
}
public static function clearMetadata()
......@@ -71,6 +76,7 @@ class Db extends PhalconDb
protected function connect($name)
{
$name = static::$instance->config[$name] ?? $name;
$connection = $this->config['connections'][$name];
$class = $connection['adapter'];
isset($connection['charset']) and static::$defaultTableCharset[$name] = $connection['charset'];
......
......@@ -57,9 +57,9 @@ class HttpException extends RuntimeException
public function getBody()
{
if($this->getCode()==204){
return null;
}
if($this->getCode()==204){
return null;
}
return json_encode([
'jsonapi' => ['version' => '1.0'],
'error' => $this->getCode(),
......
......@@ -505,7 +505,7 @@ abstract class Model extends PhalconModel
$params['conditions'] = $conditions;
$params['bind'] = $bind;
}
// debug(json_encode($params));
// debug(json_encode($params));
return $params;
}
}
......@@ -5,7 +5,6 @@ namespace Phwoolcon\Model\MetaData;
use Phwoolcon\Cache;
use Phalcon\Mvc\ModelInterface;
use Phalcon\Mvc\Model\MetaData;
use Phalcon\Mvc\Model\Exception;
/**
* Phwoolcon\Model\MetaData\InCache
......@@ -34,7 +33,7 @@ class InCache extends MetaData
*/
public function read($key)
{
$this->_cachedData or $this->_cachedData = Cache::get('model-metadata');
$this->_cachedData or $this->_cachedData = Cache::get('model-metadata') ?? [];
return isset($this->_cachedData[$key]) ? $this->_cachedData[$key] : null;
}
......@@ -42,10 +41,11 @@ class InCache extends MetaData
* Writes the meta-data to files
*
* @param string $key
* @param array $data
* @param array $data
*/
public function write($key, $data)
{
if (!isset($this->_cachedData)) return;
$this->_cachedData[$key] = $data;
Cache::set('model-metadata', $this->_cachedData, Cache::TTL_ONE_MONTH);
}
......
......@@ -7,7 +7,6 @@ use Phwoolcon\Exception\InvalidConfigException;
use Phwoolcon\Queue\AdapterInterface;
use Phwoolcon\Queue\AdapterTrait;
use Phwoolcon\Queue\FailedLoggerDb;
use Workerman\MySQL\Connection as MySQL;
class Queue
{
......@@ -29,9 +28,6 @@ class Queue
public function __construct($config)
{
//为避免消息队列中mysql的连接长时间没有通讯而被mysql服务端踢掉,所以在消息队列中使用该数据库类,该类当发生mysql gone away错误时,会自动重试一次
global $mysql;
$mysqlConfig = Config::get('database.connections.mysql');
$mysql = new MySQL($mysqlConfig['host'], empty($mysqlConfig['port']) ? 3306 : $mysqlConfig['port'], $mysqlConfig['username'], $mysqlConfig['password'], $mysqlConfig['dbname'], $mysqlConfig['charset']); //实例化mysql组件并连接
$this->config = $config;
static::$di->has('queueFailLogger') or static::$di->setShared('queueFailLogger', function () use ($config) {
......
<?php
/**
* Created by IntelliJ IDEA.
* User: yeran
* Date: 2018/5/11
* Time: 下午6:34
*/
namespace Phwoolcon\Queue\Adapter;
use Phwoolcon\Queue\Adapter\RocketMQ\Job;
use Phwoolcon\Queue\Adapter\RocketMQ\RocketClient;
use Phwoolcon\Queue\AdapterInterface;
use Phwoolcon\Queue\AdapterTrait;
class RocketMQ implements AdapterInterface
{
use AdapterTrait;
protected $readTimeout = null;
/**
* @var RocketClient
*/
private $connection;
protected function connect(array $options)
{
// @codeCoverageIgnoreStart
if ($this->connection) {
return;
}
// @codeCoverageIgnoreEnd
$this->connection = new RocketClient(
$options['host'],
$options['port'],
$options['connect_timeout'],
$options['persistence']
);
isset($options['read_timeout']) and $this->readTimeout = $options['read_timeout'];
}
public function pop($queue = null,$tags=null)
{
$queue = $this->getQueue($queue);
if (($job = $this->connection->watchOnly($queue,$tags)->reserve($this->readTimeout))) {
return new Job($this, $job, $queue);
}
return null;
}
public function reserve($queue = null,$tags=null){
$queue = $this->getQueue($queue);
$listener = $this->connection->watchOnly($queue,$tags);
echo '----';
while (($job = $listener->reserve($this->readTimeout))) {
return new Job($this, $job, $queue);
}
echo '-finish---';
return null;
}
public function pushRaw($payload, $queue = null, array $options = [])
{
$payload = (string)$payload;
$priority = isset($options['priority']) ? $options['priority'] : Pheanstalk::DEFAULT_PRIORITY;
$delay = isset($options['delay']) ? $options['delay'] : Pheanstalk::DEFAULT_DELAY;
$timeToRun = isset($options['ttr']) ? $options['ttr'] : Pheanstalk::DEFAULT_TTR;
return $this->connection->useTube($this->getQueue($queue))
->put($payload, $priority, $delay, $timeToRun);
}
}
\ No newline at end of file
<?php
namespace Phwoolcon\Queue\Adapter\RocketMQ;
use Phwoolcon\Queue\Adapter\JobInterface;
use Phwoolcon\Queue\Adapter\JobTrait;
class Job implements JobInterface
{
use JobTrait;
protected function _delete()
{
$this->connection->delete($this->rawJob);
}
protected function _release($delay = 0)
{
$priority = Pheanstalk::DEFAULT_PRIORITY;
$this->connection->release($this->rawJob, $priority, $delay);
}
public function attempts()
{
$stats = $this->connection->statsJob($this->rawJob);
return (int)$stats->reserves;
}
/**
* Bury the job in the queue.
*
* @return void
*/
public function bury()
{
$this->connection->bury($this->rawJob);
}
/**
* Get the job identifier.
*
* @return integer
*/
public function getJobId()
{
return $this->rawJob->getId();
}
public function getRawBody()
{
return $this->rawJob->getData();
}
}
<?php
/**
* Created by IntelliJ IDEA.
* User: yeran
* Date: 2018/5/12
* Time: 上午12:52
*/
namespace Phwoolcon\Queue\Adapter\RocketMQ;
use core\service\asyn\tcp\ClientPool;
class RocketClient
{
/**
* @var
*/
private $tcpClient;
public function __construct( $host, $port, $connect_timeout,$persistence)
{
// 注册tcp连接,默认执行连接
$this->tcpClient = ClientPool::getInstance()->getAsyncClient();
}
/**
* 注册监听topic和tags
*
* @param $topic
* @param $tags
* @return $this
*/
public function watchOnly($topic,$tags,$callback=null){
// 发送第一次tcp请求,声明监听topic和tags
$data = [
'msg' => [
'topic' => $topic,
'tags' => $tags
],
'access' =>[
'appid' => 'LD_yeran001',
'accessKey' => ''
]
];
ClientPool::getInstance()->send($this->tcpClient,json_encode($data), function ($result) use ($callback) {
if($callback){
call_user_func($callback,$result);
}
return $this;
});
}
/**
* 启动阻塞监听,如果收到新的消息,会通过回调传入
*
* @param $readTimeout
*/
public function reserve($readTimeout){
// 启动消息结果回调
return new RowJob(1,"dasda");
}
/**
*
* 发送消息至队列
*
* @param $msg
*/
public function send($msg){
}
}
\ No newline at end of file
<?php
/**
* Created by IntelliJ IDEA.
* User: yeran
* Date: 2018/5/12
* Time: 上午1:15
*/
namespace Phwoolcon\Queue\Adapter\RocketMQ;
class RowJob
{
private $messageId;
private $data;
/**
* RowJob constructor.
* @param $messageId
* @param $data
*/
public function __construct($messageId, $data)
{
$this->messageId = $messageId;
$this->data = $data;
}
/**
* @return mixed
*/
public function getMessageId()
{
return $this->messageId;
}
/**
* @param mixed $messageId
*/
public function setMessageId($messageId)
{
$this->messageId = $messageId;
}
/**
* @return mixed
*/
public function getData()
{
return $this->data;
}
/**
* @param mixed $data
*/
public function setData($data)
{
$this->data = $data;
}
}
\ No newline at end of file
......@@ -51,6 +51,7 @@ class Text extends PhalconText
* @param int $type
* @param int $length
* @return string
* @throws \Exception
* @codeCoverageIgnore
*/
public static function random($type = 0, $length = 8)
......
<?php
namespace Phwoolcon\Util;
class Common
{
/**
* 是否为json
* @param $string
* @param bool $strip_bom
* @return bool
*/
public static function is_json($string, $strip_bom = true)
{
if ($strip_bom) json_decode(trim($string, chr(239) . chr(187) . chr(191))); else json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
/**
* 是否为xml
* @param $xml
* @return bool
*/
public static function is_xml($xml)
{
$xml_parser = xml_parser_create();
if (!xml_parse($xml_parser, $xml, true)) {
xml_parser_free($xml_parser);
return false;
} else {
return true;
}
}
/**
* XML解码
* @param $xml
* @return bool|mixed
*/
public static function xml_decode($xml)
{
if (!$xml) {
return false;
}
// 检查xml是否合法
$xml_parser = xml_parser_create();
if (!xml_parse($xml_parser, $xml, true)) {
xml_parser_free($xml_parser);
return false;
}
libxml_disable_entity_loader(true); //禁止引用外部xml实体
//将XML转为array
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}
/**
* 数组过滤
*
* @param $filter
* @param $data
* @return array
*/
public static function array_map_recursive($filter, $data)
{
$result = array();
foreach ($data as $key => $val) {
$result[$key] = is_array($val) ? self::array_map_recursive($filter, $val) : call_user_func($filter, $val);
}
return $result;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!