Esempio n. 1
0
 public function get($index, $defaultValue = null, $remove = false)
 {
     $this->_uniqueId and $index = $this->_uniqueId . '#' . $index;
     $value = fnGet($_SESSION, $index, $defaultValue, '.');
     $remove and array_forget($_SESSION, $index);
     return $value;
 }
Esempio n. 2
0
 public static function log($type, $message = null, array $context = [])
 {
     static::$logger or static::$logger = Di::getDefault()->getShared('log');
     $context['host'] = static::$hostname;
     $context['request'] = fnGet($_SERVER, 'REQUEST_METHOD') . ' ' . fnGet($_SERVER, 'REQUEST_URI');
     static::$logger->log($type, $message, $context);
 }
Esempio n. 3
0
 public function testGetPhwoolconJsOptions()
 {
     $jsOptions = View::getPhwoolconJsOptions();
     $this->assertArrayHasKey('baseUrl', $jsOptions, 'View::getPhwoolconJsOptions(): baseUrl not set');
     $this->assertArrayHasKey('cookies', $jsOptions, 'View::getPhwoolconJsOptions(): cookies not set');
     $this->assertArrayHasKey('domain', fnGet($jsOptions, 'cookies'), 'View::getPhwoolconJsOptions(): cookies.domain not set');
     $this->assertArrayHasKey('path', fnGet($jsOptions, 'cookies'), 'View::getPhwoolconJsOptions(): cookies.path not set');
 }
Esempio n. 4
0
 protected function createMigrateFile()
 {
     foreach (glob(migrationPath('/*test.php')) as $file) {
         @unlink($file);
     }
     $output = $this->runCommand('migrate:create', ['test']);
     preg_match('/Created\\ Migration:\\ (.+)/', $output, $matches);
     return fnGet($matches, 1);
 }
Esempio n. 5
0
 protected function keyList()
 {
     $keys = [];
     foreach (Config::get() as $key => $value) {
         if (is_array(fnGet($value, '_black_list')) || is_array(fnGet($value, '_white_list'))) {
             $keys[$key] = static::getKeyLabel($key);
         }
     }
     ksort($keys);
     return $keys;
 }
Esempio n. 6
0
 public function testFnGet()
 {
     $array = ['child' => ['child' => ['child' => 'no child']]];
     $obj = json_decode(json_encode($array));
     $default = 'default';
     $this->assertEquals($array['child']['child']['child'], fnGet($array, 'child.child.child'), 'Unable to fetch child on array');
     $this->assertEquals($array['child']['child']['child'], fnGet($array, 'child.child.child', null, '.', true), 'Unable to fetch child on array');
     $this->assertEquals($obj->child->child->child, fnGet($obj, 'child.child.child', null, '.', true), 'Unable to fetch child on object');
     $this->assertEquals($default, fnGet($array, 'bad.key', $default), 'Unable to return default value if child not found on array');
     $this->assertEquals($default, fnGet($obj, 'bad.key', $default, '.', true), 'Unable to return default value if child not found on object');
 }
Esempio n. 7
0
 /**
  * @param string $key
  * @return mixed|OrderData
  */
 public function getOrderData($key = null)
 {
     if ($this->orderData === null) {
         if ($existingOrderData = $this->__get('order_data')) {
             $this->orderData = $existingOrderData;
         } else {
             $this->orderData = $this->_dependencyInjector->get(OrderData::class);
             $this->__set('order_data', $this->orderData);
         }
     }
     $data = $this->orderData->getData('data');
     return $key ? fnGet($data, $key) : $this->orderData;
 }
Esempio n. 8
0
 public function __construct($config)
 {
     $this->config = $config;
     $ormOptions = $config['orm_options'];
     $ormOptions['distributed'] = $config['distributed'];
     Model::setup($ormOptions);
     if (fnGet($this->config, 'query_log')) {
         Events::attach('db:beforeQuery', function (Event $event) {
             /* @var Adapter $adapter */
             $adapter = $event->getSource();
             $binds = $adapter->getSqlVariables();
             Log::debug($adapter->getSQLStatement() . '; binds = ' . var_export($binds, 1));
         });
     }
 }
