/** * We will get all column schema from database. * * @return mixed */ public function getColumns() { $table = $this->table->connect($this->database, Inflector::tabilize($this->model)); return $table->{__FUNCTION__}(); }
/** * @param null $number * @return $this */ public function setTotalNumberOfPage($number = null) { if (is_null($number)) { $modelClass = Inflector::getClassNameFromNamespace(get_class($this->model)); $table = Inflector::tabilize($modelClass); $numRecords = $this->model->select($this->count() . " AS " . $this->numCount)->findMany(); $this->totalNumOfPage = $numRecords[0]->{$this->numCount}; return $this; } $this->totalNumOfPage = $number; return $this; }
/** * You cannot create an instance of Schema class * directly * * @param $model */ protected function __construct($model) { $this->klass = $model; if (class_exists(get_class($this->klass))) { $reflectionClass = new \ReflectionClass(get_class($this->klass)); /* | We will set the database connection name here */ if (property_exists($this->klass, 'database')) { $reflectionProperty = $reflectionClass->getProperty('database'); $reflectionProperty->setAccessible(true); $this->database = $reflectionProperty->getValue($this->klass); } else { $this->database = $this->getDefaultConnection(); } /* | We will set the primary key of the table schema */ if (property_exists($this->klass, 'primaryKey')) { $reflectionPropertyKey = $reflectionClass->getProperty('primaryKey'); $reflectionPropertyKey->setAccessible(true); $this->primaryKey = $reflectionPropertyKey->getValue($this->klass); } /* | Set database connection name */ $this->setDatabaseConnection($this->database); if (!property_exists($this->klass, 'tableName')) { $this->tableName = Inflector::tabilize(get_class($this->klass)); } } }
/** * Get the Queued message and return it * * @param string $key * @return mixed * */ public function getFlash($key = null) { $messages = $flash = ''; if (!Session::has('flashMessages')) { return false; } $flashArray = Session::get('flashMessages'); // Check $key is valid flash type if (in_array($key, $this->validFlashTypes)) { if (isset($flashArray[$key])) { foreach ($flashArray[$key] as $msg) { $messages .= '<p>' . $msg . "</p>\n"; } } $flash .= sprintf($this->flashWrapper, strtolower(Inflector::getClassName($this->class)), $key, $messages); // clear the viewed messages from browser $this->clearViewedMessages($key); // Print ALL queued messages } elseif (is_null($key)) { foreach ($flashArray as $key => $msgArray) { $messages = ''; foreach ($msgArray as $msg) { $messages .= '<p>' . $msg . "</p>\n"; } $flash .= sprintf($this->flashWrapper, strtolower($this->class), $key, $messages); } // clear already viewed messages $this->clearViewedMessages(); // Invalid message type } else { return false; } return $flash; }
private function replaceModelTemplate($content) { $content = str_replace('%StaticModelName%', $this->command->getModel(), $content); $primaryKey = $this->command->table()->getPrimaryKey(); $content = str_replace('{%Apps%}', APP_NS, $content); $content = str_replace('{%primaryKey%}', $primaryKey, $content); $content = str_replace('%modelName%', Inflector::tabilize($this->command->getModel()), $content); $content = str_replace('%databaseName%', $this->command->getDatabase(), $content); $content = str_replace('{%rules%}', $this->replaceValidationRules(), $content); return $content; }
/** * We will register user defined events, it will trigger event when matches. * * @param $events * * @throws \RuntimeException */ public function registerEvents($events) { if (empty($events)) { throw new \RuntimeException(sprintf('Empty argument passed %s', __FUNCTION__)); } foreach ($events as $event => $namespace) { $parts = explode('@', $namespace); // attach all before and after event to handler $this->attach("{$event}.before", $parts[0] . '@before' . ucfirst(Inflector::pathAction(end($parts))))->attach("{$event}", $parts[0] . '@' . Inflector::pathAction(end($parts)))->attach("{$event}.after", $parts[0] . '@after' . ucfirst(Inflector::pathAction(end($parts)))); } }
/** * We will execute the crud command and generate files * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { /** Check for argument database name if not given we will use default * database connection */ $this->database = !is_null($input->getArgument('database')) ? $input->getArgument('database') : $this->tableSchema->getDefaultDatabaseConnection(); $this->table = !is_null($input->getArgument('name')) ? $input->getArgument('name') : 'Form'; $this->columns = $this->getColumns(); $this->applicationDir = CYGNITE_BASE . DS . APPPATH; $this->generateForm(); $output->writeln("<info>Form " . APPPATH . "/components/form/" . Inflector::classify($this->table) . "Form" . EXT . " Generated Successfully By Cygnite Cli.</info>"); }
/** * Set all definitions into array * @param $propertyInjections * @throws \Exception */ public function setPropertyInjection($propertyInjections) { if (!is_array($propertyInjections)) { throw new \Exception(__METHOD__ . " only accept parameter as array."); } foreach ($propertyInjections as $controller => $properties) { foreach ($properties as $key => $value) { $classInstance = Inflector::toNamespace($value); $this->definitions["\\" . ucfirst(APPPATH) . $this->namespace . $controller][$key] = new $classInstance(); } } }
/** * We will execute the controller command and generate classes * * @param InputInterface $input * @param OutputInterface $output * @throws \Exception * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { // Your controller name $this->controller = Inflector::classify($input->getArgument('name')) . 'Controller'; // By default we will generate basic controller, if resource set then we will generate // REST-ful Resource controller $this->setControllerType($input); try { $this->makeController(); } catch (\Exception $e) { throw $e; } $output->writeln('<info>Controller ' . $this->controller . ' Generated Successfully By Cygnite Cli.</info>'); }
/** * We will execute the controller command and generate classes * * @return mixed|void * @throws \Exception */ public function process() { // Your controller name $this->controller = Inflector::classify($this->argument('name')) . 'Controller'; // By default we will generate basic controller, if resource set then we will generate // REST-ful Resource controller $this->setControllerType(); try { $this->makeController(); } catch (\Exception $e) { throw $e; } $this->info('Controller ' . $this->controller . ' Generated Successfully By Cygnite Cli.'); }
/** * We will inject interface implementation * * @param $reflectionParam * @return array */ public function interfaceInjection($reflectionParam) { $constructorArgs = null; /* | Check if constructor dependency is Interface or not. | if interface we will check definition for the interface | and inject into controller constructor */ if (!$reflectionParam->IsInstantiable() && $reflectionParam->isInterface()) { $aliases = $this['definition.config']['register.alias']; $interface = Inflector::getClassName($reflectionParam->getName()); if (array_key_exists($interface, $aliases)) { $constructorArgs = $this->makeInstance($aliases[$interface]); } } return $constructorArgs; }
/** * Generate Form */ public function generate() { $filePath = ''; $formName = Inflector::classify($this->formCommand->table); if (file_exists($this->getFormTemplatePath() . 'Form' . EXT)) { //We will generate Form Component $formContent = file_get_contents($this->getFormTemplatePath() . 'Form' . EXT); } else { die("Form template doesn't exists in " . $this->getFormTemplatePath() . 'Form' . EXT . " directory."); } $this->controller->isFormGenerator = true; $this->controller->updateTemplate(); $this->controller->controller = $formName; $this->controller->applicationDir = CYGNITE_BASE . DS . APPPATH; $formContent = str_replace('%controllerName%', $formName, $formContent); $formContent = str_replace('{%formElements%}', $this->controller->getForm() . PHP_EOL, $formContent); $this->controller->generateFormComponent($formContent); }
/** * All static methods will get resolve by Proxy Resolver * * @param $method * @param array $arguments * @return mixed */ public static function __callStatic($method, $arguments = array()) { $accessor = $instance = null; $accessor = static::getResolver(); $accessor = Inflector::toNamespace($accessor); $instance = new $accessor(); // calling the method directly is faster then call_user_func_array() ! switch (count($arguments)) { case 0: return $instance->{$method}(); case 1: return $instance->{$method}($arguments[0]); case 2: return $instance->{$method}($arguments[0], $arguments[1]); case 3: return $instance->{$method}($arguments[0], $arguments[1], $arguments[2]); case 4: return $instance->{$method}($arguments[0], $arguments[1], $arguments[2], $arguments[3]); default: return call_user_func_array(array($instance, $method), $arguments); } }
/** * You cannot create an instance of Schema class * directly. * * @param $model * @param null $database * * @throws \ErrorException */ protected function __construct($model = null, $database = null) { if (!is_null($model) && is_object($model)) { $this->klass = $model; if (!class_exists(get_class($this->klass))) { throw new \ErrorException(sprintf("Class %s doesn't exists", get_class($this->klass))); } $reflectionClass = new \ReflectionClass(get_class($this->klass)); /* | We will set the database connection name here */ if (property_exists($this->klass, 'database')) { $reflectionProperty = $reflectionClass->getProperty('database'); $reflectionProperty->setAccessible(true); $database = $reflectionProperty->getValue($this->klass); } // If table name not provided we will format and consider class name as table if (!property_exists($this->klass, 'tableName')) { $model = Inflector::tabilize(get_class($this->klass)); } } $this->setDatabase(!is_null($database) ? $database : $this->getDefaultConnection()); $this->setTableName($model); }
/** * @param $controller * @param $action * @return mixed */ protected function setDeleteRoute($controller, $action) { return $this->mapRoute("/{$controller}/{$action}/{:id}/", Inflector::classify($controller) . '@' . $action); }
/** * @param $key * @return string */ private function convertToFieldName($key) { return Inflector::underscoreToSpace($key); }
public function getPlainUri($name, $prefix) { return $prefix . '/' . implode('-', array_slice(explode('_', Inflector::deCamelize($name)), 1)); }
/** * Covert dash-dot to namespace * * @param $key * @return string */ public function toNamespace($key) { $class = null; $class = explode('.', $key); $class = array_map('ucfirst', Inflector::instance()->classify($class)); $class = '\\' . implode('\\', $class); return $class; }
/** * Render twig templates * * @param $view * @param array $param * @param bool $return * @return $this */ public function template($view, array $param = [], $return = false) { $this->setTwigEnvironment(); $path = $this->getPath(Inflector::toDirectorySeparator($view), true); /* | We will check if tpl is holding the object of | twig, then we will set twig template | environment */ if (is_object(static::$twigEnvironment) && is_file($path)) { $this->setTwigTemplateInstance($view); } /* | We will check is twig template instance exists | then we will render twig template with parameters */ if (is_object(static::$twigEnvironment) && is_object($this['twig_template'])) { return $return ? $this['twig_template']->render($param) : $this['twig_template']->display($param); } return $this; }
/** * @return mixed */ public function getTotalNumberOfPages() { $numRecords = null; $modelClass = Inflector::getClassNameFromNamespace(get_class($this->model)); $table = Inflector::tabilize($modelClass); $numRecords = $this->model->query("SELECT " . $this->count() . " as " . $this->numCount . " FROM `" . $table . "`")->getAll(); return $numRecords[0]->{$this->numCount}; }
/** * Resolve all dependencies of your class and return instance of * your class * * @param $class string * @throws \Exception * @return object */ public function make($class) { $reflection = new Reflection(); $reflection->setClass($class); if (false === $reflection->reflectionClass->isInstantiable()) { throw new DependencyException("Cannot instantiate " . ($reflection->reflectionClass->isInterface() ? 'interface' : 'class') . " '{$class}'"); } $constructor = null; $constructorArgsCount = ''; if ($reflection->reflectionClass->hasMethod('__construct')) { $constructor = $reflection->reflectionClass->getConstructor(); $constructorArgsCount = $constructor->getNumberOfParameters(); $constructor->setAccessible(true); } // if class does not have explicitly defined constructor or constructor does not have parameters // get the new instance if (!isset($constructor) && is_null($constructor) || $constructorArgsCount < 1) { $this->stack[$class] = $reflection->reflectionClass->newInstance(); } else { $dependencies = $constructor->getParameters(); $constructorArgs = array(); foreach ($dependencies as $dependency) { if (!is_null($dependency->getClass())) { //Get constructor class name $resolveClass = $dependency->getClass()->name; $reflectionParam = new ReflectionClass($resolveClass); // Application and Container cannot be injected into controller currently // since Application constructor is protected if ($reflectionParam->IsInstantiable()) { $constructorArgs[] = $this->makeInstance($resolveClass); } /* | Check if constructor dependency is Interface or not. | if interface we will check definition for the interface | and inject into controller constructor */ if (!$reflectionParam->IsInstantiable() && $reflectionParam->isInterface()) { $definition = $this->getDefinition(); $aliases = $definition()->registerAlias(); $interface = Inflector::getClassName($reflectionParam->getName()); if (array_key_exists($interface, $aliases)) { $constructorArgs[] = $this->makeInstance($aliases[$interface]); } } } else { /* | Check parameters are optional or not | if it is optional we will set the default value */ if ($dependency->isOptional()) { $constructorArgs[] = $dependency->getDefaultValue(); } } } $this->stack[$class] = $reflection->reflectionClass->newInstanceArgs($constructorArgs); } return $this->stack[$class]; }
/** * Resolve the class. We will create and return instance if already * not exists. * * @param $class * @param array $arguments * * @return object */ public function resolve($class, $arguments = []) { $class = Inflector::toNamespace($class); return $this->make($class, $arguments); }
/** * Quote a string that is used as an identifier * (table names, column names etc) or an array containing * multiple identifiers. This method can also deal with * dot-separated identifiers eg table.column */ protected function quoteIdentifier($identifier) { if (is_array($identifier)) { $result = array_map(array($this, 'quoteOneIdentifier'), $identifier); return join(', ', $result); } else { return Inflector::tabilize($this->quoteOneIdentifier(lcfirst($identifier))); } }
/** * The finder make use of __callStatic() to invoke * undefined static methods dynamically. This magic method is mainly used * for dynamic finders * * @param $method String * @param $arguments array * @return object * */ public static function __callStatic($method, $arguments) { $params = []; $class = self::model(); switch ($method) { case substr($method, 0, 6) == 'findBy': if (strpos($method, 'And') !== false) { return self::callFinderBy($method, $class, $arguments, 'And'); // findByAnd } if (strpos($method, 'Or') !== false) { return self::callFinderBy($method, $class, $arguments, 'Or'); // findByOr } $columnName = Inflector::tabilize(substr($method, 6)); $operator = isset($arguments[1]) ? $arguments[1] : '='; $params = [$columnName, $operator, $arguments[0]]; return self::model()->query()->find('findBy', $params); break; case 'joinWith': return static::$ar->joinWith($class, $arguments); break; } //Use the power of PDO methods directly via static functions return static::callDynamicMethod([self::model()->query()->resolveConnection(), $method], $arguments); }
/** * Set controller and method name here * @param $arguments */ private function setUpControllerAndMethodName($arguments) { $expression = Helper::stringSplit($arguments[0]); $this->controller = Inflector::instance()->classify($expression[0]) . 'Controller'; $this->controllerWithNS = $this->namespace . $this->controller; $this->method = Inflector::instance()->toCameCase($expression[1]) . 'Action'; }
/** * @param $actionName * @return string */ public function getActionName($actionName) { return Inflector::camelize(!isset($actionName) ? 'index' : $actionName) . 'Action'; }
/** * We will get all column schema from database. * * @return mixed */ private function getColumns() { $table = $this->table->connect($this->database, Inflector::tabilize($this->tableName)); return $table->getColumns(); }
public function render($view, $values = array(), $ui_content = false) { $controller = Inflector::instance()->getClassNameFromNamespace(get_called_class()); $controller = strtolower(str_replace('Controller', '', $controller)); $viewPath = null; $viewPath = strpos($this->viewsFilePath, '.') == true ? str_replace('.', DS, $this->viewsFilePath) : $this->viewsFilePath; $path = getcwd() . DS . APPPATH . DS . $viewPath . DS . $controller . DS; if (is_object($this->tpl) && is_file($path . $view . $this->templateExtension)) { $this->template = $this->tpl->loadTemplate($controller . DS . $view . $this->templateExtension); return $this; } if (!file_exists($path . $view . '.view' . EXT) && !is_readable($path . $view . '.view' . EXT)) { throw new \Exception('The Path ' . $path . $view . '.view' . EXT . ' is invalid.'); } self::$name[strtolower($view)] = $view; $viewPage = ''; $viewPage = $path . self::$name[$view] . '.view' . EXT; if (is_readable($viewPage)) { $this->layout = Inflector::instance()->toDirectorySeparator($this->layout); if ($this->layout !== '') { // render view page into the layout $layout = getcwd() . DS . APPPATH . DS . $viewPath . DS . $this->layout . '.view' . EXT; //$this->view_path = $path.self::$name[$view].'.view'.EXT; // $layout; $this->assignToProperties($values); ob_start(); include $viewPage; $data = array(); $data['yield'] = ob_get_contents(); ob_get_clean(); extract($data); include $layout; $data = array(); $content = null; $output = ob_get_contents(); ob_get_clean(); echo $output; return $this; } if ($ui_content == true) { self::$uiContent = $ui_content; $this->view_path = $viewPage; $this->loadView(); return $this->content; } $this->view_path = $viewPage; $this->loadView(); return $this; } }
/** * Run validation rules and catch errors * * @return bool * @throws \Exception */ public function run() { $isValid = true; if (empty($this->rules)) { return true; } foreach ($this->rules as $key => $val) { $rules = explode('|', $val); foreach ($rules as $rule) { if (!strstr($rule, 'max') && !strstr($rule, 'min')) { $method = Inflector::instance()->toCameCase($rule); if (is_callable(array($this, $method)) === false) { throw new \Exception('Undefined method ' . __CLASS__ . ' ' . $method . ' called.'); } //echo $key."<br>"; if ($isValid === false) { $this->setErrors($key . self::ERROR, Inflector::camelize(str_replace('_', ' ', $key))); } $isValid = $this->{$method}($key); //$isValid = call_user_func(array($this, $rule[0]), array($key)); } else { $rule = explode(':', $rule); $method = Inflector::instance()->toCameCase($rule[0]); if (is_callable(array($this, $method)) === false) { throw new \Exception('Undefined method ' . __CLASS__ . ' ' . $method . ' called.'); } if ($isValid === false) { $this->setErrors($key . self::ERROR, Inflector::camelize(str_replace('_', ' ', $key))); } //$isValid = call_user_func_array(array($this, $rule[0]), array($key,$rule[1])); $isValid = $this->{$method}($key, $rule[1]); } } } return $isValid; }
/** * We will execute the crud command and generate files * * @param InputInterface $input * @param OutputInterface $output * @throws \Exception * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { // Your model name $this->model = Inflector::classify($input->getArgument('name')); // Check for argument database name if not given we will use default // database connection $this->database = $this->getDatabase($input); $this->columns = $this->getColumns(); if (empty($this->columns)) { throw new \Exception("Please check your model name. It seems doesn't exists in the database."); } $this->applicationDir = CYGNITE_BASE . DS . APPPATH; $this->generateModel(); $modelPath = $this->applicationDir . DS . 'models' . DS . $this->model . EXT; $output->writeln("Model {$this->model} generated successfully into " . $modelPath); }