/**
  * Includes the default Dependency Injector and loads the Entity.
  */
 public function onConstruct()
 {
     $di = DI::getDefault();
     $this->setDI($di);
     // initialize entity and set to class property (doing the same to the model property)
     $this->getEntity();
 }
示例#2
0
 /**
  * Get DI
  *
  * @return DI
  */
 public function getDi()
 {
     if (empty($this->di)) {
         $this->di = DI::getDefault();
     }
     return $this->di;
 }
示例#3
0
 public function testSerialization()
 {
     $router = \Phalcon\DI::getDefault()->getShared('router');
     $serialized = serialize($router);
     $unserialized = unserialize($serialized);
     $this->assertEquals($unserialized, $router);
 }
示例#4
0
 public function send()
 {
     $di = \Phalcon\DI::getDefault();
     $res = $di->get('response');
     $req = $di->get('request');
     //query string, filter, default
     if (!$req->get('suppress_response_codes', null, null)) {
         $res->setStatusCode($this->getCode(), $this->response)->sendHeaders();
     } else {
         $res->setStatusCode('200', 'OK')->sendHeaders();
     }
     $error = array('errorCode' => $this->getCode(), 'userMessage' => $this->getMessage(), 'devMessage' => $this->devMessage, 'more' => $this->additionalInfo, 'applicationCode' => $this->errorCode);
     if (!$req->get('type') || $req->get('type') == 'json' | $req->get('type') == 'option') {
         $response = new JSONResponse();
         $response->send($error, true);
         return;
     } else {
         if ($req->get('type') == 'xml') {
             $response = new XMLResponse();
             $response->send($error, true);
             return;
         } else {
             if ($req->get('type') == 'csv') {
                 $response = new CSVResponse();
                 $response->send(array($error));
                 return;
             }
         }
     }
     error_log('HTTPException: ' . $this->getFile() . ' at ' . $this->getLine());
     return true;
 }
示例#5
0
 /**
  * Get table name.
  *
  * @return string
  */
 public static function getTableName()
 {
     $reader = DI::getDefault()->get('annotations');
     $reflector = $reader->get(get_called_class());
     $annotations = $reflector->getClassAnnotations();
     return $annotations->get('Source')->getArgument(0);
 }
示例#6
0
文件: Db.php 项目: rj28/test
 /**
  * @param $param1 AdapterInterface|Closure
  * @param $param2 Closure|null
  *
  * @throws Exception
  * @return mixed
  */
 public static function transaction()
 {
     switch (func_num_args()) {
         case 1:
             $db = DI::getDefault()['db'];
             $callback = func_get_arg(0);
             break;
         case 2:
             $db = func_get_arg(0);
             $callback = func_get_arg(1);
             break;
         default:
             throw new Exception("Bad parameter count");
     }
     /** @var $db       AdapterInterface */
     /** @var $callback Closure          */
     //Assert::true($db instanceof AdapterInterface);
     Assert::true($callback instanceof Closure);
     $db->begin();
     try {
         $ret = $callback($db);
         $db->commit();
         return $ret;
     } catch (Exception $e) {
         $db->rollback();
         throw $e;
     }
 }
示例#7
0
文件: CrudTest.php 项目: szytko/core
 public function setUp()
 {
     parent::setUp();
     $config = DI::getDefault()->get('config');
     require_once $config->application->moduleDir . '/Test/forms/Fake.php';
     $this->prepareFakeObject();
 }
示例#8
0
 public function testCreateAdapterByItsClass()
 {
     $di = DI::getDefault();
     $oauth = new OAuth($di);
     $linkedin = new \Vegas\Security\OAuth\Service\Linkedin($di, $oauth->getDefaultSessionStorage());
     $this->assertInstanceOf('\\Vegas\\Security\\OAuth\\Service\\Linkedin', $linkedin);
 }
 /**
  * Constructor, calls the parse method for the query string by default.
  *
  * @param boolean $parseQueryString
  *            true Can be set to false if a controller needs to be called
  *            from a different controller, bypassing the $allowedFields parse
  * @return void
  */
 public function __construct($parseQueryString = true)
 {
     $di = \Phalcon\DI::getDefault();
     $this->setDI($di);
     // initialize entity and set to class property
     $this->getEntity();
 }