Esempio n. 9
0
 public function getPaymentMethod($gateway, $method = null)
 {
     if (!($config = fnGet(static::$instance->config, 'gateways.' . $gateway))) {
         throw new GeneralException(__('Undefined payment gateway: [%gateway%]', ['gateway' => $gateway]), GeneralException::UNDEFINED_PAYMENT_GATEWAY);
     }
     $class = fnGet($config, 'methods.' . $method . '.class');
     $class or $class = fnGet($config, 'class');
     if (!$class || !class_exists($class)) {
         throw new GeneralException(__('Undefined payment method: [%gateway%.%method%]', ['gateway' => $gateway, 'method' => $method]), GeneralException::UNDEFINED_PAYMENT_METHOD);
     }
     /* @var MethodTrait $paymentMethod */
     $paymentMethod = new $class($config);
     if (!$paymentMethod instanceof MethodInterface) {
         throw new GeneralException(__('Invalid payment method class: [%class%]', ['class' => $class]), GeneralException::INVALID_PAYMENT_METHOD);
     }
     return $paymentMethod;
 }
Esempio n. 10
0
 public function mobilePayRequestAction()
 {
     $params = array('payment_agent' => 'alipay', 'method' => 'mobile_alipay', 'data' => $this->input, 'suppress_coupon_exception' => true);
     try {
         Hook::listen('process_payment', $event = new EventData($params));
         $result = $event->getData('result');
     } catch (Exception $e) {
         $result = PaymentMethodAbstract::prepareErrorResponse($e);
     }
     if (isset($result[0]['error_code'])) {
         $response = $result[0];
         $statusCode = $result[1];
     } else {
         $response = fnGet($result, 0);
         $statusCode = 200;
     }
     $this->_ajaxReturn($response, $statusCode);
 }
Esempio n. 11
0
 public function request($url, $params = false, $method = 'GET', $headers = array())
 {
     $ch = curl_init();
     $this->last_error = $this->last_response = null;
     $this->last_request = compact('url', 'params', 'method', 'headers');
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HEADER, $this->response_headers);
     curl_setopt($ch, CURLOPT_TIMEOUT, $this->time_out);
     curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connect_time_out);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify_peer);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->ssl_verify_host);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     if ($this->proxy) {
         curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
     }
     if ($method == 'GET') {
         $querySeparator = strpos($url, '?') === false ? '?' : '&';
         if (is_array($params)) {
             $url .= $querySeparator . http_build_query($params);
         } else {
             if (is_string($params)) {
                 $url .= $querySeparator . $params;
             }
         }
     } else {
         curl_setopt($ch, fnGet($this->_methodMapping, $method . '/method', CURLOPT_POST), fnGet($this->_methodMapping, $method . '/value', true));
         if ($params) {
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
         }
     }
     curl_setopt($ch, CURLOPT_URL, $url);
     $this->last_response = $response = curl_exec($ch);
     if ($errNo = curl_errno($ch)) {
         $this->last_error = array('err_no' => $errNo, 'error' => $error = curl_error($ch));
     }
     $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     $this->http_info = array_merge($this->http_info, curl_getinfo($ch));
     curl_close($ch);
     if ($this->throw_errors && $this->last_error) {
         throw new Exception($this->last_error['error'], $this->last_error['err_no']);
     }
     return $response;
 }
Esempio n. 12
0
 protected function getSsoUserData($input)
 {
     try {
         $site = SsoSite::getSiteDataByReturnUrl(fnGet($input, 'notifyUrl'));
         $initToken = fnGet($input, 'initToken');
         $initTime = fnGet($input, 'initTime');
         if (!$this->checkInitToken($initTime, $initToken, $site)) {
             return ['error' => __('Invalid SSO init token')];
         }
         if (!($user = Auth::getUser())) {
             return ['error' => false, 'user_data' => ['uid' => null]];
         }
         $ssoData = ['error' => false, 'user_data' => ['uid' => $user->getId(), 'username' => $user->getUsername(), 'email' => $user->getEmail(), 'avatar' => $user->getAvatar()], 'user' => $user, 'site' => $site];
         return $ssoData;
     } catch (Exception $e) {
         Log::exception($e);
         return ['error' => __('Other error %code% - %time%', ['code' => $e->getCode(), 'time' => date(DateTime::MYSQL_DATETIME)])];
     }
 }
