public function register()
 {
     $configPath = $this->configPath;
     $this->di->set('config.debugbar', function () use($configPath) {
         $base = new Php(__DIR__ . '/config/debugbar.php');
         $base['collectors']['phpinfo'] = true;
         $base['collectors']['time'] = true;
         $base['collectors']['messages'] = true;
         if (is_string($configPath) && is_file($configPath)) {
             $config = new Php($configPath);
             $base->merge($config);
         } elseif (is_object($configPath) && $configPath instanceof Php) {
             $base->merge($configPath);
         } else {
         }
         return $base;
     }, true);
     $this->di->set('debugbar', function () {
         $di = Version::getId() > 2010000 ? $this : $this->di;
         $debugbar = new PhalconDebugbar($di);
         $debugbar->setHttpDriver(new PhalconHttpDriver());
         return $debugbar;
     });
     $this->setRoute();
     return $this;
 }
 /**
  * @param RelationInterface
  * @param null|callable $constraints
  * @param Loader|EagerLoad $parent
  */
 public function __construct(Relation $relation, callable $constraints = NULL, $parent)
 {
     if (static::$isPhalcon2 === NULL) {
         static::$isPhalcon2 = version_compare(\Phalcon\Version::get(), '2.0.0') >= 0;
     }
     $this->relation = $relation;
     $this->constraints = $constraints;
     $this->parent = $parent;
 }
Example #3
0
 /**
  * @param RelationInterface
  * @param null|callable $constraints
  * @param Loader|EagerLoad $parent
  */
 public function __construct(Relation $relation, $constraints, $parent)
 {
     if (static::$isPhalcon2 === null) {
         static::$isPhalcon2 = version_compare(\Phalcon\Version::get(), '2.0.0') >= 0;
     }
     $this->relation = $relation;
     $this->constraints = is_callable($constraints) ? $constraints : null;
     $this->parent = $parent;
 }
Example #4
0
 public function log($type, $message = NULL, array $context = NULL)
 {
     if (Version::getId() < '2000000') {
         $this->logInternal($type, $message, microtime(true), $context);
     } else {
         $this->logInternal($message, $type, microtime(true), $context);
     }
     return $this;
 }
 public function initialize()
 {
     $this->add('email', new PresenceOf(['message' => 'Email is required']));
     $this->add('email', new Email(['message' => 'Email is not valid']));
     $this->add('email', new Uniqueness(['model' => (int) Version::getId() <= 2001341 ? User::class : new User(), 'message' => 'Email already exist']));
     $this->add('password', new PresenceOf(['message' => 'Password is required']));
     $this->add('password', new Confirmation(['with' => 'repassword', 'message' => 'Password and Repeat Password must match']));
     $this->add('repassword', new PresenceOf(['message' => 'Repeat Password is required']));
 }
Example #6
0
 /**
  * Tests the Debug::getVersion
  *
  * @issue  12215
  * @author Serghei Iakovlev <*****@*****.**>
  * @since  2016-09-25
  */
 public function testShouldGetVersion()
 {
     $this->specify("The getVersion doesn't work as expected", function () {
         $debug = new Debug();
         $target = '"_new"';
         $uri = '"https://docs.phalconphp.com/en/' . Version::getPart(Version::VERSION_MAJOR) . '.0.0/"';
         $version = Version::get();
         expect($debug->getVersion())->equals("<div class='version'>Phalcon Framework <a href={$uri} target={$target}>{$version}</a></div>");
     });
 }
Example #7
0
 /**
  * @expectedException \Phalcon\Acl\Exception
  * @expectedExceptionMessage Invalid value for accessList
  */
 public function testFactoryShouldThrowExceptionIfActionsKeyIsMissing()
 {
     if (version_compare(\Phalcon\Version::get(), '2.0.0', '=')) {
         $this->markTestSkipped('Fails due to a bug in Phalcon. See https://github.com/phalcon/cphalcon/pull/10226');
     }
     $config = new \Phalcon\Config\Adapter\Ini(__DIR__ . '/_fixtures/acl.ini');
     unset($config->acl->resource->index->actions);
     unset($config->acl->role->guest->allow->index->actions[0]);
     $factory = new \Phalcon\Acl\Factory\Memory();
     $acl = $factory->create($config->get('acl'));
 }