示例#10
0
文件: Subject.php 项目: nisnaker/tu
 public static function import($data)
 {
     // id字段创建唯一索引
     // db.movie.createIndex({id:1}, {unique:1});
     $di = \Phalcon\DI::getDefault();
     $di->get('mongo')->subject->batchInsert($data, ['continueOnError' => true]);
 }
示例#11
0
 /**
  * Executes the validation
  *
  * @param Validation $validator Validator object.
  * @param string     $attribute Attribute name.
  *
  * @return Group
  */
 public function validate($validator, $attribute)
 {
     $this->_currentValidator = $validator;
     $this->_currentAttribute = $attribute;
     /** @var Request $request */
     $request = DI::getDefault()->get('request');
     $isValid = true;
     if ($request->hasFiles(true)) {
         $fInfo = finfo_open(FILEINFO_MIME_TYPE);
         $types = [];
         if ($this->isSetOption('type')) {
             $types = $this->getOption('type');
             if (!is_array($types)) {
                 $types = [$types];
             }
         }
         foreach ($request->getUploadedFiles(true) as $file) {
             if ($file->getKey() != $attribute) {
                 continue;
             }
             if (!empty($types)) {
                 $mime = finfo_file($fInfo, $file->getTempName());
                 if (!in_array($mime, $types)) {
                     $isValid = false;
                     $this->_addMessage('Incorrect file type, allowed types: %s', implode(',', $types));
                 }
             }
         }
     }
     return $isValid;
 }
 public function filter($value)
 {
     return preg_replace_callback('/(phalcon(\\\\\\w+)*)(\\[\\])?/i', function ($matches) {
         $tag = \Phalcon\DI::getDefault()->get('tag');
         return $tag->linkToApi(array($matches[1], $matches[0]));
     }, $value);
 }
示例#13
0
 function __construct($key)
 {
     $di = \Phalcon\DI::getDefault();
     $this->di = $di;
     // init stripe access
     \Stripe\Stripe::setApiKey($key);
 }
示例#14
0
 public function testAuthenticateInvalidUser()
 {
     $user = $this->createTempUser();
     $auth = DI::getDefault()->get('auth');
     $this->setExpectedException('\\Vegas\\Security\\Authentication\\Exception\\InvalidCredentialException');
     $auth->authenticate($user, 'pass1234');
 }
示例#15
0
 /**
  * @param $string
  * @param array $params
  * @return string
  */
 public static function _($string, array $params = [])
 {
     if (static::$translate == null) {
         global $config;
         //Ask browser what is the best language
         $locale = DI::getDefault()->get('request')->get('lang', 'string', DI::getDefault()->get('request')->getBestLanguage());
         if (empty($config->application->langDir) || !file_exists($config->application->langDir)) {
             $config->application->langDir = __DIR__ . DIRECTORY_SEPARATOR . 'languages' . DIRECTORY_SEPARATOR;
         }
         //Check if we have a translation file for that lang
         if (!file_exists($config->application->langDir . $locale)) {
             $locale = 'en_US';
         }
         // clear cache in dev environment
         $default_domain = 'auth';
         if (defined('ENVIRONMENT') && ENVIRONMENT == 'development') {
             $default_domain = sprintf('%s.%s', $default_domain, time());
             if (file_exists($default_domain)) {
             }
         }
         //Init translate object
         static::$translate = new \Phalcon\Translate\Adapter\Gettext(['locale' => $locale, 'defaultDomain' => $default_domain, 'directory' => $config->application->langDir]);
     }
     return static::$translate->_($string, $params);
 }
