Наследование: implements Phalcon\DiInterface, implements Phalcon\Events\EventsAwareInterface
Пример #1
1
 public function addComment($data)
 {
     /** @var myModel $this */
     $comment = new Comments();
     $comment->content = $data['content'];
     $comment->commentable_id = $this->id;
     $comment->commentable_type = get_class($this);
     //        $comment->user_id = $this->getDI()->getShared('session')->get('auth')['id'];//获得当前登录对象的id
     $user = \Phalcon\Di::getDefault()->get('auth');
     $comment->user_id = $user->id;
     //获得当前登录对象的id
     //        dd($comment);
     $comment->save();
     /** @var myModel $this */
     if (method_exists($this, 'increaseCount')) {
         $this->increaseCount('commentCount');
     } else {
         $this->save();
         //更新时间
     }
     if (is_a($this, 'Tags')) {
         $meta = $this->getTagmetaOrNew();
         $meta->save();
     }
     return $this;
 }
Пример #2
0
 public static function register(Di $di)
 {
     static::$di = $di;
     ini_set('session.use_cookies', 0);
     ini_set('session.cache_limiter', '');
     $di->remove('session');
     static::$session = null;
     $di->setShared('session', function () {
         $default = Config::get('session.default');
         $config = Config::get('session.drivers.' . $default);
         $class = $config['adapter'];
         $options = $config['options'];
         $options += Config::get('session.options');
         $options['cookies'] += Config::get('cookies');
         session_name($options['cookies']['name']);
         strpos($class, '\\') === false and $class = 'Phwoolcon\\Session\\Adapter\\' . $class;
         $session = new $class($options);
         // @codeCoverageIgnoreStart
         if (!$session instanceof AdapterInterface) {
             throw new SessionException('Session class should implement ' . AdapterInterface::class);
         }
         // @codeCoverageIgnoreEnd
         return $session;
     });
 }
Пример #3
0
 /**
  * Fix over clever di service resolver in phalcon 2.1.x:
  * let definition = \Closure::bind(definition, dependencyInjector)
  * which leads to php warning "Cannot bind an instance to a static closure"
  *
  * @param Di $di
  * @codeCoverageIgnore
  */
 public static function register(Di $di)
 {
     if ($_SERVER['PHWOOLCON_PHALCON_VERSION'] > '2010000') {
         $di->setInternalEventsManager($di->getShared('eventsManager'));
         Events::attach('di:beforeServiceResolve', function (Event $event) {
             /* @var Di $di */
             $di = $event->getSource();
             $data = $event->getData();
             $name = $data['name'];
             $parameters = $data['parameters'];
             if (!isset($di->_services[$name])) {
                 return false;
             }
             /* @var Di\Service $service */
             $service = $di->_services[$name];
             if (!$service->isShared()) {
                 return false;
             }
             if (!($definition = $service->getDefinition()) instanceof Closure) {
                 return false;
             }
             return $parameters ? call_user_func_array($definition, $parameters) : call_user_func($definition);
         });
     }
 }
Пример #4
0
 public static function register(Di $di)
 {
     static::$di = $di;
     static::$config = Config::get('auth');
     $di->setShared('auth', function () {
         $di = static::$di;
         $config = static::$config;
         $class = $config['adapter'];
         $options = $config['options'];
         strpos($class, '\\') === false and $class = 'Phwoolcon\\Auth\\Adapter\\' . $class;
         if ($di->has($class)) {
             $class = $di->getRaw($class);
         }
         if (!class_exists($class)) {
             throw new Exception('Admin auth adapter class should implement ' . AdapterInterface::class);
         }
         /* @var Security $hasher */
         $hasher = static::$di->getShared('security');
         $hasher->setDefaultHash($options['security']['default_hash']);
         $hasher->setWorkFactor($options['security']['work_factor']);
         $adapter = new $class($options, $hasher, $di);
         if (!$adapter instanceof AdapterInterface) {
             throw new Exception('Auth adapter class should implement ' . AdapterInterface::class);
         }
         return $adapter;
     });
     static::addPhwoolconJsOptions();
 }