Example #8
0
 /**
  * {@inheridoc}.
  */
 public function register()
 {
     $crypt = new BaseCrypt();
     if (Str::startsWith($key = config('app.encryption.key'), 'base64:')) {
         $key = base64_decode(substr($key, 7));
     }
     $crypt->setKey($key);
     $crypt->setCipher(config('app.encryption.cipher'));
     if ((int) Version::getId() <= 2001341) {
         $crypt->setMode(config('app.encryption.mode'));
     }
     return $crypt;
 }
 /**
  * @return bool|void
  */
 public function beforeExecuteRoute()
 {
     $this->registerOptions();
     if (!parent::beforeExecuteRoute()) {
         return false;
     }
     $this->_currentVersion = join('.', sscanf(\Phalcon\Version::get(), '%d.%d.%d'));
     if (!$this->dispatcher->getParam('overwrite') && $this->db->tableExists((new Models\Versions())->getSource())) {
         $hasRecords = (bool) Models\Versions::count(['conditions' => 'version = ?0', 'bind' => [$this->_currentVersion]]);
         if ($hasRecords && !$this->confirm('Docs are already presents in the database. Do you want to overwrite it?')) {
             return false;
         }
     }
 }
 /**
  * Called by the DebugBar when data needs to be collected
  * @return array Collected data
  */
 function collect()
 {
     $request = $this->request;
     $response = $this->response;
     $status = $response->getHeaders()->get('Status') ?: '200 ok';
     $responseHeaders = $response->getHeaders()->toArray() ?: headers_list();
     $cookies = $_COOKIE;
     unset($cookies[session_name()]);
     $cookies_service = $response->getCookies();
     if ($cookies_service) {
         $useEncrypt = true;
         if ($cookies_service->isUsingEncryption() && $this->di->has('crypt') && !$this->di['crypt']->getKey()) {
             $useEncrypt = false;
         }
         if (!$cookies_service->isUsingEncryption()) {
             $useEncrypt = false;
         }
         foreach ($cookies as $key => $vlaue) {
             $cookies[$key] = $cookies_service->get($key)->useEncryption($useEncrypt)->getValue();
         }
     }
     $data = array('status' => $status, 'request_query' => $request->getQuery(), 'request_post' => $request->getPost(), 'request_body' => $request->getRawBody(), 'request_cookies' => $cookies, 'request_server' => $_SERVER, 'response_headers' => $responseHeaders, 'response_body' => $request->isAjax() ? $response->getContent() : '');
     if (Version::getId() < 2000000 && $request->isAjax()) {
         $data['request_headers'] = '';
         // 1.3.x has a ajax bug , so we use empty string insdead.
     } else {
         $data['request_headers'] = $request->getHeaders();
     }
     $data = array_filter($data);
     if (isset($data['request_query']['_url'])) {
         unset($data['request_query']['_url']);
     }
     if (empty($data['request_query'])) {
         unset($data['request_query']);
     }
     if (isset($data['request_headers']['php-auth-pw'])) {
         $data['request_headers']['php-auth-pw'] = '******';
     }
     if (isset($data['request_server']['PHP_AUTH_PW'])) {
         $data['request_server']['PHP_AUTH_PW'] = '******';
     }
     foreach ($data as $key => $var) {
         if (!is_string($data[$key])) {
             $data[$key] = $this->formatVar($var);
         }
     }
     return $data;
 }
 public function register()
 {
     $configPath = $this->configPath;
     $this->di->set('config.debugbar', function () use($configPath) {
         $base = new Php(__DIR__ . '/config/debugbar.php');
         $base['collectors']['phpinfo'] = true;
         $base['collectors']['time'] = true;
         $base['collectors']['messages'] = true;
         if (is_string($configPath) && is_file($configPath)) {
             $extension = strtolower(pathinfo($configPath, PATHINFO_EXTENSION));
             switch ($extension) {
                 case 'ini':
                     $config = new Ini($configPath);
                     break;
                 case 'json':
                     $config = new Json($configPath);
                     break;
                 case 'php':
                 case 'php5':
                 case 'inc':
                     $config = new Php($configPath);
                     break;
                 case 'yml':
                 case 'yaml':
                     $config = new Yaml($configPath);
                     break;
                 default:
                     throw new \RuntimeException(sprintf('Config adapter for %s files is not support', $extension));
             }
             $base->merge($config);
         } elseif (is_object($configPath) && $configPath instanceof Config) {
             $base->merge($configPath);
         } else {
         }
         return $base;
     }, true);
     $this->di->set('debugbar', function () {
         $di = Version::getId() > 2010000 ? $this : $this->di;
         $debugbar = new PhalconDebugbar($di);
         $debugbar->setHttpDriver(new PhalconHttpDriver());
         return $debugbar;
     });
     $this->setRoute();
     return $this;
 }