示例#16
0
 /**
  * @param Phalcon\DI $di
  */
 public function __construct(DI $di = null)
 {
     if (!$di) {
         $di = DI::getDefault();
     }
     // There's only ever going to be one error page...right?
     $di->setShared('whoops.error_page_handler', function () {
         return new PrettyPageHandler();
     });
     // Retrieves info on the Phalcon environment and ships it off
     // to the PrettyPageHandler's data tables:
     // This works by adding a new handler to the stack that runs
     // before the error page, retrieving the shared page handler
     // instance, and working with it to add new data tables
     $phalcon_info_handler = function () use($di) {
         try {
             $request = $di['request'];
         } catch (Exception $e) {
             // This error occurred too early in the application's life
             // and the request instance is not yet available.
             return;
         }
         // Request info:
         $di['whoops.error_page_handler']->addDataTable('Phalcon Application (Request)', array('URI' => $request->getScheme() . '://' . $request->getServer('HTTP_HOST') . $request->getServer('REQUEST_URI'), 'Request URI' => $request->getServer('REQUEST_URI'), 'Path Info' => $request->getServer('PATH_INFO'), 'Query String' => $request->getServer('QUERY_STRING') ?: '<none>', 'HTTP Method' => $request->getMethod(), 'Script Name' => $request->getServer('SCRIPT_NAME'), 'Scheme' => $request->getScheme(), 'Port' => $request->getServer('SERVER_PORT'), 'Host' => $request->getServerName()));
     };
     $di->setShared('whoops', function () use($di, $phalcon_info_handler) {
         $run = new Run();
         $run->pushHandler($di['whoops.error_page_handler']);
         $run->pushHandler($phalcon_info_handler);
         return $run;
     });
     $di['whoops']->register();
 }
示例#17
0
 /**
  * Create object.
  *
  * @param DiInterface|DIBehaviour $di Dependency injection container.
  */
 public function __construct($di = null)
 {
     if ($di == null) {
         $di = DI::getDefault();
     }
     $this->setDI($di);
 }
示例#18
0
 /**
  * Log error.
  *
  * @param string $type Type name.
  * @param string $message Message text.
  * @param string $file File path.
  * @param string $line Line info.
  * @param string|null $trace Trace info.
  * @return string
  * @throws \Exception
  */
 public static function logError($type, $message, $file, $line, $trace = null)
 {
     $id = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 7);
     $di = DI::getDefault();
     $template = "<%s> [%s] %s (File: %s Line: [%s])";
     $logMessage = sprintf($template, $id, $type, $message, $file, $line);
     if ($di->has('profiler')) {
         $profiler = $di->get('profiler');
         if ($profiler) {
             $profiler->addError($logMessage, $trace);
         }
     }
     if ($trace) {
         $logMessage .= $trace . PHP_EOL;
     } else {
         $logMessage .= PHP_EOL;
     }
     if ($di->has('logger')) {
         $logger = $di->get('logger');
         if ($logger) {
             $logger->error($logMessage);
         } else {
             throw new \Exception($logMessage);
         }
     } else {
         throw new \Exception($logMessage);
     }
     return $id;
 }
示例#19
0
 /**
  * Returns the translation related to the given key
  *
  * @param string $index
  * @param array $placeholders
  * @return string
  */
 public function query($index, $placeholders = null)
 {
     if (!empty($index) and !array_key_exists($index, $this->_translate)) {
         $transdir = \Phalcon\DI::getDefault()->getConfig()->dirs->translations;
         $new = [$index => $index . '*'];
         $this->_translate = $new + $this->_translate;
         $d = dir($transdir);
         while (($file = $d->read()) !== false) {
             if (!preg_match('/^[a-z]{2}\\.php$/', $file)) {
                 continue;
             }
             $messages = [];
             $dict = $transdir . DIRECTORY_SEPARATOR . $file;
             require $dict;
             // Check if $index exists in given dictionary:
             if (!array_key_exists($index, $messages)) {
                 $messages = $new + $messages;
                 $content = sprintf("<?php\n\n// app/config/translations/%s\n\n\$messages = %s;", $file, var_export($messages, true));
                 file_put_contents($dict, $content);
             }
         }
         $d->close();
     }
     return parent::query($index, $placeholders);
 }
示例#20
0
 public function __construct()
 {
     parent::__construct();
     $di = \Phalcon\DI::getDefault();
     $di->setShared('rediscom', function () use($di) {
         $redis = new Redis();
         $redis->connect($di['config']->txyredispro->host, intval($di['config']->txyredispro->port), 0.5);
         //$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
         if (APP_ENV == 'product') {
             $redis->auth($di['config']->txyredispro->instanceid . ":" . $di['config']->txyredispro->auth);
         }
         return $redis;
     });
     //读配置
     $di->setShared('rocksdbcomread', function () use($di) {
         $redis = new Redis();
         $redis->connect($di['config']->rocksdbcomread->host, intval($di['config']->rocksdbcomread->port), 0.5);
         //$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
         return $redis;
     });
     //写配置
     $di->setShared('rocksdbcomwrite', function () use($di) {
         $redis = new Redis();
         $redis->pconnect($di['config']->rocksdbcomwrite->host, intval($di['config']->rocksdbcomwrite->port), 0.5);
         //$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
         return $redis;
     });
 }
