/** * Creates the new policies for the rest config. * @param array $mappedPolicies * @return array The first element are the new class usages and the second element is the policy mapping. * @throws Exception */ public function createNewPolicies(array $mappedPolicies) { $appNamespace = $this->getAppNamespace(); $config = $this->getConfig(); $newUsages = []; foreach (@$config['tables'] ?: [] as $table => $tableConfig) { $policyName = Str::ucfirst(Str::camel($table)) . 'Policy'; $className = preg_replace('/(\\w+\\\\)+/', '', $tableConfig['model']); $classCall = $className . '::class'; if (!class_exists($fullPolicyName = $appNamespace . '\\Policies\\' . $policyName)) { if (Artisan::call('make:policy', ['name' => $policyName])) { throw new Exception('Could not write ' . $policyName); } // if app(File::class, [$policyFile = app_path("Policies/{$policyName}.php")])->setContent(str_replace([' }', "\nclass "], [" }\n{$this->getPolicyMethods($table)}", "use {$tableConfig['model']};\n\nclass "], file_get_contents($policyFile)))->save(); } // if if (!array_key_exists($classCall, $mappedPolicies)) { $newUsages = array_merge($newUsages, [$tableConfig['model'], str_replace('\\\\', '\\', $fullPolicyName)]); $mappedPolicies[$className . '::class'] = $policyName . '::class'; } // if } return array($newUsages, $mappedPolicies); }
/** * Event subscribe handler. * * @throws \Exception */ public function subscribe() { $method = 'handle'; if (method_exists($this, $getHandler = 'get' . Str::ucfirst($method) . 'r')) { $method = $this->{$getHandler}(); } $this->events->listen($this->getEvent(), [$this, $method]); }
/** * Get redirection path. * * @param string $namespace * @param string $path * @param string|null $redirect * * @return string */ protected function redirectUserPath($namespace, $path, $redirect = null) { if (!empty($redirect)) { $path = $redirect; } $property = sprintf('redirect%sPath', Str::ucfirst($namespace)); return property_exists($this, $property) ? $this->{$property} : $path; }
protected static function getClassName($routeName) { $className = Str::ucfirst(substr($routeName, strpos($routeName, '.') + 1)); if (preg_match_all("/_\\w/s", $className, $m)) { foreach ($m[0] as $v) { $className = str_replace($v, strtoupper($v[1]), $className); } } return self::$namespaceModel . $className . 's'; }
protected function getNamespace() { if (empty($this->package)) { throw new \Exception('Enter name package'); } $prefix = Str::ucfirst($this->package); if (!empty($this->vendor)) { $prefix = "{$this->vendor}\\{$prefix}"; } return "{$prefix}\\Commands\\"; }
protected function doReplacements($message, $attribute, $rule, $parameters) { $value = $attribute; $message = str_replace([':ATTRIBUTE', ':Attribute', ':attribute'], [Str::upper($value), Str::ucfirst($value), $value], $message); if (isset($this->replacers[Str::snake($rule)])) { $message = $this->callReplacer($message, $attribute, Str::snake($rule), $parameters); } elseif (method_exists($this, $replacer = "replace{$rule}")) { $message = $this->{$replacer}($message, $attribute, $rule, $parameters); } return $message; }
protected function saveConfigForModule($class, array $arData) { $file = MODULE_PATH . Str::ucfirst($class::MODULE_NAME) . "/config.json"; $arConfigData = new \stdClass(); if (file_exists($file)) { $arConfigData = json_decode(file_get_contents($file)); } foreach ($arData as $key => $item) { $key = strtolower($key); $arConfigData->{$key} = $item; } file_put_contents($file, json_encode($arConfigData, JSON_PRETTY_PRINT)); }
/** * Capitalize the first letter of the string. * * @return $this|static */ public function ucfirst() { return new static(Str::ucfirst($this->string)); }
public function getDefaultName() { $a = Str::snake(get_class($this)); $b = explode('\\', $a); $c = str_replace('_', ' ', array_pop($b)); return Str::ucfirst(trim($c)); }
public function getNameUcfirst() { return Str::ucfirst($this->getName()); //Post }
/** * Make the place-holder replacements on a line. * * @param string $line * @param array $replace * @return string */ protected function makeReplacements($line, array $replace) { $replace = $this->sortReplacements($replace); foreach ($replace as $key => $value) { $line = str_replace([':' . Str::upper($key), ':' . Str::ucfirst($key), ':' . $key], [Str::upper($value), Str::ucfirst($value), $value], $line); } return $line; }
protected function parseMeta($model) { $meta = []; foreach ($this->transformer->getMeta() as $method) { if (!method_exists(get_class($this->model), 'get' . Str::ucfirst($method))) { continue; } $meta = array_merge($meta, $this->model->{'get' . Str::ucfirst($method)}()); } if (count($meta)) { $this->responseBody->put(Mapper::ATTR_META, $meta); $model->put(Mapper::ATTR_META, $meta); } return $model; }
/** * Init form with or within Model * * @param $obj Model * @param $action string * @param $targetAction string * * @return \Kris\LaravelFormBuilder\Form */ protected function buildForm($action, $targetAction, Model $obj = null) { /** @var \Kris\LaravelFormBuilder\Form $form */ $form = null; /** List available namespace exists to class */ $form_class = [$this->getConfig("{$action}.form_class"), sprintf("App\\Http\\Modules\\%s\\forms\\%sForm", $this->getModuleName(), $this->getModuleName()), sprintf("App\\Forms\\%sForm", $this->getModuleName())]; /** End */ /** Check first namespace exists */ foreach ($form_class as $class) { if (empty($class)) { continue; } if (is_array($class)) { $class = $class[0]; } if (class_exists($class)) { $form = $class; break; } } /** End */ if (is_null($form)) { $message = env('APP_DEBUG') ? "Not found Form for module!" : ""; abort(404, $message); $this->form = null; return null; } /** * Use FormBuilder to init class form */ $url = is_null($obj) ? $this->getGeneratedUrl($targetAction) : $this->getGeneratedUrl($targetAction, $obj->id); $form = FormBuilder::create($form, ['method' => 'post', 'url' => $url, 'name' => $action]); /** * Get Field config from module config * @var $formConfig */ $formConfig = $this->getConfig('field', $action); /** * Create field to form if it not exists * @var string $key * @var string $config */ foreach ($formConfig as $key => $config) { if ($form->has($key)) { continue; } $key = trim($key, '[]'); $fieldParams = ['default_value' => array_get($config, 'default_value', ''), 'label' => array_get($config, 'label', $key), 'class' => array_get($config, 'class', ''), 'rules' => array_get($config, 'validation', '')]; if (isset($config['template'])) { $fieldParams['template'] = $config['template']; } if ($obj) { $func = "get" . Str::ucfirst($key); if ($is_I18N = method_exists($obj, 'saveI18N')) { $obj->load('i18n_relation'); } $data = $obj->toArray(); if (method_exists($obj, $func)) { $fieldParams['value'] = $obj->{$func}(); } else { try { $parseField = explode('.', $this->parseFieldName($key)); if (count($parseField) == 1) { $fieldParams['value'] = $data[$parseField[0]]; } else { if ($parseField[0] === 'i18n' && count($parseField) > 1) { $field = last($parseField); $locale = $parseField[1]; $indexData = array_pluck($data['i18n_relation'], $field, 'locale'); $fieldParams['value'] = $indexData[$locale]; } } } catch (\Exception $ex) { } } } /** Custom Prepare Validation in Progress */ $methodValidation = sprintf("%sPrepareValidation", Str::studly(Str::slug($key))); if (method_exists($this, $methodValidation)) { $fieldParams['rules'] = call_user_func_array([$this, $methodValidation], [$fieldParams['rules'], $obj]); } /** End */ /** @var array $fieldParams */ $fieldParams = array_merge($fieldParams, (array) array_get($config, 'params', [])); $form->add($key, array_get($config, 'type', 'text'), $fieldParams); } /** End */ /** Default Button */ foreach ($subActions = $this->getConfig("{$action}.action") as $subAction => $config) { $subAction = sprintf("%sAction", $subAction); if (method_exists($this, $subAction)) { $this->{$subAction}($form, $config); } } $form->rebuildForm(); /** End */ $this->form = $form; return $this->form; }
/** * Take a guess at what the basic labels will be, based on the given name. * @return $this */ protected function guessLabels($name) { return $this->labels(['singular' => str_replace("_", " ", Str::singular($name)), 'plural' => str_replace("_", " ", Str::plural($name)), 'navigation' => str_replace("_", " ", Str::ucfirst($name)), 'slug' => Str::slug(Str::plural($name))]); }
/** * Load the properties from the database table. * * @param \Illuminate\Database\Eloquent\Model $model */ protected function getPropertiesFromTable($model) { $table = $model->getConnection()->getTablePrefix() . $model->getTable(); $schema = $model->getConnection()->getDoctrineSchemaManager($table); $databasePlatform = $schema->getDatabasePlatform(); $databasePlatform->registerDoctrineTypeMapping('enum', 'string'); $platformName = $databasePlatform->getName(); $customTypes = $this->laravel['config']->get("ide-helper.custom_db_types.{$platformName}", array()); foreach ($customTypes as $yourTypeName => $doctrineTypeName) { $databasePlatform->registerDoctrineTypeMapping($yourTypeName, $doctrineTypeName); } $database = null; if (strpos($table, '.')) { list($database, $table) = explode('.', $table); } $columns = $schema->listTableColumns($table, $database); if ($columns) { foreach ($columns as $column) { $name = $column->getName(); if (in_array($name, $model->getDates())) { $type = '\\Carbon\\Carbon'; } else { $type = $column->getType()->getName(); switch ($type) { case 'string': case 'text': case 'date': case 'time': case 'guid': case 'datetimetz': case 'datetime': $type = 'string'; break; case 'integer': case 'bigint': case 'smallint': $type = 'integer'; break; case 'decimal': case 'float': $type = 'float'; break; case 'boolean': $type = 'boolean'; break; default: $type = 'mixed'; break; } } $comment = $column->getComment(); $this->setProperty($name, $type, true, true, $comment); // Method where<name> $name = Str::ucfirst(Str::studly($name)); $modelClass = (new \ReflectionClass($model))->getName(); $this->setMethod("where{$name}", "\\Illuminate\\Database\\Query\\Builder|\\{$modelClass}", array('$value')); } } }
/** * Execute the job. * @param Container $services The service container. * @return bool * @throws Exception If there is an error. */ public function handle(Container $services) { $routesFile = app_path('Http/routes.php'); if (file_exists($routesFile)) { touch($routesFile); } // if /** @var File $file */ $config = $this->getConfig(); $file = $services->make(File::class, [$routesFile]); $codeTemplate = 'Route::group([\'namespace\' => \'%s\', \'prefix\' => \'%s\'], function (Router $router)'; $groups = $file->findLine([$codeTemplate => $values = [$this->getNamespace(), $this->getPrefix()]], 1); if (!$groups) { $group = $file->appendLine(new Line(call_user_func_array('sprintf', array_merge([$codeTemplate], $values)), T_VARIABLE))->setNestingLevel(1); } else { $group = reset($groups); } // else foreach (@$config['tables'] ?: [] as $table => $tableConfig) { $ucTable = ucfirst($table); $className = preg_replace('/(\\w+\\\\)+/', '', $tableConfig['model']); if (!$file->findLine(['use %s' => [$tableConfig['model']]], 1)) { $file->prependLine(new Line("use {$tableConfig['model']}")); } // if $modelLines = $file->findLine(['$router->model(\'%s\', %s::class)' => [$table, $className]], 1, $group->getNestingLevel() + 1); if (!$modelLines) { $group->appendLine(new Line("\$router->model('{$table}', {$className}::class)")); } // if $ctrlrPrefix = Str::ucfirst(Str::camel($ucTable)); $ctrlrLines = $file->findLine(['$router->resource(\'%s\', \'%sController\', [\'except\' => [\'create\', \'edit\']])' => [$table, $ctrlrPrefix]], $group->getNestingLevel() + 1); if (!$ctrlrLines) { $group->appendLine(new Line("\$router->resource('{$table}', '{$ctrlrPrefix}Controller', ['except' => ['create', 'edit']])")); } // if } // foreach if (!$file->save()) { throw new Exception('Routes files can not be cached.'); } // if return true; }
/** * @param $string * @param array $arguments * @return mixed * @author Rytis Grincevičius <*****@*****.**> */ public static function applyArguments($string, array $arguments = array()) { foreach ($arguments as $key => $value) { $string = str_replace([':' . Str::upper($key), ':' . Str::ucfirst($key), ':' . $key], [Str::upper($value), Str::ucfirst($value), $value], $string); } return $string; }
function applyReplacement($line, $replacements) { foreach ($replacements as $key => $value) { $line = str_replace([':' . Str::upper($key), ':' . Str::ucfirst($key), ':' . $key], [Str::upper($value), Str::ucfirst($value), $value], $line); } return $line; }