Example #12
0
 public function onConstruct()
 {
     if (!($release = $this->cacheData->get('gh_release'))) {
         $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_AUTOREFERER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 20, CURLOPT_HEADER => true, CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_USERAGENT => 'Phalcon HTTP/' . \Phalcon\Version::get() . ' (Curl)', CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_TIMEOUT => 30, CURLOPT_URL => 'https://api.github.com/repos/phalcon/cphalcon/releases/latest', CURLOPT_HTTPGET => true, CURLOPT_CUSTOMREQUEST => 'GET'];
         $ch = curl_init();
         curl_setopt_array($ch, $options);
         $content = curl_exec($ch);
         $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
         $body = substr($content, $headerSize);
         if ($errno = curl_errno($ch)) {
             error_log("Get GitHub release error: " . curl_error($ch));
         }
         curl_close($ch);
         $response = json_decode($body);
         if (JSON_ERROR_NONE !== json_last_error()) {
             error_log("Decode GitHub response error: " . json_last_error_msg());
         }
         if (isset($response->tag_name)) {
             $release = str_replace('phalcon-v', '', strtolower(trim($response->tag_name)));
             $this->cacheData->save('gh_release', $release, 60 * 60);
         }
     }
     $this->view->setVar('release', $release ? ' v.' . $release : '');
 }
Example #13
0
 public function setUp()
 {
     $_SERVER['SCRIPT_NAME'] = '/index.php';
     $_SERVER['PHWOOLCON_PHALCON_VERSION'] = Version::getId();
     /* @var Di $di */
     $di = $this->di = Di::getDefault();
     Events::register($di);
     DiFix::register($di);
     Db::register($di);
     Cache::register($di);
     Log::register($di);
     Config::register($di);
     Counter::register($this->di);
     Aliases::register($di);
     I18n::register($di);
     Cookies::register($di);
     Session::register($di);
     Cache::flush();
     Config::clearCache();
     parent::setUp();
     $class = get_class($this);
     Log::debug("================== Running {$class}::{$this->getName()}() ... ==================");
     Timer::start();
 }
Example #14
0
 public static function getPart($part)
 {
     return parent::getPart($part);
 }
Example #15
0
 /**
  * Executes the web tool application
  *
  * @param string $path
  */
 public static function main($path)
 {
     chdir('..');
     if (!extension_loaded('phalcon')) {
         throw new \Exception('Phalcon extension isn\'t installed, follow these instructions to install it: http://phalconphp.com/documentation/install');
     }
     //Read configuration
     $configPath = "app/config/config.ini";
     if (file_exists($configPath)) {
         $config = new \Phalcon\Config\Adapter\Ini($configPath);
     } else {
         $configPath = "app/config/config.php";
         if (file_exists($configPath)) {
             $config = (require $configPath);
         } else {
             throw new \Phalcon\Exception('Configuration file could not be loaded');
         }
     }
     $loader = new \Phalcon\Loader();
     $loader->registerDirs(array($path . '/scripts/', $path . '/scripts/Phalcon/Web/Tools/controllers/'));
     $loader->registerNamespaces(array('Phalcon' => $path . '/scripts/'));
     $loader->register();
     if (Version::getId() < Script::COMPATIBLE_VERSION) {
         throw new \Exception('Your Phalcon version isn\'t compatible with Developer Tools, download the latest at: http://phalconphp.com/download');
     }
     if (!defined('TEMPLATE_PATH')) {
         define('TEMPLATE_PATH', $path . '/templates');
     }
     try {
         $di = new \Phalcon\Di\FactoryDefault();
         $di->set('view', function () use($path) {
             $view = new \Phalcon\Mvc\View();
             $view->setViewsDir($path . '/scripts/Phalcon/Web/Tools/views/');
             return $view;
         });
         $di->set('config', $config);
         $di->set('url', function () use($config) {
             $url = new \Phalcon\Mvc\Url();
             $url->setBaseUri($config->application->baseUri);
             return $url;
         });
         $di->set('flash', function () {
             return new \Phalcon\Flash\Direct(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
         });
         $di->set('db', function () use($config) {
             return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name));
         });
         self::$_di = $di;
         $app = new \Phalcon\Mvc\Application();
         $app->setDi($di);
         echo $app->handle()->getContent();
     } catch (\Phalcon\Exception $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     } catch (\PDOException $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     }
 }