示例#21
0
 public static function tearDownAfterClass()
 {
     $di = DI::getDefault();
     $di->get('db')->execute('DROP TABLE IF EXISTS fake_table ');
     $di->get('mongo')->selectCollection('fake_with_dao')->remove([]);
     $di->get('mongo')->selectCollection('fake_without_dao')->remove([]);
 }
示例#22
0
 /**
  * 得到ID数组
  *
  * @access public
  * @param obj $obj
  * @param array $ids  id集合
  * @return array
  * @author 刘建辉
  * @修改日期 2015-08-03 15:56:28
  */
 public function get($getName, $id)
 {
     $diObj = \Phalcon\DI::getDefault()->get($getName);
     $data = $diObj->get($id);
     $newdataArr = array($id => gzuncompress($data));
     return $newdataArr;
 }
示例#23
0
文件: Mongo.php 项目: vegas-cmf/acl
 /**
  * @param array $options
  * @throws \Exception
  */
 public function __construct($options = array())
 {
     if (empty($options)) {
         $options = array('db' => DI::getDefault()->get('mongo'), 'roles' => 'vegas_acl_roles', 'resources' => 'vegas_acl_resources', 'resourcesAccesses' => 'vegas_acl_resources_accesses', 'accessList' => 'vegas_acl_access_list');
     }
     if (!is_array($options)) {
         throw new Exception("Acl options must be an array");
     }
     if (!isset($options['db'])) {
         throw new Exception("Parameter 'db' is required");
     }
     if (!isset($options['roles'])) {
         throw new Exception("Parameter 'roles' is required");
     }
     if (!isset($options['resources'])) {
         throw new Exception("Parameter 'resources' is required");
     }
     if (!isset($options['resourcesAccesses'])) {
         throw new Exception("Parameter 'resourcesAccesses' is required");
     }
     if (!isset($options['accessList'])) {
         throw new Exception("Parameter 'accessList' is required");
     }
     $this->options = $options;
     $this->_defaultAccess = Acl::DENY;
 }
示例#24
0
 /**
  * Init
  */
 protected function setUp()
 {
     $this->getTester()->setDi(DI::getDefault());
     $this->getTester()->setTestableConfig($this->getTestableConfig());
     parent::setUp();
     $this->testable = new ModuleTestable();
 }
 /**
  * @param DI $di
  */
 public function __construct(DI $di = null)
 {
     if (!class_exists('\\Whoops\\Run')) {
         return;
     }
     if (!$di) {
         $di = DI::getDefault();
     }
     // There's only ever going to be one error page...right?
     $di->setShared('whoops.pretty_page_handler', function () use($di) {
         return (new DebugbarHandler())->setDi($di);
     });
     // There's only ever going to be one error page...right?
     $di->setShared('whoops.json_response_handler', function () {
         $jsonHandler = new JsonResponseHandler();
         $jsonHandler->onlyForAjaxRequests(true);
         return $jsonHandler;
     });
     $di->setShared('whoops', function () use($di) {
         $run = new Run();
         $run->silenceErrorsInPaths(array('/phalcon-debugbar/'), E_ALL);
         $run->pushHandler($di['whoops.pretty_page_handler']);
         $run->pushHandler($di['whoops.json_response_handler']);
         return $run;
     });
     $di['whoops']->register();
 }
示例#26
0
文件: Regex.php 项目: biggtfish/cms
 /**
  * Create regex validator.
  *
  * @param array $params Validator parameters.
  */
 public function __construct($params = [])
 {
     if (isset($params['message'])) {
         $params['message'] = DI::getDefault()->get('i18n')->_($params['message']);
     }
     parent::__construct($params);
 }