Esempio n. 13
0
 public function callback($data)
 {
     try {
         $this->verifyCallbackParameters($data);
         $this->verifyCallbackSign(null, $data, fnGet($data, 'sign'));
         $order = $this->getCallbackOrder(fnGet($data, 'out_trade_no'));
         $status = fnGet($data, 'trade_status');
         // Processing
         if ($status == 'WAIT_BUYER_PAY') {
             if ($order->canConfirm()) {
                 $order->confirm(__('Alipay callback status %status%', ['status' => $status]));
                 $order->save();
             }
             return Result::create(['order' => $order, 'response' => 'success']);
         }
         // Success
         if ($status == 'TRADE_FINISHED' || $status == 'TRADE_SUCCESS') {
             if ($order->canComplete()) {
                 $this->verifyCallbackAmount($order, fnGet($data, 'total_fee'));
                 $order->complete('Test Callback');
                 $order->save();
             }
             return Result::create(['order' => $order, 'response' => 'success']);
         }
         // Failure
         if ($order->canFail()) {
             $order->fail(__('Alipay callback status %status%', ['status' => $status]));
             $order->save();
         }
         return Result::create(['order' => $order, 'response' => 'success']);
     } catch (CallbackException $e) {
         return Result::create(['error' => $e, 'response' => 'FAILED']);
     } catch (Exception $e) {
         Log::exception($e);
         return Result::create(['error' => $e, 'response' => 'FAILED']);
     }
     // @codeCoverageIgnoreEnd
 }
Esempio n. 14
0
 public static function prepare($data)
 {
     /* @var Order $order */
     $order = Di::getDefault()->get(Order::class);
     // Detect required fields
     foreach ($order->requiredFieldsOnPreparation as $field) {
         if (empty($data[$field])) {
             throw new OrderException(__('Missing required field %field%', ['field' => $field]), OrderException::ERROR_CODE_BAD_PARAMETERS);
         }
     }
     // Load existing order if any
     if ($existingOrder = $order::getByTradeId($data['trade_id'], $data['client_id'])) {
         $order = $existingOrder;
         if (!$order->canPrepare()) {
             throw new OrderException(__('Order "%trade_id%" is %status%, please do not submit repeatedly', ['trade_id' => $data['trade_id'], 'status' => $order->getStatus()]), OrderException::ERROR_CODE_ORDER_PROCESSING);
         }
     }
     $order->getOrderData()->setData('request_data', $data);
     // Fire before_prepare_order_data event
     $data = Events::fire('order:before_prepare_order_data', $order, $data) ?: $data;
     // Filter protected fields
     foreach ($order->protectedFieldsOnPreparation as $field) {
         unset($data[$field]);
     }
     unset($data[static::PREFIXED_ORDER_ID_FIELD]);
     // Remove objects in $data
     foreach ($data as $k => $v) {
         // @codeCoverageIgnoreStart
         if (is_object($v)) {
             unset($data[$k]);
         }
         // @codeCoverageIgnoreEnd
     }
     // Verify order data
     $amount = $data['amount_in_currency'] = fnGet($data, 'amount') * 1;
     // TODO process currency exchange rate
     $data['currency'] = fnGet($data, 'currency', 'CNY');
     $data['amount'] = $amount;
     if ($amount <= 0) {
         throw new OrderException(__('Invalid order amount'), OrderException::ERROR_CODE_BAD_PARAMETERS);
     }
     $cashToPay = fnGet($data, 'cash_to_pay', $amount);
     if ($cashToPay < 0) {
         throw new OrderException(__('Invalid order cash to pay'), OrderException::ERROR_CODE_BAD_PARAMETERS);
     }
     $data['cash_to_pay'] = $cashToPay;
     // Set order attributes
     $keyFields = $order->getKeyFields();
     foreach ($order->toArray() as $attribute => $oldValue) {
         $newValue = fnGet($data, $attribute);
         if (isset($keyFields[$attribute]) && $oldValue && $oldValue != $newValue) {
             throw new OrderException(__('Order crucial attribute [%attribute%] changed', compact('attribute')), OrderException::ERROR_CODE_KEY_PARAMETERS_CHANGED);
         }
         $newValue === null or $order->setData($attribute, $newValue);
     }
     // Fire after_prepare_order_data event
     $data = Events::fire('order:after_prepare_order_data', $order, $data) ?: $data;
     // Generate order id
     $order->generateOrderId(fnGet($data, 'order_prefix'));
     unset($data['order_prefix']);
     $order->setOrderData($data)->updateStatus($order->getFsm()->getCurrentState(), __('Order initialized'))->refreshFsmHistory();
     return $order;
 }