Example #16
0
try {
    $extensionLoaded = true;
    if (!extension_loaded('phalcon')) {
        $extensionLoaded = false;
        include dirname(__FILE__) . '/scripts/Phalcon/Script.php';
        throw new Exception(sprintf("Phalcon extension isn't installed, follow these instructions to install it: %s", Script::DOC_INSTALL_URL));
    }
    $loader = new Loader();
    $loader->registerDirs(array(__DIR__ . '/scripts/'))->registerNamespaces(array('Phalcon' => __DIR__ . '/scripts/'))->register();
    if (Version::getId() < Script::COMPATIBLE_VERSION) {
        throw new Exception(sprintf("Your Phalcon version isn't compatible with Developer Tools, download the latest at: %s", Script::DOC_DOWNLOAD_URL));
    }
    if (!defined('TEMPLATE_PATH')) {
        define('TEMPLATE_PATH', __DIR__ . '/templates');
    }
    $vendor = sprintf('Phalcon DevTools (%s)', Version::get());
    print PHP_EOL . Color::colorize($vendor, Color::FG_GREEN, Color::AT_BOLD) . PHP_EOL . PHP_EOL;
    $eventsManager = new EventsManager();
    $eventsManager->attach('command', new CommandsListener());
    $script = new Script($eventsManager);
    $commandsToEnable = array('\\Phalcon\\Commands\\Builtin\\Enumerate', '\\Phalcon\\Commands\\Builtin\\Controller', '\\Phalcon\\Commands\\Builtin\\Model', '\\Phalcon\\Commands\\Builtin\\AllModels', '\\Phalcon\\Commands\\Builtin\\Project', '\\Phalcon\\Commands\\Builtin\\Scaffold', '\\Phalcon\\Commands\\Builtin\\Migration', '\\Phalcon\\Commands\\Builtin\\Webtools');
    foreach ($commandsToEnable as $command) {
        $script->attach(new $command($script, $eventsManager));
    }
    $script->run();
} catch (PhalconException $e) {
    print Color::error($e->getMessage()) . PHP_EOL;
} catch (Exception $e) {
    if ($extensionLoaded) {
        print Color::error($e->getMessage()) . PHP_EOL;
    } else {
Example #17
0
 /**
  * Execute Phalcon Developer Tools
  *
  * @param  string             $path The path to the Phalcon Developer Tools
  * @param  string             $ip   Optional IP address for securing Developer Tools
  * @return void
  * @throws \Exception         if Phalcon extension is not installed
  * @throws \Exception         if Phalcon version is not compatible Developer Tools
  * @throws \Phalcon\Exception if Application config could not be loaded
  */
 public static function main($path, $ip = null)
 {
     if (!extension_loaded('phalcon')) {
         throw new \Exception(sprintf("Phalcon extension isn't installed, follow these instructions to install it: %s", Script::DOC_INSTALL_URL));
     }
     if ($ip !== null) {
         self::$ip = $ip;
     }
     if (!defined('TEMPLATE_PATH')) {
         define('TEMPLATE_PATH', $path . '/templates');
     }
     $basePath = dirname(getcwd());
     // Dirs for search config file
     $configDirs = array($basePath . '/config/', $basePath . '/app/config/', $basePath . '/apps/frontend/config/', $basePath . '/apps/backend/config/');
     $readed = false;
     foreach ($configDirs as $configPath) {
         if (file_exists($configPath . 'config.ini')) {
             $config = new ConfigIni($configPath . 'config.ini');
             $readed = true;
             break;
         } else {
             if (file_exists($configPath . 'config.php')) {
                 $config = (include $configPath . 'config.php');
                 if (is_array($config)) {
                     $config = new Config($config);
                 }
                 $readed = true;
                 break;
             }
         }
     }
     if ($readed === false) {
         throw new Exception(sprintf('Configuration file could not be loaded! Scanned dirs: %s', implode(', ', $configDirs)));
     }
     $loader = new Loader();
     $loader->registerDirs(array($path . '/scripts/', $path . '/scripts/Phalcon/Web/Tools/controllers/'));
     $loader->registerNamespaces(array('Phalcon' => $path . '/scripts/'));
     $loader->register();
     if (Version::getId() < Script::COMPATIBLE_VERSION) {
         throw new \Exception(sprintf("Your Phalcon version isn't compatible with Developer Tools, download the latest at: %s", Script::DOC_DOWNLOAD_URL));
     }
     try {
         $di = new FactoryDefault();
         $di->set('view', function () use($path) {
             $view = new View();
             $view->setViewsDir($path . '/scripts/Phalcon/Web/Tools/views/');
             return $view;
         });
         $di->set('config', $config);
         $di->set('url', function () use($config) {
             $url = new Url();
             $url->setBaseUri($config->application->baseUri);
             return $url;
         });
         $di->set('flash', function () {
             return new Flash(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning'));
         });
         $di->set('db', function () use($config) {
             if (isset($config->database->adapter)) {
                 $adapter = $config->database->adapter;
             } else {
                 $adapter = 'Mysql';
             }
             if (is_object($config->database)) {
                 $configArray = $config->database->toArray();
             } else {
                 $configArray = $config->database;
             }
             $className = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
             unset($configArray['adapter']);
             return new $className($configArray);
         });
         self::$di = $di;
         $app = new Application();
         $app->setDi($di);
         echo $app->handle()->getContent();
     } catch (Exception $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     } catch (\PDOException $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     }
 }
Example #18
0
    /**
     * Returns the current framework version.
     *
     * @return string
     */
    public function getVersion()
    {
        if (class_exists("\\Phalcon\\Version")) {
            $version = \Phalcon\Version::get();
        } else {
            $version = "git-master";
        }
        $parts = explode(' ', $version);
        return '<div class="version">
			Phalcon Framework <a target="_new" href="http://docs.phalconphp.com/en/' . $parts[0] . '/">' . $version . '</a>
		</div>';
    }
Example #19
0
<?php

/**
 * Скрипт формирует файлы примеров для компонентов
 *
 *
 * php scripts/gen-examples.php
 */
define('ROOT_DIR', '/home/boston/www/phalcon-docs/en/api');
$version = \Phalcon\Version::get();
$versionPieces = explode(' ', $version);
$phalconVersion = $versionPieces[0];
define('EXAMPLES_ROOT', sprintf("%s/%s", dirname(__DIR__), 'examples'));
define('EXAMPLES_DIR', sprintf("%s/%s", EXAMPLES_ROOT, $phalconVersion));
class ExamplesGenerator
{
    protected $_docs = array();
    private $template;
    public function __construct($directory)
    {
        $this->template = file_get_contents(EXAMPLES_ROOT . '/template.php');
        $this->_scanSources($directory);
    }
    protected function _scanSources($directory)
    {
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS));
        foreach ($iterator as $item) {
            $file = $item->getPathname();
            if ($item->getExtension() == 'rst' && !strpos($file, 'Interface') && !strpos($file, 'index')) {
                $this->createFile($file);
            }
 public function testModuleLoaded()
 {
     $this->assertTrue(in_array('phalcon', get_loaded_extensions()), 'Phalcon extension not properly loaded');
     $this->assertGreaterThanOrEqual(2, Version::getPart(Version::VERSION_MAJOR), 'Invalid Phalcon version: "' . Version::get() . '"');
 }
Example #21
0
 public function getRealSql($sql, $variables, $sqlBindTypes)
 {
     if (!$variables) {
         return $sql;
     }
     $pdo = $this->_db->getInternalHandler();
     $indexes = array();
     $keys = array();
     foreach ($variables as $key => $value) {
         if (is_array($value) && Version::getId() >= 2000440) {
             foreach ($value as $k => $v) {
                 $keys[':' . $key . $k] = $pdo->quote($v);
             }
         } else {
             $type = isset($sqlBindTypes[$key]) ? $sqlBindTypes[$key] : null;
             if (is_numeric($key)) {
                 $indexes[$key] = $this->quote($pdo, $value, $type);
             } else {
                 if (is_numeric(substr($key, 1))) {
                     $keys[$key] = $this->quote($pdo, $value, $type);
                 } elseif (substr($key, 0, 1) === ':') {
                     $keys[$key] = $this->quote($pdo, $value, $type);
                 } else {
                     $keys[':' . $key] = $this->quote($pdo, $value, $type);
                 }
             }
         }
     }
     $splited = preg_split('/(?=\\?)|(?<=\\?)/', $sql);
     $result = array();
     foreach ($splited as $key => $value) {
         if ($value == '?') {
             $result[$key] = array_shift($indexes);
         } else {
             $result[$key] = $value;
         }
     }
     $result = implode(' ', $result);
     $result = strtr($result, $keys);
     return $result;
 }
Example #22
0
use Phalcon\Version;
use Phwoolcon\Aliases;
use Phwoolcon\Cache;
use Phwoolcon\Config;
use Phwoolcon\Cookies;
use Phwoolcon\Db;
use Phwoolcon\DiFix;
use Phwoolcon\Events;
use Phwoolcon\I18n;
use Phwoolcon\Log;
use Phwoolcon\Queue;
use Phwoolcon\Router;
use Phwoolcon\Session;
use Phwoolcon\Util\Counter;
use Phwoolcon\View;
$_SERVER['PHWOOLCON_PHALCON_VERSION'] = Version::getId();
Events::register($di);
DiFix::register($di);
Db::register($di);
Cache::register($di);
Log::register($di);
Config::register($di);
Counter::register($di);
Aliases::register($di);
Router::register($di);
I18n::register($di);
Cookies::register($di);
Session::register($di);
View::register($di);
Queue::register($di);
$loader->registerNamespaces(Config::get('app.autoload.namespaces', []), true);
Example #23
0
 /**
  * Tests the getId() translation to get()
  *
  * @author Nikos Dimopoulos <*****@*****.**>
  * @since  2012-11-29
  */
 public function testGetIdToGet()
 {
     $id = Version::getId();
     $major = intval($id[0]);
     $med = intval($id[1] . $id[2]);
     $min = intval($id[3] . $id[4]);
     $special = $this->_numberToSpecial($id[5]);
     $specialNo = $special ? $id[6] : '';
     $expected = trim("{$major}.{$med}.{$min} {$special} {$specialNo}");
     $actual = Version::get();
     $this->assertEquals($actual, $expected, "Version getId to get does not translate properly");
 }
<?php

/**
 * Created by PhpStorm.
 * User: rcmonitor
 * Date: 07.07.15
 * Time: 15:46
 */
use Phalcon\Di;
use Phalcon\Events\Manager;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Router;
use Phalcon\Version;
$di = new Di\FactoryDefault();
$oRouter = new Router(false);
$oRouter->setDI($di);
$oRouter->add('/:controller', array('controller' => 1, 'action' => 'index'));
$oEventManager = new Manager();
$oEventManager->attach('dispatch:beforeDispatch', function () {
    return false;
});
$oDispatcher = new Dispatcher();
$oDispatcher->setDI($di);
$oDispatcher->setEventsManager($oEventManager);
$oRouter->handle('/test');
$oDispatcher->setControllerName($oRouter->getControllerName());
$oDispatcher->setActionName($oRouter->getActionName());
$oDispatcher->dispatch();
echo $oDispatcher->getControllerClass() . PHP_EOL;
echo Version::get() . PHP_EOL;
Example #25
0
 /**
  * Execute Phalcon Developer Tools
  *
  * @param  string             $path The path to the Phalcon Developer Tools
  * @param  string             $ip   Optional IP address for securing Developer Tools
  * @return void
  * @throws \Exception         if Phalcon extension is not installed
  * @throws \Exception         if Phalcon version is not compatible Developer Tools
  * @throws \Phalcon\Exception if Application config could not be loaded
  */
 public static function main($path, $ip = null)
 {
     if (!extension_loaded('phalcon')) {
         throw new \Exception('Phalcon extension is not installed, follow these instructions to install it: http://phalconphp.com/documentation/install');
     }
     if ($ip !== null) {
         self::$ip = $ip;
     }
     if (!defined('TEMPLATE_PATH')) {
         define('TEMPLATE_PATH', $path . '/templates');
     }
     chdir('..');
     // Read configuration
     $configPaths = array('config', 'app/config', 'apps/frontend/config');
     $readed = false;
     foreach ($configPaths as $configPath) {
         $cpath = $configPath . '/config.ini';
         if (file_exists($cpath)) {
             $config = new \Phalcon\Config\Adapter\Ini($cpath);
             $readed = true;
             break;
         } else {
             $cpath = $configPath . '/config.php';
             if (file_exists($cpath)) {
                 $config = (require $cpath);
                 $readed = true;
                 break;
             }
         }
     }
     if ($readed === false) {
         throw new \Phalcon\Exception('Configuration file could not be loaded!');
     }
     $loader = new \Phalcon\Loader();
     $loader->registerDirs(array($path . '/scripts/', $path . '/scripts/Phalcon/Web/Tools/controllers/'));
     $loader->registerNamespaces(array('Phalcon' => $path . '/scripts/'));
     $loader->register();
     if (Version::getId() < Script::COMPATIBLE_VERSION) {
         throw new \Exception('Your Phalcon version is not compatible with Developer Tools, download the latest at: http://phalconphp.com/download');
     }
     try {
         $di = new FactoryDefault();
         $di->set('view', function () use($path) {
             $view = new View();
             $view->setViewsDir($path . '/scripts/Phalcon/Web/Tools/views/');
             return $view;
         });
         $di->set('config', $config);
         $di->set('url', function () use($config) {
             $url = new \Phalcon\Mvc\Url();
             $url->setBaseUri($config->application->baseUri);
             return $url;
         });
         $di->set('flash', function () {
             return new \Phalcon\Flash\Direct(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
         });
         $di->set('db', function () use($config) {
             if (isset($config->database->adapter)) {
                 $adapter = $config->database->adapter;
             } else {
                 $adapter = 'Mysql';
             }
             if (is_object($config->database)) {
                 $configArray = $config->database->toArray();
             } else {
                 $configArray = $config->database;
             }
             $className = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
             unset($configArray['adapter']);
             return new $className($configArray);
         });
         self::$di = $di;
         $app = new \Phalcon\Mvc\Application();
         $app->setDi($di);
         echo $app->handle()->getContent();
     } catch (\Phalcon\Exception $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     } catch (\PDOException $e) {
         echo get_class($e), ': ', $e->getMessage(), "<br>";
         echo nl2br($e->getTraceAsString());
     }
 }
Example #26
0
    return $url;
});
/**
 * Setting the View and View Engines
 */
$di->setShared('view', function () use($config, $di, $eventsManager) {
    $view = new View();
    $view->registerEngines(['.volt' => function ($view, $di) use($config) {
        $volt = new Volt($view, $di);
        $path = APPLICATION_ENV == APP_TEST ? DOCROOT . 'tests/_cache/' : DOCROOT . $config->get('volt')->cacheDir;
        $options = ['compiledPath' => $path, 'compiledExtension' => $config->get('volt')->compiledExt, 'compiledSeparator' => $config->get('volt')->separator, 'compileAlways' => APPLICATION_ENV !== APP_PRODUCTION];
        $volt->setOptions($options);
        $volt->getCompiler()->addFunction('strtotime', 'strtotime')->addFunction('sprintf', 'sprintf')->addFunction('str_replace', 'str_replace')->addFunction('is_a', 'is_a');
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']);
    $view->setVar('version', Version::get())->setViewsDir(DOCROOT . $config->get('application')->viewsDir);
    $eventsManager->attach('view', function ($event, $view) use($di, $config) {
        /**
         * @var \Phalcon\Events\Event $event
         * @var \Phalcon\Mvc\View $view
         */
        if ($event->getType() == 'notFoundView') {
            $message = sprintf('View not found - %s', $view->getActiveRenderPath());
            throw new Exception($message);
        }
    });
    $view->setEventsManager($eventsManager);
    return $view;
});
/**
 * Database connection is created based in the parameters defined in the configuration file
 /**
  * @param $view
  *
  * @throws \DebugBar\DebugBarException
  */
 public function attachView($view)
 {
     if (!$this->shouldCollect('view', true) || isset($this->collectors['views'])) {
         return;
     }
     // You can add only One View instance
     if (is_string($view)) {
         $view = $this->di[$view];
     }
     $engins = $view->getRegisteredEngines();
     if (isset($engins['.volt'])) {
         $volt = $engins['.volt'];
         if (is_object($volt)) {
             if ($volt instanceof \Closure) {
                 $volt = $volt($view, $this->di);
             }
         } elseif (is_string($volt)) {
             if (class_exists($volt)) {
                 $volt = new Volt($view, $this->di);
             } elseif ($this->di->has($volt)) {
                 $volt = $this->di->getShared($volt, array($view, $this->di));
             }
         }
         $engins['.volt'] = $volt;
         $view->registerEngines($engins);
         $volt->getCompiler()->addExtension(new VoltFunctions($this->di));
     }
     $viewProfiler = new Registry();
     $viewProfiler->templates = array();
     $viewProfiler->engines = $view->getRegisteredEngines();
     $config = $this->config;
     $eventsManager = $view->getEventsManager();
     if (!is_object($eventsManager)) {
         $eventsManager = new Manager();
     }
     $eventsManager->attach('view:beforeRender', function ($event, $view) use($viewProfiler) {
         $viewProfiler->startRender = microtime(true);
     });
     $eventsManager->attach('view:afterRender', function ($event, $view) use($viewProfiler, $config) {
         $viewProfiler->stopRender = microtime(true);
         if ($config->options->views->get('data', false)) {
             $viewProfiler->params = $view->getParamsToView();
         } else {
             $viewProfiler->params = null;
         }
     });
     $eventsManager->attach('view:beforeRenderView', function ($event, $view) use($viewProfiler) {
         $viewFilePath = $view->getActiveRenderPath();
         if (Version::getId() >= 2000140) {
             if (!$view instanceof \Phalcon\Mvc\ViewInterface && $view instanceof \Phalcon\Mvc\ViewBaseInterface) {
                 $viewFilePath = realpath($view->getViewsDir()) . DIRECTORY_SEPARATOR . $viewFilePath;
             }
         } elseif ($view instanceof Simple) {
             $viewFilePath = realpath($view->getViewsDir()) . DIRECTORY_SEPARATOR . $viewFilePath;
         }
         $templates = $viewProfiler->templates;
         $templates[$viewFilePath]['startTime'] = microtime(true);
         $viewProfiler->templates = $templates;
     });
     $eventsManager->attach('view:afterRenderView', function ($event, $view) use($viewProfiler) {
         $viewFilePath = $view->getActiveRenderPath();
         if (Version::getId() >= 2000140) {
             if (!$view instanceof \Phalcon\Mvc\ViewInterface && $view instanceof \Phalcon\Mvc\ViewBaseInterface) {
                 $viewFilePath = realpath($view->getViewsDir()) . DIRECTORY_SEPARATOR . $viewFilePath;
             }
         } elseif ($view instanceof Simple) {
             $viewFilePath = realpath($view->getViewsDir()) . DIRECTORY_SEPARATOR . $viewFilePath;
         }
         $templates = $viewProfiler->templates;
         $templates[$viewFilePath]['stopTime'] = microtime(true);
         $viewProfiler->templates = $templates;
     });
     $view->setEventsManager($eventsManager);
     $collector = new ViewCollector($viewProfiler, $view);
     $this->addCollector($collector);
 }
Example #28
0
 /**
  * Returns the major framework's version
  *
  * @return string
  */
 public function getMajorVersion()
 {
     $parts = explode(' ', Version::get());
     return (string) $parts[0];
 }