Пример #5
0
 public static function injectTo(Di $di)
 {
     /** @var Dispatcher $dispatcher */
     $dispatcher = $di->getShared('dispatcher');
     $dispatcher->getEventsManager()->attach('dispatch:beforeException', function (Event $event, Dispatcher $dispatcher, \Exception $e) {
         /** @var \Phalcon\Logger\AdapterInterface $logger */
         $logger = $dispatcher->getDI()->get('logger');
         $logger->error($e->getMessage());
         if ($dispatcher instanceof Mvc\Dispatcher) {
             if ($e instanceof Mvc\Dispatcher\Exception) {
                 $action = 'notFound';
             } else {
                 $action = 'fatal';
                 if ($dispatcher->getDI()->has('response')) {
                     /** @var \Phalcon\Http\Response $response */
                     $response = $dispatcher->getDI()->get('response');
                     $response->setStatusCode(500, "Internal Server Error");
                 }
             }
             $dispatcher->setNamespaceName($dispatcher->getDefaultNamespace());
             $dispatcher->forward(['controller' => 'error', 'action' => $action]);
         }
         return false;
     });
 }
Пример #6
0
    public static function register(Di $di)
    {
        $environment = isset($_SERVER['PHWOOLCON_ENV']) ? $_SERVER['PHWOOLCON_ENV'] : 'production';
        // @codeCoverageIgnoreStart
        if (is_file($cacheFile = storagePath('cache/config-' . $environment . '.php'))) {
            static::$config = (include $cacheFile);
            Config::get('app.cache_config') or static::clearCache();
            return;
        }
        // @codeCoverageIgnoreEnd
        $defaultFiles = glob($_SERVER['PHWOOLCON_CONFIG_PATH'] . '/*.php');
        $environmentFiles = glob($_SERVER['PHWOOLCON_CONFIG_PATH'] . '/' . $environment . '/*.php');
        $config = new PhalconConfig(static::loadFiles($defaultFiles));
        $environmentSettings = static::loadFiles($environmentFiles);
        $environmentSettings['environment'] = $environment;
        $environmentConfig = new PhalconConfig($environmentSettings);
        $config->merge($environmentConfig);
        $di->remove('config');
        $di->setShared('config', $config);
        static::$config = $config->toArray();
        Config::get('database.default') and static::loadDb($config);
        // @codeCoverageIgnoreStart
        if (Config::get('app.cache_config')) {
            is_dir($cacheDir = dirname($cacheFile)) or mkdir($cacheDir, 0777, true);
            fileSaveArray($cacheFile, static::$config, function ($content) {
                $replacement = <<<'EOF'
$_SERVER['PHWOOLCON_ROOT_PATH'] . '
EOF;
                return str_replace("'{$_SERVER['PHWOOLCON_ROOT_PATH']}", $replacement, $content);
            });
        }
        // @codeCoverageIgnoreEnd
    }
Пример #7
0
 /**
  * @expectedException           \Phalcon\Mvc\Model\Exception
  * @expectedExceptionMessage    Field name must be a string
  */
 public function testValidateIncorrectFieldType()
 {
     $di = new Di();
     $di->set('modelsManager', new Manager());
     require_once __DIR__ . '/resources/TestCardNumberIncorrectField.php';
     $obj = new \TestCardNumberIncorrectField();
     $obj->validation();
 }
Пример #8
0
 /**
  * Setup viewCache service and DI
  * @return Di
  */
 protected function getDi()
 {
     $di = new Di();
     $di->set('viewCache', function () {
         return new File(new Output(['lifetime' => 2]), ['cacheDir' => PATH_CACHE]);
     });
     return $di;
 }
Пример #9
0
 /**
  * @param array|Payload $payload
  * @return Payload
  * @throws GeneralException
  */
 public static function run($payload)
 {
     static::$instance === null and static::$instance = static::$di->getShared('payment');
     $payload instanceof Payload or $payload = Payload::create($payload);
     $paymentMethod = static::$instance->getPaymentMethod($payload->getGateway(), $payload->getMethod());
     $payload->setResult($paymentMethod->process($payload));
     return $payload;
 }
Пример #10
0
 /**
  * Return flash instance
  */
 protected function getFlash()
 {
     $flash = new Session($this->classes);
     $di = new Di();
     $di->setShared('session', new PhalconMemorySession());
     $di->setShared('escaper', new Escaper());
     $flash->setDI($di);
     return $flash;
 }
Пример #11
0
 public function testAvailableUniquenessWithDefaultDI()
 {
     $di = new Di();
     $di->set('db', $this->getDbStub());
     $uniquenessOptions = ['table' => 'users', 'column' => 'login'];
     $uniqueness = new Uniqueness($uniquenessOptions);
     $this->validation->add('login', $uniqueness);
     $messages = $this->validation->validate(['login' => 'login_free']);
     $this->assertCount(0, $messages);
 }
Пример #12
0
 /**
  * Initializes the request object and returns it
  *
  * @author Nikolaos Dimopoulos <*****@*****.**>
  * @since  2014-10-05
  *
  * @return Request
  */
 protected function getRequestObject()
 {
     Di::reset();
     $di = new Di();
     $di->set('filter', function () {
         return new Filter();
     });
     $request = new Request();
     $request->setDI($di);
     return $request;
 }