Esempio n. 15
0
 public static function getParam($key, $default = null)
 {
     static::$instance or static::$instance = static::$di->getShared('view');
     return fnGet(static::$instance->_params, $key, $default, '.');
 }
Esempio n. 16
0
 public function createCallbackSign($order, $callbackData)
 {
     return fnGet($callbackData, 'sign');
 }
Esempio n. 17
0
 /**
  * @param $key          string
  * @param $defaultValue mixed
  * @return mixed
  */
 public static function get($key = null, $defaultValue = null)
 {
     return $key === null ? static::$config : fnGet(static::$config, $key, $defaultValue, '.');
 }
Esempio n. 18
0
function url($path, $queries = array(), $secure = null)
{
    if (substr($path, 0, 2) == '//' || ($prefix = substr($path, 0, 7)) == 'http://' || $prefix == 'https:/') {
        return $path;
    }
    if (PHP_SAPI == 'cli') {
        $url = C('CLI_BASE_URL');
        $secure and $url = str_replace('http://', 'https://', $url);
    } else {
        $secure === null and $secure = is_ssl();
        $protocol = $secure ? 'https://' : 'http://';
        $host = fnGet($_SERVER, 'HTTP_HOST', C('host'));
        $base = $_SERVER['SCRIPT_NAME'];
        $base = trim(C('URL_MODEL') ? dirname($base) : $base, '/');
        $base and $base .= '/';
        $url = $protocol . $host . '/' . $base;
    }
    $url .= $path;
    if ($queries && is_array($queries)) {
        $queries = http_build_query($queries);
    }
    $queries && is_string($queries) and $url .= '?' . str_replace('?', '', $queries);
    return $url;
}
Esempio n. 19
0
function url($path, $queries = [], $secure = null)
{
    if (isHttpUrl($path)) {
        return $path;
    }
    $path = trim($path, '/');
    if (Config::get('app.enable_https')) {
        Text::startsWith($path, 'admin', false) and $secure = true;
        $secure === null && null !== ($configValue = Config::get('app.secure_routes.' . $path)) and $secure = $configValue;
        // TODO Detection https via proxy
        $secure === null and $secure = Di::getDefault()['request']->getScheme() === 'https';
    } else {
        $secure = false;
    }
    $protocol = $secure ? 'https://' : 'http://';
    $host = fnGet($_SERVER, 'HTTP_HOST') ?: parse_url(Config::get('app.url'), PHP_URL_HOST);
    $base = $_SERVER['SCRIPT_NAME'];
    $base = trim(dirname($base), '/');
    $base and $base .= '/';
    $url = $protocol . $host . '/' . $base;
    $url .= $path;
    if ($queries && is_array($queries)) {
        $queries = http_build_query($queries);
    }
    $queries && is_string($queries) and $url .= '?' . str_replace('?', '', $queries);
    return $url;
}
Esempio n. 20
0
 public function verifyCallbackParameters($data, $errorCode = CallbackException::BAD_PARAMETERS)
 {
     $lackedParameters = [];
     foreach (fnGet($this->config, 'required_callback_parameters', []) as $parameter) {
         isset($data[$parameter]) or $lackedParameters[] = $parameter;
     }
     $lackedParameters and $this->throwCallbackException(__('Missing parameters: [%parameters%]', ['parameters' => implode('], [', $lackedParameters)]), $errorCode);
 }
