Esempio n. 1
0
 /**
  * {@inheritdoc}
  */
 public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity)
 {
     $di = new Di();
     /** @var Security $security */
     $security = $di->getShared('security');
     $user = Users::query()->where("username = :username:")->bind(['username' => $username])->limit(1)->execute()->toArray();
     $correctDetails = false;
     if (count($user) === 1) {
         $user = current($user);
         if ($security->checkHash($password, $user['password'])) {
             $correctDetails = true;
         } else {
             $security->hash(rand());
         }
     } else {
         // prevent timing attacks
         $security->hash(rand());
     }
     if ($correctDetails) {
         //$scope = new ScopeEntity();
         //$scope->setIdentifier('email');
         //$scopes[] = $scope;
         return new UserEntity($user);
     }
     return null;
 }
Esempio n. 2
0
 public function getShared($name, $parameters = null)
 {
     if ($this->_init) {
         $this->checkPermission($name);
     }
     return parent::getShared($name, $parameters);
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  */
 public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
 {
     $di = new Di();
     /** @var Security $security */
     $security = $di->getShared('security');
     $client = Clients::query()->where("id = :id:")->bind(['id' => $clientIdentifier])->limit(1)->execute()->toArray();
     $correctDetails = false;
     if (count($client) === 1) {
         $client = current($client);
         if ($mustValidateSecret) {
             if ($security->checkHash($clientSecret, $client['secret'])) {
                 $correctDetails = true;
             } else {
                 $security->hash(rand());
             }
         } else {
             $correctDetails = true;
         }
     } else {
         // prevent timing attacks
         $security->hash(rand());
     }
     if ($correctDetails) {
         $clientEntity = new ClientEntity();
         $clientEntity->setIdentifier($clientIdentifier);
         $clientEntity->setName($client['name']);
         $clientEntity->setRedirectUri($client['redirect_url']);
         return $clientEntity;
     }
     return null;
 }
 function __construct(FactoryDefault $di, $options = null)
 {
     $this->is_started = false;
     $this->_di = $di;
     $dispatcher = $di->getDispatcher();
     $eventsManager = $di->getShared('eventsManager');
     $eventsManager->attach('dispatch', function ($event, $dispatcher) use($di) {
         if ($event->getType() == 'afterDispatch') {
             $session = $di->getSession();
             $session->__destruct();
         }
     });
     $dispatcher->setEventsManager($eventsManager);
 }
Esempio n. 5
0
 /**
  * Normally, the framework creates the Dispatcher automatically. In our case, we want to perform a verification
  * before executing the required action, checking if the user has access to it or not. To achieve this,
  * we have replaced the component by creating a function in the bootstrap
  * @param \Phalcon\DI\FactoryDefault     $di
  * @param null                           $security
  */
 public function registerSecureDispatcher($di, $security)
 {
     /**
      * @return Dispatcher
      */
     $di->set('dispatcher', function () use($di, $security) {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace($this->default_namespace);
         /**
          * Obtain the standard eventsManager from the DI
          */
         $eventsManager = $di->getShared('eventsManager');
         /**
          * Listen for events produced in the dispatcher using the Security plugin
          */
         $eventsManager->attach('dispatch', $security);
         /**
          * Bind the EventsManager to the Dispatcher
          */
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
 }
Esempio n. 6
0
});
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    return new DbAdapter($config->database->toArray());
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->set('modelsMetadata', function () {
    return new MetaDataAdapter();
});
// custom dispatcher overrides the default
$di->set('$dispatcher', function () use($di) {
    $eventsManager = $di->getShared('eventsManager');
    // custom ACl class
    $permission = new Permission();
    // Listen for events from the permission class
    $eventsManager->attach('dispatch', $permission);
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
Esempio n. 7
0
 public function build()
 {
     $options = $this->_options;
     $path = '';
     if (isset($this->_options['directory'])) {
         if ($this->_options['directory']) {
             $path = $this->_options['directory'] . '/';
         }
     }
     $name = $options['name'];
     $config = $this->_getConfig($path);
     if (!isset($config->database->adapter)) {
         throw new BuilderException("Adapter was not found in the config. Please specify a config varaible [database][adapter]");
     }
     $adapter = ucfirst($config->database->adapter);
     $this->isSupportedAdapter($adapter);
     $di = new FactoryDefault();
     $di->set('db', function () use($adapter, $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;
         }
         $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
         unset($configArray['adapter']);
         return new $adapterName($configArray);
     });
     if (isset($config->application->modelsDir)) {
         $options['modelsDir'] = $path . $config->application->modelsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the views directory");
     }
     if (isset($config->application->controllersDir)) {
         $options['controllersDir'] = $path . $config->application->controllersDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the controllers directory");
     }
     if (isset($config->application->viewsDir)) {
         $options['viewsDir'] = $path . $config->application->viewsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the views directory");
     }
     if (isset($config->application->gridsDir)) {
         $options['gridsDir'] = $path . $config->application->gridsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the grids directory");
     }
     if (isset($config->application->formsDir)) {
         $options['formsDir'] = $path . $config->application->formsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the forms directory");
     }
     $options['manager'] = $di->getShared('modelsManager');
     $options['className'] = Text::camelize($options['name']);
     $options['fileName'] = Text::uncamelize($options['className']);
     $modelClass = Text::camelize($name);
     $modelPath = $config->application->modelsDir . '/' . $modelClass . '.php';
     if (!file_exists($modelPath)) {
         $modelBuilder = new ModelBuilder(array('name' => $name, 'schema' => $options['schema'], 'className' => $options['className'], 'fileName' => $options['fileName'], 'genSettersGetters' => $options['genSettersGetters'], 'directory' => $options['directory'], 'force' => $options['force']));
         $modelBuilder->build();
     }
     if (!class_exists($modelClass)) {
         require $modelPath;
     }
     $entity = new $modelClass();
     $metaData = $di['modelsMetadata'];
     $attributes = $metaData->getAttributes($entity);
     $dataTypes = $metaData->getDataTypes($entity);
     $identityField = $metaData->getIdentityField($entity);
     $primaryKeys = $metaData->getPrimaryKeyAttributes($entity);
     $setParams = [];
     $selectDefinition = [];
     $relationField = '';
     $single = $name;
     $options['name'] = strtolower(Text::camelize($single));
     $options['plural'] = $this->_getPossiblePlural($name);
     $options['singular'] = $this->_getPossibleSingular($name);
     $options['entity'] = $entity;
     $options['setParams'] = $setParams;
     $options['attributes'] = $attributes;
     $options['dataTypes'] = $dataTypes;
     $options['primaryKeys'] = $primaryKeys;
     $options['identityField'] = $identityField;
     $options['relationField'] = $relationField;
     $options['selectDefinition'] = $selectDefinition;
     $options['autocompleteFields'] = [];
     $options['belongsToDefinitions'] = [];
     //Build Controller
     $this->_makeController($path, $options);
     if (isset($options['templateEngine']) && $options['templateEngine'] == 'volt') {
         //View layouts
         $this->_makeLayoutsVolt($path, $options);
         //View index.phtml
         $this->_makeViewIndexVolt($path, $options);
         //View search.phtml
         $this->_makeViewSearchVolt($path, $options);
         //View new.phtml
         $this->_makeViewNewVolt($path, $options);
         //View edit.phtml
         $this->_makeViewEditVolt($path, $options);
     } else {
         //View layouts
         $this->_makeLayouts($path, $options);
         //View index.phtml
         $this->_makeViewIndex($path, $options);
         //View search.phtml
         $this->_makeViewSearch($path, $options);
         //View new.phtml
         $this->_makeViewNew($path, $options);
         //View edit.phtml
         $this->_makeViewEdit($path, $options);
     }
     return true;
 }
Esempio n. 8
0
 /**
  * @return bool
  * @throws \Exception
  */
 public function build()
 {
     $options = $this->_options;
     if (Tools::getDb()) {
         $config = Tools::getDb();
     }
     if (!isset($config->adapter)) {
         throw new \Exception("Adapter was not found in the config. Please specify a config variable [database][adapter]");
     }
     $adapter = ucfirst($config->adapter);
     $this->isSupportedAdapter($adapter);
     $di = new FactoryDefault();
     $di->set('db', function () use($adapter, $config) {
         if (isset($config->adapter)) {
             $adapter = $config->adapter;
         } else {
             $adapter = 'Mysql';
         }
         if (is_object($config)) {
             $configArray = $config->toArray();
         } else {
             $configArray = $config;
         }
         $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
         unset($configArray['adapter']);
         return new $adapterName($configArray);
     });
     $options['manager'] = $di->getShared('modelsManager');
     $options['className'] = $options['name'];
     $options['fileName'] = str_replace('_', '-', Text::uncamelize($options['className']));
     $modelsNamespace = $options['modelsNamespace'];
     if (isset($modelsNamespace) && substr($modelsNamespace, -1) !== '\\') {
         $modelsNamespace .= "\\";
     }
     $modelName = $options['name'];
     $modelClass = $modelsNamespace . $modelName;
     if (!@dir($options['modelsDir'])) {
         if (!@mkdir($options['modelsDir'])) {
             throw new \Exception('Could not create directory on ' . $options['modelsDir']);
         }
         @chmod($options['modelsDir'], 0777);
     }
     $modelPath = $options['modelsDir'] . DIRECTORY_SEPARATOR . $modelName . '.php';
     if (!file_exists($modelPath)) {
         $modelBuilder = new ModelBuilder(array('module' => $options['module'], 'name' => null, 'tableName' => $options['tableName'], 'schema' => $options['schema'], 'baseClass' => null, 'namespace' => $options['modelsNamespace'], 'foreignKeys' => true, 'defineRelations' => true, 'genSettersGetters' => $options['genSettersGetters'], 'directory' => $options['modelsDir'], 'force' => $options['force']));
         $modelBuilder->build();
     }
     if (!class_exists($modelClass)) {
         require_once $modelPath;
     }
     $entity = new $modelClass();
     $metaData = $di['modelsMetadata'];
     $attributes = $metaData->getAttributes($entity);
     $dataTypes = $metaData->getDataTypes($entity);
     $identityField = $metaData->getIdentityField($entity);
     $primaryKeys = $metaData->getPrimaryKeyAttributes($entity);
     $setParams = array();
     $selectDefinition = array();
     $relationField = '';
     $options['name'] = Text::uncamelize($options['name']);
     $options['plural'] = $this->_getPossiblePlural($options['name']);
     $options['singular'] = $this->_getPossibleSingular($options['name']);
     $options['modelClass'] = $options['modelsNamespace'] . '\\' . $this->_options['name'];
     $options['entity'] = $entity;
     $options['setParams'] = $setParams;
     $options['attributes'] = $attributes;
     $options['dataTypes'] = $dataTypes;
     $options['primaryKeys'] = $primaryKeys;
     $options['identityField'] = $identityField;
     $options['relationField'] = $relationField;
     $options['selectDefinition'] = $selectDefinition;
     $options['autocompleteFields'] = array();
     $options['belongsToDefinitions'] = array();
     //Build Controller
     $this->_makeController($options);
     if (isset($options['templateEngine']) && $options['templateEngine'] == 'volt') {
         //View layouts
         //    $this->_makeLayoutsVolt($options);
         //View index.phtml
         $this->_makeViewIndexVolt(null, $options);
         //View search.phtml
         $this->_makeViewSearchVolt(null, $options);
         //View new.phtml
         $this->_makeViewNewVolt(null, $options);
         //View edit.phtml
         $this->_makeViewEditVolt(null, $options);
     } else {
         //View layouts
         //     $this->_makeLayouts(null, $options);
         //View index.phtml
         $this->_makeViewIndex(null, $options);
         //View search.phtml
         $this->_makeViewSearch(null, $options);
         //View new.phtml
         $this->_makeViewNew(null, $options);
         //View edit.phtml
         $this->_makeViewEdit(null, $options);
     }
     return true;
 }
Esempio n. 9
0
    return new IniConfig("config/{$fileName}.ini");
});
$di->setShared('session', function () {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});
$di->set('modelsCache', function () {
    //Cache data for one day by default
    $frontCache = new \Phalcon\Cache\Frontend\Data(array('lifetime' => 3600));
    //File cache settings
    $cache = new \Phalcon\Cache\Backend\File($frontCache, array('cacheDir' => __DIR__ . '/cache/'));
    return $cache;
});
$di->set('db', function () use($di) {
    $config = $di->getShared('config');
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname));
});
/**
 * If our request contains a body, it has to be valid JSON.  This parses the 
 * body into a standard Object and makes that vailable from the DI.  If this service
 * is called from a function, and the request body is nto valid JSON or is empty,
 * the program will throw an Exception.
 */