示例#27
0
 public function setAdditionalOptions()
 {
     $format = new \Vegas\Forms\Element\Text('format');
     $format->setLabel("Format");
     $this->additionalOptions[] = $format;
     DI::getDefault()->get('assets')->addJs('assets/js/lib/vegas/formbuilder/datepicker.js');
 }
示例#28
0
 /**
  * Check Recaptcha
  *
  * @param $privateKey
  * @param $remoteIP
  * @param $response
  * @return array|bool
  */
 public static function check($remoteIP, $response)
 {
     $privateKey = \Phalcon\DI::getDefault()->getShared('config')->recaptcha->private or die(self::RECAPTCHA_ERROR_KEY);
     $result = array();
     $result['success'] = FALSE;
     $result['error-codes'] = FALSE;
     $result = json_decode(file_get_contents(self::RECAPTCHA_VERIFY_SERVER . "?secret={$privateKey}&response=" . $response . "&remoteip=" . $remoteIP), true);
     if ($result['success'] == FALSE) {
         // errors
         if (is_array($result['error-codes'])) {
             if ($result['error-codes'][0] == 'missing-input-response') {
                 return array('success' => FALSE, 'error' => __('Please verify you are human'));
             } else {
                 if ($result['error-codes'][0] == 'invalid-input-response') {
                     return array('success' => FALSE, 'error' => __('You have failed the human verification test!'));
                 }
             }
         } else {
             return array('success' => FALSE, 'error' => __('There was an unknown error!'));
         }
     } else {
         return array('success' => TRUE, 'error' => FALSE);
     }
     return FALSE;
 }
示例#29
0
 public function send()
 {
     $di = \Phalcon\DI::getDefault();
     $res = $di->get('response');
     $req = $di->get('request');
     //query string, filter, default
     if (!$req->get('suppress_response_codes', null, null)) {
         $res->setStatusCode($this->getCode(), $this->response)->sendHeaders();
     } else {
         $res->setStatusCode('200', 'OK')->sendHeaders();
     }
     $error = array('errorCode' => $this->getCode(), 'messages' => $this->messages);
     if (!$req->get('type') || $req->get('type') == 'json') {
         $response = new \Base\Framework\Responses\JSONResponse();
         $response->send($error, true);
         return;
     } else {
         if ($req->get('type') == 'csv') {
             $response = new \Base\Framework\Responses\CSVResponse();
             $response->send(array($error));
             return;
         }
     }
     error_log('HTTPException: ' . $this->getFile() . ' at ' . $this->getLine());
     return true;
 }
示例#30
0
 public function mapAction($idVisit)
 {
     $visit = Visit::findFirst(array("conditions" => "idVisit = ?1", "bind" => array(1 => $idVisit)));
     if (!$visit) {
         $this->flashSession->error("Ocurrio un error procesando su solicitud, por favor intentelo nuevamente.");
         return $this->response->redirect('index');
     }
     $user = User::findFirst(array("conditions" => "idUser = ?1 AND idAccount = ?2", "bind" => array(1 => $visit->idUser, 2 => $this->user->idAccount)));
     if (!$user) {
         $this->flashSession->error("Ocurrio un error procesando su solicitud, por favor intentelo nuevamente.");
         return $this->response->redirect('visit/index');
     }
     try {
         $sql_rows = "SELECT v.idVisit AS idUser, v.start AS date, u.name AS name, u.lastName AS lastname, vt.name AS visit, c.name AS client, v.battery AS battery, v.latitude AS latitude, v.longitude AS longitude, v.location AS location " . "FROM Visit AS v " . " JOIN User AS u ON (u.idUser = v.idUser) " . " JOIN Visittype AS vt ON (vt.idVisittype = v.idVisittype) " . " JOIN Client AS c ON (c.idClient = v.idClient) " . " WHERE v.idVisit = {$idVisit}";
         //            $this->logger->log($sql_rows);
         $modelsManager = \Phalcon\DI::getDefault()->get('modelsManager');
         $rows = $modelsManager->executeQuery($sql_rows);
         $this->view->setVar('visit', $rows->getFirst());
         $this->view->setVar('user', $user);
     } catch (Exception $e) {
         $this->flashSession->error($e->getMessage());
         $this->trace("fail", $e->getMessage());
         return $this->response->redirect('visit/index');
     }
 }