Esempio n. 21
0
 public function testBrowserCache()
 {
     $controller = $this->getTestController();
     $pageId = 'test-browser-cache';
     $controller->response->setContent($content = 'Test browser cache');
     $controller->testSetBrowserCache($pageId);
     $cachedContent = $controller->testGetBrowserCache($pageId);
     $eTag = fnGet($cachedContent, 'etag');
     $this->assertEquals($content, fnGet($cachedContent, 'content'));
     $this->assertEquals($eTag, $controller->response->getHeaders()->get('Etag'));
     $cachedContentNonExisting = $controller->testGetBrowserCache('non-existing');
     $this->assertNull(fnGet($cachedContentNonExisting, 'content'));
     $controller2 = $this->getTestController();
     $pageId2 = 'test-browser-cache-2';
     $controller2->response->setContent($content2 = 'Test browser cache 2');
     $cachedContent2 = $controller2->testGetBrowserCache('non-existing');
     $this->assertNull(fnGet($cachedContent2, 'content'));
     $controller2->testSetBrowserCache($pageId2, $controller2::BROWSER_CACHE_ETAG);
     $eTag = $controller2->getBrowserCache($pageId2, $controller2::BROWSER_CACHE_ETAG);
     $this->assertEquals($eTag, $controller2->response->getHeaders()->get('Etag'));
     $controller2->testSetBrowserCache($pageId2, $controller2::BROWSER_CACHE_CONTENT);
     $this->assertEquals($content2, $controller2->getBrowserCache($pageId2, $controller2::BROWSER_CACHE_CONTENT));
 }
Esempio n. 22
0
 public function testFailedListener()
 {
     Queue::register($this->di);
     $queue = Queue::connection();
     $workerClass = TestQueueWorker::class;
     $data = ['test' => 'listener'];
     TestQueueWorker::reset();
     $queue->push("{$workerClass}::staticFailureWorker", $data);
     // Failure
     $listener = new Listener();
     $e = null;
     try {
         $listener->pop('', null, 0, 0, 1);
     } catch (Exception $e) {
     }
     $this->assertInstanceOf(Exception::class, $e);
     // Log failure job
     $result = $listener->pop('', null, 0, 0, 1);
     $this->assertTrue(fnGet($result, 'failed'));
 }
Esempio n. 23
0
 public function getData($key = null, $default = null)
 {
     return $key === null ? $this->data : fnGet($this->data, $key, $default);
 }
Esempio n. 24
0
 /**
  * Get service info, including pid, manager pid and port
  *
  * @param string $instance Specify instance name (e.g. "current", "old").
  *                         If not specified, return combined info of all instances.
  * @return array An array containing service info
  */
 protected function getServiceInfo($instance = null)
 {
     $file = $this->runDir . 'service-info.php';
     $info = is_file($file) ? include $file : [];
     return $instance ? fnGet($info, $instance, []) : $info;
 }
Esempio n. 25
0
 public function testReload()
 {
     $service = $this->service;
     // Should be able to start
     $serverProcess = $service->startIsolated();
     // Should return running status
     $status = $service->showStatus(null, false, $error);
     $this->assertFalse($error);
     $this->assertStringStartsWith('Service is running. PID: ' . $serverProcess->pid, $status);
     // Get current port
     $oldPort = $service->choosePort();
     // Port should be shifted
     $service->shift();
     $this->assertNotEquals($oldPort, $service->choosePort());
     /*
      * TODO The old instance should be stopped after new instance is started
      *      But I am unable to start two instances due to swoole status detection
      *      It may be implemented in the future if swoole fixed this
      */
     // Should be able to stop old instance
     $service->stop('old');
     // Should be able to start new instance
     $substituteServerProcess = $service->startIsolated();
     // Should return running status
     $status = $service->showStatus(null, false, $error);
     $this->assertFalse($error);
     $this->assertStringStartsWith('Service is running. PID: ' . $substituteServerProcess->pid, $status);
     // Should be able to stop
     $service->stop();
     // Service stopped, should be error 2 No such file or directory, or 111 Connection refused
     $service->showStatus(null, false, $error);
     $this->assertContains(fnGet($error, 'err'), [2, 111], fnGet($error, 'message'));
 }