Пример #13
0
 public static function injectTo(Di $di)
 {
     /** @var Dispatcher $dispatcher */
     $dispatcher = $di->getShared('dispatcher');
     $dispatcher->getEventsManager()->attach('dispatch:beforeException', function (Event $event, Dispatcher $dispatcher, \Throwable $e) {
         if ($dispatcher instanceof Mvc\Dispatcher) {
             $dispatcher->setNamespaceName($dispatcher->getDefaultNamespace());
             $dispatcher->forward(['controller' => 'error', 'action' => 'index', 'params' => ['exception' => $e]]);
             return false;
         }
     });
 }
Пример #14
0
 public static function injectTo(Di $di)
 {
     $di->setShared('logger', function () use($di) {
         $logger = new Multiple();
         $config = $di->get('config')['loggers'];
         foreach ($config as $logConfig) {
             $adapter = $logConfig['adapter'];
             $options = isset($logConfig['options']) ? $logConfig['options'] : null;
             $logger->push(new $adapter($logConfig['name'], $options));
         }
         return $logger;
     });
 }
Пример #15
0
 public static function register(Di $di)
 {
     static::$di = $di;
     $di->remove('counter');
     static::$adapter = null;
     $di->setShared('counter', function () {
         $default = Config::get('counter.default');
         $config = Config::get('counter.drivers.' . $default);
         $class = $config['adapter'];
         $options = $config['options'];
         strpos($class, '\\') === false and $class = 'Phwoolcon\\Util\\Counter\\' . $class;
         return new $class($options);
     });
 }
Пример #16
0
    public function run()
    {
        $log = new Stream('php://stdout');
        /** @var Config $config */
        $config = Di::getDefault()->getShared('config');
        $expireDate = new DateTime('now', new DateTimeZone('UTC'));
        $expireDate->modify('+1 month');
        $baseUrl = rtrim($config->get('site')->url, '/');
        $content = <<<EOL
User-agent: *
Allow: /
Sitemap: {$baseUrl}/sitemap.xml
EOL;
        $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
        $filesystem = new Filesystem($adapter);
        if ($filesystem->has('robots.txt')) {
            $result = $filesystem->update('robots.txt', $content);
        } else {
            $result = $filesystem->write('robots.txt', $content);
        }
        if ($result) {
            $log->info('The robots.txt was successfully updated');
        } else {
            $log->error('Failed to update the robots.txt file');
        }
    }
Пример #17
0
 public static function run()
 {
     $di = \Phalcon\Di::getDefault();
     $em = $di->get('em');
     // Clear out any non-daily statistics.
     $em->createQuery('DELETE FROM Entity\\Analytics a WHERE a.type != :type')->setParameter('type', 'day')->execute();
     // Pull statistics in from influx.
     $influx = $di->get('influx');
     $daily_stats = $influx->setDatabase('pvlive_stations')->query('SELECT * FROM /1d.*/ WHERE time > now() - 14d', 's');
     $new_records = array();
     $earliest_timestamp = time();
     foreach ($daily_stats as $stat_series => $stat_rows) {
         $series_split = explode('.', $stat_series);
         $station_id = $series_split[1] == 'all' ? NULL : $series_split[2];
         foreach ($stat_rows as $stat_row) {
             if ($stat_row['time'] < $earliest_timestamp) {
                 $earliest_timestamp = $stat_row['time'];
             }
             $new_records[] = array('station_id' => $station_id, 'type' => 'day', 'timestamp' => $stat_row['time'], 'number_min' => (int) $stat_row['min'], 'number_max' => (int) $stat_row['max'], 'number_avg' => round($stat_row['value']));
         }
     }
     $em->createQuery('DELETE FROM Entity\\Analytics a WHERE a.timestamp >= :earliest')->setParameter('earliest', $earliest_timestamp)->execute();
     foreach ($new_records as $new_record) {
         $row = new \Entity\Analytics();
         $row->fromArray($new_record);
         $em->persist($row);
     }
     $em->flush();
 }