$di->setShared('requestBody', function () {
    $in = file_get_contents('php://input');
    $in = json_decode($in, FALSE);
    // JSON body could not be parsed, throw exception
    if ($in === null) {
        throw new \PhalconRest\Exceptions\HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => ''));
    }
Esempio n. 10
0
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
/**
* Start dispatcher
*/
$di->set('dispatcher', function () {
    $dispatcher = new Dispatcher();
    return $dispatcher;
});
/**
* Setup Facebook Auth
*/
$di->set('facebook', function () use($config, $di) {
    $session = $di->getShared('session');
    $session->set("redirectUrl", $config->facebook->redirectUrl);
    $fb = new Facebook(array('app_id' => $config->facebook->appId, 'app_secret' => $config->facebook->appSecret, 'default_graph_version' => $config->facebook->default_graph_version, 'persistent_data_handler' => new MyPhalconPersistentDataHandler($session)));
    return $fb;
});
$di->set('authFacebook', function () {
    return new AuthFacebook();
});
/**
* Setup Request Handler
*/
$di->set('request', function () {
    $request = new Request();
    return $request;
});
/**
Esempio n. 11
0
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->set('modelsMetadata', function () {
    return new MetaDataAdapter();
});
/**
 * Start the session the first time some component request the session service
 */
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
$di->set('view', function () use($config, $di) {
    $view = new View();
    $router = $di->getShared('router');
    /*
     * @todo 给layouts等目录统一变量
     * */
    $view->setViewsDir(__DIR__ . '/views/');
    $view->setLayoutsDir('/../../../layouts/');
    // 多模块的话, 可能会有多个风格,所以需要切换layout,这里的Path是根据当前module的Path向上走的
    $view->setLayout('adminCommon');
    $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
        $volt = new VoltEngine($view, $di);
        $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_'));
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
}, true);
    $router->add("/methodist/:controller/:action/?([0-9]+)?", array('module' => 'methodist', 'controller' => 1, 'action' => 2, 'id' => 3));
    $router->add("/student/:controller/?", array('module' => 'student', 'controller' => 1, 'action' => 'index'));
    $router->add("/student/:controller/:action", array('module' => 'student', 'controller' => 1, 'action' => 2));
    /*$router->add("/crud/:controller/:action/", array(
    		'module'     => 'crud',
    		'controller' => 1,
    		'action'     => 2
    	));*/
    $router->add("/crud/:controller/:action/:params", array('module' => 'crud', 'controller' => 1, 'action' => 2, 'params' => 3));
    $router->add("/crud/:controller(/)", array('module' => 'crud', 'controller' => 1, 'action' => "index"));
    $router->add("/crud/:controller/:int", array('module' => 'crud', 'controller' => 1, 'action' => "index", 'int' => 2));
    return $router;
});
$di->set('mail', function () use($config) {
    return new Mail($config);
});
/**
 * Shared translate service
 */
