public function onKernelController(FilterControllerEvent $event) { $locale = null; $default_locale = null; $part_locale = Service::get('config')->get('app', 'local', null); if ($part_locale) { $part_locale = explode('_', $part_locale); $default_locale = $part_locale[0]; } $Request = $event->getRequest(); // Si en la sesion no existe _locale pregunta a la ruta encontrada si existe la opcion _locale if (!Service::get('session')->has('_locale')) { /** @var RouteCollection $RouteCollection */ $RouteCollection = Service::get('kernel.routes'); /** @var Route $Route */ $Route = $RouteCollection->get($Request->attributes->get('_route')); $locale = $Route->getOption('_locale'); // Si no la encuentra la optiene de la configuracion. if (!$locale) { $locale = $default_locale; } // Si no existe en la configuracion la obtiene de la peticion por defecto del componente. if (!$locale) { $locale = $Request->getDefaultLocale(); $default_locale = $Request->getDefaultLocale(); } // Asigna a la sesion la variable locale. Service::get('session')->set('_locale', $locale); Service::get('session')->set('_locale_default', $default_locale); } $Request->setLocale($locale); $Request->setDefaultLocale($default_locale); }
public function loader($locale = 'es_ES') { $Translator = new Translator($locale); $Translator->addLoader('array', new ArrayLoader()); $data = array(); $part_locale = explode('_', $locale); $bundles = Service::getBundles(); foreach ($bundles as $bundle) { $path_i18n = str_replace('\\', '/', $bundle->getPath() . '/i18n/' . $part_locale[0]); if (is_dir($path_i18n)) { $finder = new Finder(); $finder->files()->name('*.i18n.php')->in($path_i18n); // Une todos los esquemas en un solo array foreach ($finder as $file) { $_a = (require $file->getRealpath()); $data = array_merge($data, $_a); } } } $path_i18n = str_replace('\\', '/', Ki_APP . 'src/i18n/' . $part_locale[0]); if (is_dir($path_i18n)) { $finder = new Finder(); $finder->files()->name('*.i18n.php')->in($path_i18n); // Une todos los esquemas en un solo array foreach ($finder as $file) { $_a = (require $file->getRealpath()); $data = array_merge($data, $_a); } } $Translator->addResource('array', $data, $locale); $this->Translator = $Translator; }
public function onKernelException(GetResponseForExceptionEvent $event) { if (!(Ki_ENVIRONMENT == 'prod') || Ki_ENVIRONMENT == 'prod' && Ki_DEBUG === true) { // Si retorna muestra el error detallado. return; } $Exception = $event->getException(); $status = $Exception->getStatusCode(); $message = $Exception->getMessage(); /** * @var $view ViewBuilder */ $view = Service::get('view'); /** * @var $request Request */ $request = Service::get('new.request'); $request->setMethod('GET'); $request = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false); if (in_array($status, array(404))) { $content = $view->render('exceptions/error404', array('exception_message' => $message)); } else { if (in_array($status, array(401, 403))) { $content = $view->render('exceptions/error403', array('exception_message' => $message)); } else { if (in_array($status, array(409))) { $content = $view->render('exceptions/error409', array('exception_message' => $message)); } } } $request->setContent($content); // Envia la respuesta $event->setResponse($request); }
private function createDatabase($input, $output, $path_schema) { $fs = new Filesystem(); $dateTime = new \DateTime(); $output->write(PHP_EOL . " Actualizando la base de datos..." . PHP_EOL . PHP_EOL); if (!is_file($path_schema . '/schema.php')) { $output->writeln(" <error>ATENCION: El esquema no fue creado.</error>" . PHP_EOL); return; } $DriverManager = Service::get('database.manager')->getConnectionManager()->getConnection(); $sm = $DriverManager->getSchemaManager(); // Obtiene el esquema de la base de datos. $schema_current = $sm->createSchema(); // Se Obtiene el objeto del esquema creado. $schema = (include $path_schema . '/schema.php'); $comparator = new \Doctrine\DBAL\Schema\Comparator(); $schemaDiff = $comparator->compareSchemas($schema_current, $schema); $queries = $schemaDiff->toSql($DriverManager->getDatabasePlatform()); if (count($queries) == 0) { $output->writeln(PHP_EOL . " <info>No hay nada para actualizar.</info>"); return; } $_q = "set foreign_key_checks = 0;"; $DriverManager->query($_q); $output->writeln(PHP_EOL . " {$_q}" . PHP_EOL); foreach ($queries as $query) { $DriverManager->query($query); $output->writeln(" - {$query}"); } $_q = "set foreign_key_checks = 1;"; $output->writeln(PHP_EOL . " {$_q}" . PHP_EOL); $DriverManager->query($_q); $output->writeln("<info>La base de datos fue actualizada correctamente.</info>"); }
protected function execute(InputInterface $input, OutputInterface $output) { $namespace = $input->getArgument('namespace'); /** @var RouteCollection $RouteCollection */ $RouteCollection = Service::get('kernel.routes'); $Routes = $RouteCollection->all(); $io = new SymfonyStyle($input, $output); $io->newLine(); $rows = array(); /** @var Route $Route */ foreach ($Routes as $name => $Route) { $path = $Route->getPath(); $local = $Route->getOption('_locale'); $controller = $Route->getDefault('controller'); $host = $Route->getHost(); $methods = implode(', ', $Route->getMethods()); $schemes = implode(', ', $Route->getSchemes()); $_requirements = $Route->getRequirements(); $requirements = null; $name = $local ? str_replace("-{$local}", '', $name) : $name; foreach ($_requirements as $var => $patt) { $requirements .= "\"{$var}={$patt}\" "; } $requirements = $requirements ? rtrim($requirements, ',') : ''; $rows[] = array($name, $path, $local, $methods, $schemes); } $io->table(array('Name', 'Path', 'Local', 'Method', 'Scheme'), $rows); $io->success('Se han mostrado las rutas del proyecto exitosamente.'); }
public static function __callStatic($method, $args) { $instance = Service::get(static::getName()); if (!method_exists($instance, $method)) { throw new \Exception(get_called_class() . ' does not implement ' . $method . ' method.'); } return call_user_func_array(array($instance, $method), $args); }
public function console() { $cli = new Application('======= Kodazzi - Lista de Comandos ======='); $cli->add(Service::get('command.schema')); $cli->add(Service::get('command.database')); $cli->add(Service::get('command.model')); $cli->add(Service::get('command.form')); $cli->add(Service::get('command.bundle')); $cli->add(Service::get('command.routes')); $cli->run(); }
public function renderField() { if (!$this->is_display) { return ''; } $format = $this->format ? $this->format : $this->name_form . '[' . $this->name . ']'; $id = $this->id ? $this->id : $this->name_form . '_' . $this->name; $options = $this->options; if (count($options) == 0) { $options = Service::get('database.manager')->model($this->name_model_relation)->getForOptions(); } return \Kodazzi\Helper\FormHtml::select($format, $options, $this->value, null, array('id' => $id, 'class' => $this->getClassCss(), 'disabled' => $this->isDisabled(), 'readonly' => $this->isReadonly())); }
public function saveRelation($last_id) { $definition = $this->definition; $values = $this->value; /** * @var $db DatabaseManager */ $db = Service::get('database.manager'); $ConnectionOptions = $db->getConnectionManager()->getConnectionOptions(); $db->getQueryBuilder()->where("{$definition['localField']}={$last_id}")->delete("{$ConnectionOptions['prefix']}{$definition['tableManyToMany']}")->execute(); foreach ($values as $value) { $db->getQueryBuilder()->values(array($definition['localField'] => $last_id, $definition['foreignField'] => $value))->insert("{$ConnectionOptions['prefix']}{$definition['tableManyToMany']}")->execute(); } }
public function __construct($instance_model = null) { $this->I18n = Service::get('translator'); // token para campo csrf del form $this->csrf_token = sha1(get_class($this)); // Nombre de la clase formulario $this->name_form = basename(str_replace('\\', '/', get_class($this))); // Llama a config() de la clase base $this->config(); // Llama a change() de la clase extends de base $this->change(); // Crea el widget para seguridad de ataque csrf $this->setWidget('csrf_token', new \Kodazzi\Form\Fields\Csfr())->setValue($this->csrf_token); $this->setModel($instance_model); }
private function createSchema($input, $output, $path_schema, $schema, $behavior) { $GenerateClass = Service::get('generate_class'); $connectionOptions = Service::get('config')->get('db', 'dev'); $connectionOptions = array_key_exists('default', $connectionOptions) ? $connectionOptions['default'] : current($connectionOptions); $prefix = array_key_exists('prefix', $connectionOptions) ? $connectionOptions['prefix'] : ''; $helper = $this->getHelper('question'); $fs = new Filesystem(); $dateTime = new \DateTime(); $output->write(PHP_EOL . " Creando el esquema..." . PHP_EOL . PHP_EOL); if ($behavior != 'overwrite' && is_file($path_schema . 'current/schema.php')) { $question = new ConfirmationQuestion(' <question>Ya existe una version del esquema, desea reemplazarlo [n]?</question> ', false); if (!$helper->ask($input, $output, $question)) { $output->writeln(" <error>ATENCION: El esquema no fue creado.</error>" . PHP_EOL); return; } } // Crea el directorio src/storage/schema/current $this->mkdir($path_schema . 'current'); // vuelca el arreglo PHP a YAML $dumper = new Dumper(); $content_yaml = $dumper->dump($schema); // Crea el archivo yml dentro de src/storage/schema/current. $fs->dumpFile($path_schema . 'current/schema.yml', $content_yaml); $output->writeln(PHP_EOL . " <info>- Se genero el archivo schema.yml correctamente.</info>"); // Crea el archivo yml dentro de src/storage/schema/current. $content_readme = 'Creado: ' . $dateTime->format('Y-m-d H:i:s'); $fs->dumpFile($path_schema . 'current/readme.md', $content_readme); $output->writeln(" <info>- Se genero el archivo readme.md correctamente.</info>"); $GenerateClass->setTemplate('Doctrine'); $GenerateClass->setValues(array('_prefix' => $prefix)); $GenerateClass->create($path_schema . 'current/schema', $schema); $output->writeln(" <info>- Se genero el archivo schema.php correctamente.</info>"); // Se Obtiene el objeto del esquema creado. $schema = (include $path_schema . 'current/schema.php'); // Se crea el archivo .sql que contendra la estructura del esquema para la base de datos. $querys = $schema->toSql(Service::get('database.manager')->getConnectionManager()->getConnection()->getDatabasePlatform()); $sql = ""; foreach ($querys as $query) { $sql .= "{$query};\n"; } $fs->dumpFile($path_schema . 'current/database.sql', $sql); $output->writeln(" <info>- Se genero el archivo database.sql correctamente.</info>"); $output->writeln(PHP_EOL . " <info>EL esquema fue creado correctamente en: " . Ki_SYSTEM . "app/src/storage/schemas/current/</info>"); }
<?php /** * This file is part of the Kodazzi Framework. * * (c) Jorge Gaitan <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Kodazzi\Container\Service; Service::Routing()->add('homepage')->path('/')->controller('Kodazzi\\Site:Welcome:index')->ok();
private function createFormsI18n($input, $output, $bundle, $schema) { $GenerateClass = Service::get('generate_class'); $path = Ki_BUNDLES . $bundle . '/i18n/es/'; /* Crea el directorio donde se crearan las clases de los formularios */ $this->mkdir($path); $output->write(PHP_EOL . "Lista de archivos catalogo de tranduccion para los formularios:" . PHP_EOL); foreach ($schema as $table => $options) { if (strpos($table, ':')) { $p = explode(':', $table); $table = $p[1]; } // Para evitar sobreescribir el archivo if (!is_file($path . ucfirst($table) . 'Form.i18n.php')) { $GenerateClass->setTemplate('FormI18n'); $GenerateClass->setValues(array('form' => ucfirst($table) . 'Form')); $GenerateClass->create($path . ucfirst($table) . 'Form.i18n', $options); $output->write(" - Archivo Traduccion '" . ucfirst($table) . "Form.i18n' fue creada correctamente." . PHP_EOL); } } $output->write(PHP_EOL . PHP_EOL); }
public function validate($data) { $type = strtoupper(basename(str_replace('\\', '/', get_class($this)))); // No se valida los campos FILE o IMAGEN que estan vacios y son de un objeto viejo // En este punto no se actualiza el valor del campo y se utiliza facilmente en save() if ($type == 'FILE' || $type == 'IMAGE') { if (!$this->form->isNew() && ($data == '' || $data == null)) { return true; } } /* Todos los campos menos Editor, File, Image y Table - se valida el minimo y maximo de caracteres */ if (!in_array($type, array('EDITOR', 'FILE', 'IMAGE', 'TABLE'))) { if ($this->max_length && strlen($data) > $this->max_length) { $msg = !$this->msg_max_length ? $this->I18n->get('form.max_length', 'Is Invalid.') : $this->msg_max_length; $this->msg_error = strtr($msg, array('%name%' => $this->getValueLabel(), '%max%' => $this->max_length)); return false; } if ($this->min_length && strlen($data) < $this->min_length) { $msg = !$this->msg_min_length ? $this->I18n->get('form.min_length', 'Is Invalid.') : $this->msg_min_length; $this->msg_error = strtr($msg, array('%name%' => $this->getValueLabel(), '%min%' => $this->min_length)); return false; } } // Envia el valor para ser procesado por le metodo valid() de cada campo $this->value = $data; // Llama al validador del widget if (!$this->valid()) { $this->msg_error = $this->msg_error ? $this->msg_error : $this->I18n->get('form.' . strtolower($type), 'Is Invalid.'); $this->value = null; return false; } if ($this->is_unique) { /** * @var $db Model */ $Model = Service::get('database.manager')->model($this->form->getNameModel()); if ($this->form->isNew()) { $exist = $Model->where($this->name, '=', $this->value)->exist(); } else { $instanceModelo = $this->form->getModel(); $fieldPrimary = $instanceModelo::primary; $exist = $Model->where($this->name, '=', $this->value)->andWhere($fieldPrimary, '<>', $instanceModelo->{$fieldPrimary})->exist(); } if ($exist) { $this->msg_error = $this->I18n->get('form.unique', 'Is unique.'); return false; } } // Si pasa las validaciones transforma la data para evitar inyeccion sql if (!in_array($type, array('EDITOR', 'NOTE', 'FILE', 'IMAGE', 'FOREIGN', 'TABLE'))) { $this->value = htmlentities($this->value, ENT_QUOTES, 'UTF-8'); } return true; }
public function generateModels($input, $output, $schema, $bundle) { $GenerateClass = Service::get('generate_class'); $output->write(PHP_EOL . "Lista de clases para el modelo:" . PHP_EOL); $this->mkdir(Ki_BUNDLES . $bundle . '/Models/Base/'); foreach ($schema as $table => $options) { if (strpos($table, ':')) { $p = explode(':', $table); $table = $p[1]; } if (!is_file(Ki_BUNDLES . $bundle . '/Models/' . ucfirst($table) . 'Model.php')) { $GenerateClass->setTemplate('Model'); $GenerateClass->setNameClass(ucfirst($table) . 'Model'); $GenerateClass->setNamespace(ucfirst(str_replace('/', '\\', $bundle)) . '\\Models'); $GenerateClass->setNameClassExtend('Base\\' . ucfirst($table) . 'ModelBase'); $GenerateClass->create(Ki_BUNDLES . $bundle . '/Models/' . ucfirst($table) . 'Model', $options); $output->write(" - Clase Model {$table} del Bundle {$bundle}, fue creada correctamente." . PHP_EOL); } $options['package'] = $bundle; $GenerateClass->setTemplate('BaseModel'); $GenerateClass->setNameClass(ucfirst($table) . 'ModelBase'); $GenerateClass->setNamespace(ucfirst(str_replace('/', '\\', $bundle)) . '\\Models\\Base'); $GenerateClass->setValues(array('namespace_bundle' => ucfirst(str_replace('/', '\\', $bundle)), 'model' => ucfirst($table))); $GenerateClass->create(Ki_BUNDLES . $bundle . '/Models/Base/' . ucfirst($table) . 'ModelBase', $options); $output->write(" - Clase Model Base{$table} del Bundle {$bundle}, fue creada correctamente." . PHP_EOL); } $output->write(PHP_EOL . PHP_EOL); }
public static function buildUrl($name, $parameters = array(), $locale = null) { if ($name == '@default' || preg_match('/^(\\@default)/', $name)) { foreach ($parameters as $key => $parameter) { $parameters[$key] = strtolower(preg_replace('/[^A-Z^a-z^0-9^\\:]+/', '-', preg_replace('/([a-z\\d])([A-Z])/', '\\1_\\2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', str_replace(array('/', '\\'), ':', $parameter))))); } } // Forza la url para generarla desde una lenguaje especifico if ($locale) { $name = "{$name}-{$locale}"; } else { $locale = $locale ? $locale : Service::get('session')->getLocale(); // Primero intenta encontrar la ruta concatenada con el lenguaje actual $Route = Service::get('kernel.routes')->get("{$name}-{$locale}"); if ($Route) { $name = "{$name}-{$locale}"; } } return Service::get('kernel.url_generator')->generate($name, $parameters); }
protected function execute(InputInterface $input, OutputInterface $output) { $path_schema = Ki_APP . 'src/storage/schemas/'; $action = $input->getArgument('action'); $namespace = $input->getArgument('namespace'); $yaml = new Parser(); if (!in_array($action, array('create', 'delete'))) { $output->writeln(PHP_EOL . 'El parametro "action" debe ser create o delete. Por defecto es create.' . PHP_EOL); exit; } switch (strtoupper($action)) { case 'CREATE': if (is_dir(Ki_BUNDLES . $namespace)) { $output->writeln(PHP_EOL . 'Ya existe un bundle con el mismo espacio de nombre.' . PHP_EOL); exit; } // Crea el directorio config/ $this->mkdir(Ki_BUNDLES . $namespace . '/config/schema'); // Crea el directorio Controllers/ $this->mkdir(Ki_BUNDLES . $namespace . '/Controllers'); // Crea el directorio i18n/ $this->mkdir(Ki_BUNDLES . $namespace . '/i18n'); // Crea el directorio Main/ $this->mkdir(Ki_BUNDLES . $namespace . '/Main'); // Crea el directorio Providers/ $this->mkdir(Ki_BUNDLES . $namespace . '/Providers'); // Crea el directorio Services/ $this->mkdir(Ki_BUNDLES . $namespace . '/Services'); // Crea el directorio vies/ $this->mkdir(Ki_BUNDLES . $namespace . '/views/home'); $GenerateClass = Service::get('generate_class'); // Crea la clase HomeController $GenerateClass->setTemplate('Controller'); $GenerateClass->setValues(array('bundle' => str_replace('/', '\\', $namespace))); $GenerateClass->create(Ki_BUNDLES . $namespace . '/Controllers/HomeController'); // Crea la clase BundleController $GenerateClass->setTemplate('BundleController'); $GenerateClass->setValues(array('bundle' => str_replace('/', '\\', $namespace))); $GenerateClass->create(Ki_BUNDLES . $namespace . '/Main/BundleController'); // Crea las rutas del bundle $GenerateClass->setTemplate('routes'); $GenerateClass->setValues(array('bundle' => str_replace('/', '\\', $namespace), 'route' => str_replace(array('/', '\\'), '-', strtolower($namespace)))); $GenerateClass->create(Ki_BUNDLES . $namespace . '/config/routes.cf'); // Crea la plantilla index.twig $GenerateClass->setTemplate('index'); $GenerateClass->create(Ki_BUNDLES . $namespace . '/views/home/index', array(), '.twig'); // Crea el HookBundle $GenerateClass->setTemplate('HookBundle'); $GenerateClass->setValues(array('namespace' => str_replace('/', '\\', $namespace))); $GenerateClass->create(Ki_BUNDLES . $namespace . '/HookBundle'); \Kodazzi\Tools\Util::bundle($namespace, 'new'); $output->writeln(PHP_EOL . 'El bundle ' . str_replace('/', '\\', $namespace) . ' ha sido creado con exito' . PHP_EOL); exit; break; case 'DELETE': if (!is_dir(Ki_BUNDLES . $namespace)) { $output->writeln(PHP_EOL . 'No se ha encontrado el bundle' . PHP_EOL); exit; } \Kodazzi\Tools\Util::bundle($namespace, 'delete'); $output->writeln(PHP_EOL . 'El bundle ' . str_replace('/', '\\', $namespace) . ' ha sido eliminado con exito' . PHP_EOL); break; } }
public function ok() { $routes = Service::get('kernel.routes'); $paths = $this->paths; foreach ($paths as $path) { $name = $this->name; if (!preg_match('/^(\\@default)/', $name) && !isset($this->default['controller'])) { throw new \Exception("En la ruta '{$name}'' debe agregar un controlador."); } if ($path['lang']) { $this->options['_locale'] = $path['lang']; $name .= "-{$path['lang']}"; } $routes->add("{$name}", new Route($path['path'], $this->default, $this->requirements, $this->options, $this->host, $this->schemes, $this->methods)); } $this->name = null; $this->paths = array(); $this->controler = null; $this->default = array(); $this->requirements = array(); $this->options = array(); $this->host = null; $this->schemes = array(); $this->methods = array(); }
public function __construct(ConfigBuilderInterface $config, SessionInterface $user, UrlGenerator $url_generator) { $this->User = $user; $this->Config = $config; $this->UrlGenerator = $url_generator; $bundles = Service::getBundles(); $theme_web = $config->get('app', 'theme_web'); $theme_admin = $config->get('app', 'theme_admin'); $enabled_path_themes = $config->get('app', 'enabled_path_themes'); $path_templates = array(Ki_APP . 'src/layouts', Ki_APP . 'src/templates'); if ($enabled_path_themes) { if (is_dir(Ki_THEMES . $theme_web . '/layouts')) { $path_templates[] = Ki_THEMES . $theme_web . '/layouts'; } if (is_dir(Ki_THEMES . $theme_web . '/templates')) { $path_templates[] = Ki_THEMES . $theme_web . '/templates'; } if (is_dir(Ki_THEMES . $theme_admin . '/layouts')) { $path_templates[] = Ki_THEMES . $theme_admin . '/layouts'; } if (is_dir(Ki_THEMES . $theme_admin . '/templates')) { $path_templates[] = Ki_THEMES . $theme_admin . '/templates'; } } foreach ($bundles as $bundle) { $path_bundles_templates = str_replace('\\', '/', $bundle->getPath() . '/templates'); if (is_dir($path_bundles_templates)) { $path_templates[] = $path_bundles_templates; } } $Twig_Loader_Filesystem = new \Twig_Loader_Filesystem($path_templates); $Twig = new \Twig_Environment(null, array('cache' => Ki_CACHE . 'views', 'debug' => Ki_DEBUG)); // Funcion para construir las url $build_url = new \Twig_SimpleFunction('build_url', function ($name_route, $parameters = array(), $locale = null) { return \Kodazzi\Tools\Util::buildUrl($name_route, $parameters, $locale); }); // Funcion para construir las url $cut_text = new \Twig_SimpleFunction('cut_text', function ($string, $limit = 100, $end_char = '...') { return \Kodazzi\Tools\StringProcessor::cutText($string, $limit, $end_char); }); // Funcion para cortar texto muy largo. $resume = new \Twig_SimpleFunction('resume', function ($string, $limit = 100, $end_char = '...') { return \Kodazzi\Tools\StringProcessor::resume($string, $limit, $end_char); }); // Funcion para dar formato a un numero $number_format = new \Twig_SimpleFunction('number_format', function ($number, $decimals = 0, $dec_point = ',', $thousands_sep = '.') { return number_format($number, $decimals, $dec_point, $thousands_sep); }); // Funcion para dar formato a un numero $date_format = new \Twig_SimpleFunction('date_format', function ($date, $format) { return \Kodazzi\Tools\Date::format($date, $format); }); // Funcion para dar formato a un numero $get_date = new \Twig_SimpleFunction('get_date', function ($string) { return \Kodazzi\Tools\Date::getDate($string); }); // Funcion para indicar si existe un archivo $isFile = new \Twig_SimpleFunction('isFile', function ($path, $file) { return \Kodazzi\Tools\Util::isFile($path, $file); }); // Funcion para indicar si existe un archivo $hash = new \Twig_SimpleFunction('hash', function ($id, $str = 'z6i5v36h3F5', $position = 5, $prefix = '') { return \Kodazzi\Tools\Util::hash($id, $str, $position, $prefix); }); // Funcion para indicar si existe un archivo $ucfirst = new \Twig_SimpleFunction('ucfirst', function ($string) { return ucfirst($string); }); // Funcion para acceder al catalogo de traduccion. $i18n = new \Twig_SimpleFunction('i18n', function ($string) { return Service::get('translator')->get($string); }); // Funcion para indicar si existe un archivo $dump = new \Twig_SimpleFunction('dump', function ($var) { ob_start(); var_dump($var); $a = ob_get_contents(); ob_end_clean(); return $a; }); $Twig->addFunction($build_url); $Twig->addFunction($cut_text); $Twig->addFunction($get_date); $Twig->addFunction($resume); $Twig->addFunction($number_format); $Twig->addFunction($isFile); $Twig->addFunction($date_format); $Twig->addFunction($hash); $Twig->addFunction($ucfirst); $Twig->addFunction($i18n); $Twig->addFunction($dump); $this->Twig_Loader_Filesystem = $Twig_Loader_Filesystem; $this->Twig = $Twig; }
public function save() { $data = $this->data; $widget_many = array(); if ($this->is_valid) { $widgets = $this->getWidgets(); // Elimina el campo de verificacion csfr del formulario unset($data['csrf_token']); $files_uploads = $this->files_uploads; foreach ($files_uploads as $field => $widget) { $widget->doUpload(); } // Se limpia el atributo con lo archivos para subir $this->files_uploads = array(); // Si no existen valores para guardar returna false // Esta verificacion se debe hacer despues de eliminar el campo csrf_token if (count($data) == 0) { return false; } /** * @var $db DatabaseManager */ $db = Service::get('database.manager'); // Si el objeto es nuevo lo crea $instance = $this->isNew() ? new $this->name_model() : $this->model; foreach ($widgets as $field => $widget) { if (is_object($widget)) { if ($widget->hasMany()) { $widget_many[] = $widget; } else { if (array_key_exists($field, $data)) { // Si el campo debe ir vacio se asigna null para que no tenga problemas al ejecutar el query $instance->{$field} = $data[$field] == '' ? null : $data[$field]; } } } } try { $ok = $db->save($instance); } catch (Exception $e) { $this->msg_global_error = $this->I18n->get('form.form_internal', 'Internal Error'); } if (!$ok) { return false; } $this->identifier = $db->getIdentifier(); $this->instance = $instance; if (count($widget_many)) { foreach ($widget_many as $_widget) { $_widget->saveRelation($this->identifier); } } if (array_key_exists('translation', $widgets) && is_array($widgets['translation']) && $this->is_translatable) { $namespaceInstace = $this->getNameModel(); $instaceModel = new $namespaceInstace(); // Obtiene todos los registros de lenguage de la bd $languages = Service::get('database.manager')->model($instaceModel::modelLanguage)->getForOptions("a.code, a.id"); foreach ($widgets['translation'] as $lang => $translation) { if (array_key_exists($lang, $languages)) { $translation['form']->setData('language_id', $languages[$lang]); $translation['form']->setData('translatable_id', $this->identifier); $translation['form']->save(); } } } return true; } return false; }
/** * @return DatabaseManager */ public function getDatabaseManager() { return Service::get('database.manager'); }