Пример #18
0
 public function __get($propertyName)
 {
     $dependencyInjector = null;
     $service = null;
     $persistent = null;
     $dependencyInjector = $this->_dependencyInjector;
     if (!$dependencyInjector) {
         $dependencyInjector = Di::getDefault();
     }
     if (!$dependencyInjector) {
         throw new Exception("A dependency injection object is required to access the application services");
     }
     /**
      * Fallback to the PHP userland if the cache is not available
      */
     if ($dependencyInjector->has($propertyName)) {
         $service = $dependencyInjector->getShared($propertyName);
         $this->{$propertyName} = $service;
         return $service;
     }
     if ($propertyName == "di") {
         $this->{"di"} = $dependencyInjector;
         return $dependencyInjector;
     }
     /**
      * A notice is shown if the property is not defined and isn't a valid service
      */
     trigger_error("Access to undefined property " . $propertyName);
     return null;
 }
Пример #19
0
 public function isVotedBy(Users $user = null)
 {
     if (null == $user) {
         $user = \Phalcon\Di::getDefault()->get('auth');
     }
     return Vote::query()->where('voteable_type = :type:', ['type' => get_class($this)])->andWhere('voteable_id = :id:', ['id' => $this->id])->andWhere('user_id = :user:'******'user' => $user->id])->execute()->count() > 0;
 }
Пример #20
0
 /**
  * Opens a connection to the database, using dependency injection.
  * @see \Phalcon\Queue\Db::diServiceKey
  * @return bool
  */
 public function connect()
 {
     if (!$this->connection) {
         $this->connection = Di::getDefault()->get($this->diServiceKey);
     }
     return true;
 }
Пример #21
0
 /**
  * Class constructor.
  *
  * @param  array $options
  * @param  DbConnection  $db
  * @throws ValidationException
  */
 public function __construct(array $options = [], DbConnection $db = null)
 {
     parent::__construct($options);
     if (!$db) {
         // try to get db instance from default Dependency Injection
         $di = Di::getDefault();
         if ($di instanceof DiInterface && $di->has('db')) {
             $db = $di->get('db');
         }
     }
     if (!$db instanceof DbConnection) {
         throw new ValidationException('Validator Uniqueness require connection to database');
     }
     if (!$this->hasOption('table')) {
         throw new ValidationException('Validator require table option to be set');
     }
     if (!$this->hasOption('column')) {
         throw new ValidationException('Validator require column option to be set');
     }
     if ($this->hasOption('exclude')) {
         $exclude = $this->getOption('exclude');
         if (!isset($exclude['column']) || empty($exclude['column'])) {
             throw new ValidationException('Validator with "exclude" option require column option to be set');
         }
         if (!isset($exclude['value']) || empty($exclude['value'])) {
             throw new ValidationException('Validator with "exclude" option require value option to be set');
         }
     }
     $this->db = $db;
 }
Пример #22
0
 public function sqlite(UnitTester $I)
 {
     $I->wantToTest("Model validation by using SQLite as RDBMS");
     /** @var \Phalcon\Di\FactoryDefault $di */
     $di = Di::getDefault();
     $connection = $di->getShared('db');
     $di->remove('db');
     $di->setShared('db', function () {
         $connection = new Sqlite(['dbname' => TEST_DB_SQLITE_NAME]);
         /** @var \PDO $pdo */
         $pdo = $connection->getInternalHandler();
         $pdo->sqliteCreateFunction('now', function () {
             return date('Y-m-d H:i:s');
         });
         return $connection;
     });
     Di::setDefault($di);
     $this->success($I);
     $this->presenceOf($I);
     $this->email($I);
     $this->emailWithDot($I);
     $this->exclusionIn($I);
     $this->inclusionIn($I);
     $this->uniqueness1($I);
     $this->uniqueness2($I);
     $this->regex($I);
     $this->tooLong($I);
     $this->tooShort($I);
     $di->remove('db');
     $di->setShared('db', $connection);
 }
Пример #23
0
 /**
  * 根据学校id归类获取信息
  *
  * @param int $school_id
  *
  * @return mixed
  * @author Hunter.<*****@*****.**>
  */
 public function getStatisticsForSchoolAndGrade($school_id = 0)
 {
     $page = new Page();
     $page_table = $page->getSource();
     $classes = new Classes();
     $classes_table = $classes->getSource();
     $eva_task_log = new EvaTaskLog();
     $eva_task_log_table = $eva_task_log->getSource();
     $sql_query = "select c.grade_id,count(DISTINCT p.id) as countP, 'reading' as type from {$page_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\nwhere is_finished=0\ngroup by c.grade_id\n\nunion all\n\nselect c.grade_id,count(DISTINCT p.id) as countP, 'reading_finished' as type from {$page_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\nwhere is_finished=1\ngroup by c.grade_id\n\nunion all\n\nselect c.grade_id,count(DISTINCT p.id) as countP, 'eva_task' as type from {$eva_task_log_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\ngroup by c.grade_id";
     try {
         if (DEBUG) {
             $logger = Di::getDefault()->getLogger();
             $logger->log($sql_query, \Phalcon\Logger::DEBUG);
         }
         $stmt = $this->di->getDefault()->get('db')->prepare($sql_query);
         $stmt->bindParam(':school_id', $school_id, \PDO::PARAM_INT);
         $stmt->execute();
         $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         return $result;
     } catch (\PDOException $e) {
         if (DEBUG) {
             die($e->getMessage());
         } else {
             $this->di->get('logger_error')->log('PDOException: ' . $e->getMessage(), \Phalcon\Logger::ERROR);
             $this->di->get('dispatcher')->forward(['module' => 'home', 'controller' => 'error', 'action' => 'show_sql_error']);
         }
     }
 }