Esempio n. 26
0
 protected function _checkPaymentParameters()
 {
     //检测参数是否输入有误
     if (!fnGet($this->input, 'developerurl')) {
         $this->err['error_msg'] = '参数错误';
         //开发商回调url不能为空
         $this->err['error_details'] = 'developerurl 为空';
         $this->_ajaxReturn($this->err, 400);
     }
     if (!fnGet($this->input, 'trade_id') || strlen($this->input['trade_id']) > 50) {
         $this->err['error_msg'] = '参数错误';
         $this->err['error_details'] = 'trade_id 为空 或者超过 50 位';
         $this->_ajaxReturn($this->err, 400);
     }
     if (fnGet($this->input, 'amount') <= 0) {
         $this->err['error_msg'] = '金额错误';
         $this->_ajaxReturn($this->err, 400);
     }
     if (!fnGet($this->input, 'product_name') || mb_strlen($this->input['product_name']) > 50) {
         $this->err['error_msg'] = '产品名称错误';
         $this->err['error_details'] = 'product_name 为空 或者超过 50 位';
         $this->_ajaxReturn($this->err, 400);
     }
     if (mb_strlen(fnGet($this->input, 'game_server_id')) > 10) {
         $this->err['error_msg'] = '参数错误';
         $this->err['error_details'] = 'game_server_id 超过 10 位';
         $this->_ajaxReturn($this->err, 400);
     }
     if (mb_strlen(fnGet($this->input, 'terminalid')) > 20) {
         $this->err['error_msg'] = '参数错误';
         //参数[terminalid]不能超过20位
         $this->err['error_details'] = 'terminalid 超过 20 位';
         $this->_ajaxReturn($this->err, 400);
     }
 }
Esempio n. 27
0
 public function getAdditionalData($key = null)
 {
     return $key === null ? $this->_additionalData : fnGet($this->_additionalData, $key);
 }
Esempio n. 28
0
 public function testSubmitConfig()
 {
     $data = ['foo' => 'baz', 'hello' => 'word'];
     $rawData = json_encode($data);
     $key = 'white_listed';
     $submittedData = $this->configTrait->submitConfig($key, $rawData);
     // foo should be kept because it is in white list
     $this->assertEquals(fnGet($submittedData, 'foo'), fnGet($data, 'foo'));
     // hello should be removed because it is not in white list
     $this->assertNotEquals(fnGet($submittedData, 'hello'), fnGet($data, 'hello'));
     $key = 'black_listed';
     $submittedData = $this->configTrait->submitConfig($key, $rawData);
     // foo should be removed because it is in black list
     $this->assertNotEquals(fnGet($submittedData, 'foo'), fnGet($data, 'foo'));
     // hello should be kept because it is not in black list
     $this->assertEquals(fnGet($submittedData, 'hello'), fnGet($data, 'hello'));
     $e = false;
     $key = 'protected';
     try {
         $this->configTrait->submitConfig($key, $rawData);
     } catch (Exception $e) {
     }
     $this->assertInstanceOf(ValidationException::class, $e);
     $e = false;
     $key = 'white_listed';
     $badData = $rawData . 'oops';
     try {
         $this->configTrait->submitConfig($key, $badData);
     } catch (Exception $e) {
     }
     $this->assertInstanceOf(ValidationException::class, $e);
 }
Esempio n. 29
0
 /**
  * Get input from request
  *
  * @param string $key
  * @param mixed  $defaultValue
  * @return mixed
  */
 protected function input($key = null, $defaultValue = null)
 {
     return is_null($key) ? $_REQUEST : fnGet($_REQUEST, $key, $defaultValue);
 }
Esempio n. 30
0
 public function getOption($key)
 {
     return fnGet($this->options, $key);
 }