$di->setShared('trans', function () use($di) {
    $request = $di->getShared('request');
    $language = $request->getBestLanguage();
    if (file_exists(__DIR__ . "/../languages/" . $language . ".php")) {
        require __DIR__ . "/../languages/" . $language . ".php";
    } else {
        if (file_exists(__DIR__ . "/../languages/ru.php")) {
            require __DIR__ . "/../languages/ru.php";
        }
    }
    return new \Phalcon\Translate\Adapter\NativeArray(array("content" => $t));
});
Esempio n. 13
0
 * Setting up the view component
 */
$di->set('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(['.volt' => 'voltService', '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']);
    return $view;
}, true);
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config, $di) {
    $connection = new DatabaseConnection($config->database->toArray());
    $debug = $config->application->debug;
    if ($debug) {
        $eventsManager = $di->getShared('eventsManager');
        $logger = new FileLogger(__DIR__ . "/../logs/query.txt");
        // Listen all the database events
        $eventsManager->attach('db', function ($event, $connection) use($logger) {
            // Phalcon\Events\Event
            if ($event->getType() == 'beforeQuery') {
                // DatabaseConnection
                $variables = $connection->getSQLVariables();
                if ($variables) {
                    $logger->log($connection->getSQLStatement() . ' [' . join(',', (array) $variables) . ']', \Phalcon\Logger::INFO);
                } else {
                    $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
                }
            }
        });
        // Assign the eventsManager to the db adapter instance
Esempio n. 14
0
 * @var DefaultDI
 */
$di = new DefaultDI();
/**
 * $di's setShared method provides a singleton instance.
 * If the second parameter is a function, then the service is lazy-loaded
 * on its first instantiation.
 */
$di->setShared('config', function () {
    return new IniConfig(__DIR__ . "/config/config.ini");
});
/**
 * Return array of the Collections, which define a group of routes, from
 * routes/collections.  These will be mounted into the app itself later.
 */
$availableVersions = $di->getShared('config')->versions;
$allCollections = [];
foreach ($availableVersions as $versionString => $versionPath) {
    $currentCollections = (include 'Modules/' . $versionPath . '/Routes/routeLoader.php');
    $allCollections = array_merge($allCollections, $currentCollections);
}
$di->set('collections', function () use($allCollections) {
    return $allCollections;
});
// As soon as we request the session service, it will be started.
$di->setShared('session', function () {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});
/**
Esempio n. 15
0
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as FlashDirect;
use Moltin\Cart\Cart;
use Moltin\Cart\Storage\Session;
use Moltin\Cart\Identifier\Cookie;
/**
 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
 */
$di = new FactoryDefault();
$di->set('ecommerce_options', function () {
    return new Ecommerce\Admin\Models\Options();
});
$di->set('url', function () use($di) {
    $eo = $di->getShared('ecommerce_options');
    $url = new UrlResolver();
    $url->setBaseUri($eo->url_base);
    return $url;
}, true);
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    return new DbAdapter($config->database->toArray());
});
$di->set('flash', function () {
    $flash = new FlashDirect(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning'));
    return $flash;
});
/**
Esempio n. 16
0
 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
 */
$di = new FactoryDefault();
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
}, true);
/**
 * The Dispatcher component
 */