Пример #24
0
 /**
  * @return Client
  */
 public function getConnection()
 {
     if (static::$connection === null) {
         static::$connection = Di::getDefault()->getShared('Neo4jClient');
     }
     return static::$connection;
 }
Пример #25
0
 public static function getDbName()
 {
     if (!isset(self::$_db)) {
         self::$_db = Di::getDefault()->get('config')->mongodb->database;
     }
     return self::$_db;
 }
Пример #26
0
 public function modulesClosure(IntegrationTester $I)
 {
     $I->wantTo('handle request and get content by using single modules strategy (closure)');
     Di::reset();
     $_GET['_url'] = '/login';
     $di = new FactoryDefault();
     $di->set('router', function () {
         $router = new Router(false);
         $router->add('/index', ['controller' => 'index', 'module' => 'frontend', 'namespace' => 'Phalcon\\Test\\Modules\\Frontend\\Controllers']);
         $router->add('/login', ['controller' => 'login', 'module' => 'backend', 'namespace' => 'Phalcon\\Test\\Modules\\Backend\\Controllers']);
         return $router;
     });
     $application = new Application();
     $view = new View();
     $application->registerModules(['frontend' => function ($di) use($view) {
         /** @var \Phalcon\DiInterface $di */
         $di->set('view', function () use($view) {
             $view->setViewsDir(PATH_DATA . 'modules/frontend/views/');
             return $view;
         });
     }, 'backend' => function ($di) use($view) {
         /** @var \Phalcon\DiInterface $di */
         $di->set('view', function () use($view) {
             $view->setViewsDir(PATH_DATA . 'modules/backend/views/');
             return $view;
         });
     }]);
     $application->setDI($di);
     $I->assertEquals('<html>here</html>' . PHP_EOL, $application->handle()->getContent());
 }
Пример #27
0
 /**
  * 跟find()类似,包含总数、页数、上一页、下一页等信息
  *
  * @param $parameters
  * @param int $limit
  * @param int $page
  * @return mixed
  */
 public static function list($parameters = null, $page = 1, $limit = 20)
 {
     // static function.
     $di = Di::getDefault();
     //
     if (!is_array($parameters)) {
         $params[] = $parameters;
     } else {
         $params = $parameters;
     }
     $manager = $di->getShared('modelsManager');
     $builder = $manager->createBuilder($params);
     $builder->from(get_called_class());
     if (isset($params['limit'])) {
         $limit = $params['limit'];
     }
     $params = ["builder" => $builder, "limit" => $limit, "page" => $page];
     $paginator = $di->get("Phalcon\\Paginator\\Adapter\\QueryBuilder", [$params]);
     $data = $paginator->getPaginate();
     $items = [];
     foreach ($data->items as $item) {
         $items[] = $item->toArray();
     }
     $data = (array) $data;
     $data['items'] = $items;
     return $data;
 }
Пример #28
0
 /**
  * executed after each test
  */
 protected function _after()
 {
     if ($this->previousDependencyInjector instanceof DiInterface) {
         Di::setDefault($this->previousDependencyInjector);
     } else {
         Di::reset();
     }
 }
Пример #29
0
 public function getWatchList()
 {
     if (null == $this->watchList) {
         $user = \Phalcon\Di::getDefault()->get('auth');
         $this->watchList = Watchlist::findOrCreateNew($this, $user);
     }
     return $this->watchList;
 }
 /**
  * construct with supplied standard array
  * break list down into smaller properites
  *
  * @param array $errorList
  */
 public function __construct($errorList)
 {
     $di = Di::getDefault();
     // pull from messageBag if no explicit devMessage is provided
     $this->dev = isset($errorList['dev']) ? $errorList['dev'] : $di->get('messageBag')->getString();
     $this->code = isset($errorList['code']) ? $errorList['code'] : null;
     $this->more = isset($errorList['more']) ? $errorList['more'] : null;
 }