$di->setShared('dispatcher', function () use($di) {
    $eventsManager = $di->getShared('eventsManager');
    $dispatcher = new Dispatcher();
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});
/**
 * Setting up the view component
 */
$di->set('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->setRenderLevel(View::LEVEL_ACTION_VIEW);
    $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
        $volt = new VoltEngine($view, $di);
        $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_', 'compileAlways' => true));
        //add filter functions
Esempio n. 17
0
 /**
  * @return bool
  * @throws BuilderException
  */
 public function build()
 {
     if ($this->options->contains('directory')) {
         $this->path->setRootPath($this->options->get('directory'));
     }
     $name = $this->options->get('name');
     $config = $this->getConfig();
     if (!isset($config->database->adapter)) {
         throw new BuilderException('Adapter was not found in the config. Please specify a config variable [database][adapter].');
     }
     $adapter = 'Mysql';
     if (isset($config->database->adapter)) {
         $adapter = ucfirst($config->database->adapter);
         $this->isSupportedAdapter($adapter);
     }
     $di = new FactoryDefault();
     $di->set('db', function () use($adapter, $config) {
         if (is_object($config->database)) {
             $configArray = $config->database->toArray();
         } else {
             $configArray = $config->database;
         }
         $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
         unset($configArray['adapter']);
         return new $adapterName($configArray);
     });
     if (!isset($config->application->modelsDir)) {
         throw new BuilderException('The builder is unable to find the models directory.');
     }
     $modelPath = $config->application->modelsDir;
     if (false == $this->isAbsolutePath($modelPath)) {
         $modelPath = $this->path->getRootPath($config->application->modelsDir);
     }
     $this->options->offsetSet('modelsDir', rtrim($modelPath, '\\/') . DIRECTORY_SEPARATOR);
     if (!isset($config->application->controllersDir)) {
         throw new BuilderException('The builder is unable to find the controllers directory.');
     }
     $controllerPath = $config->application->controllersDir;
     if (false == $this->isAbsolutePath($controllerPath)) {
         $controllerPath = $this->path->getRootPath($config->application->controllersDir);
     }
     $this->options->offsetSet('controllersDir', rtrim($controllerPath, '\\/') . DIRECTORY_SEPARATOR);
     if (!isset($config->application->viewsDir)) {
         throw new BuilderException('The builder is unable to find the views directory.');
     }
     $viewPath = $config->application->viewsDir;
     if (false == $this->isAbsolutePath($viewPath)) {
         $viewPath = $this->path->getRootPath($config->application->viewsDir);
     }
     $this->options->offsetSet('viewsDir', $viewPath);
     $this->options->offsetSet('manager', $di->getShared('modelsManager'));
     $this->options->offsetSet('className', Text::camelize($this->options->get('name')));
     $this->options->offsetSet('fileName', Text::uncamelize($this->options->get('className')));
     $modelsNamespace = '';
     if ($this->options->contains('modelsNamespace') && $this->checkNamespace($this->options->get('modelsNamespace'))) {
         $modelsNamespace = $this->options->get('modelsNamespace');
     }
     $modelName = Text::camelize($name);
     if ($modelsNamespace) {
         $modelClass = '\\' . trim($modelsNamespace, '\\') . '\\' . $modelName;
     } else {
         $modelClass = $modelName;
     }
     $modelPath = $this->options->get('modelsDir') . $modelName . '.php';
     if (!file_exists($modelPath) || $this->options->get('force')) {
         $modelBuilder = new ModelBuilder(array('name' => $name, 'schema' => $this->options->get('schema'), 'className' => $this->options->get('className'), 'fileName' => $this->options->get('fileName'), 'genSettersGetters' => $this->options->get('genSettersGetters'), 'directory' => $this->options->get('directory'), 'force' => $this->options->get('force'), 'namespace' => $this->options->get('modelsNamespace')));
         $modelBuilder->build();
     }
     if (!class_exists($modelClass)) {
         require $modelPath;
     }
     $entity = new $modelClass();
     $metaData = $di['modelsMetadata'];
     $attributes = $metaData->getAttributes($entity);
     $dataTypes = $metaData->getDataTypes($entity);
     $identityField = $metaData->getIdentityField($entity);
     $primaryKeys = $metaData->getPrimaryKeyAttributes($entity);
     $setParams = array();
     $selectDefinition = array();
     $relationField = '';
     $single = $name;
     $this->options->offsetSet('name', strtolower(Text::camelize($single)));
     $this->options->offsetSet('plural', $this->_getPossiblePlural($name));
     $this->options->offsetSet('singular', $this->_getPossibleSingular($name));
     $this->options->offsetSet('modelClass', $modelClass);
     $this->options->offsetSet('entity', $entity);
     $this->options->offsetSet('setParams', $setParams);
     $this->options->offsetSet('attributes', $attributes);
     $this->options->offsetSet('dataTypes', $dataTypes);
     $this->options->offsetSet('primaryKeys', $primaryKeys);
     $this->options->offsetSet('identityField', $identityField);
     $this->options->offsetSet('relationField', $relationField);
     $this->options->offsetSet('selectDefinition', $selectDefinition);
     $this->options->offsetSet('autocompleteFields', array());
     $this->options->offsetSet('belongsToDefinitions', array());
     // Build Controller
     $this->_makeController();
     if ($this->options->get('templateEngine') == 'volt') {
         // View layouts
         $this->_makeLayoutsVolt();
         // View index.phtml
         $this->makeViewVolt('index');
         // View search.phtml
         $this->_makeViewSearchVolt();
         // View new.phtml
         $this->makeViewVolt('new');
         // View edit.phtml
         $this->makeViewVolt('edit');
     } else {
         // View layouts
         $this->_makeLayouts();
         // View index.phtml
         $this->makeView('index');
         // View search.phtml
         $this->_makeViewSearch();
         // View new.phtml
         $this->makeView('new');
         // View edit.phtml
         $this->makeView('edit');
     }
     return true;
 }
Esempio n. 18
0
$di->set('security', function () {
    $security = new Security();
    $security->setWorkFactor(12);
    return $security;
}, true);
/**
 * Mail Service.
 */
$di->set('mailSender', function () {
    return new MailSender();
});
/**
 * Localization Service.
 */
$di->set('localization', function () use($di, $config) {
    $languageDectorPlugin = new LanguageDectorPlugin();
    $session = $di->getShared('session');
    $request = $di->getShared('request');
    $language = $languageDectorPlugin->getCurrentLanguage($request, $session);
    $languageDir = APP_PATH . $config->application->languageDir;
    $languageFile = "{$languageDir}/{$language}.php";
    if (file_exists($languageFile)) {
        require $languageFile;
    } else {
        require "{$languageDir}/en.php";
    }
    return new TranslateArray(array("content" => $messages));
});
$di->set('languages', function () {
    return array('en' => 'English', 'zh' => '简体中文');
});