예제 #1
0
 public function action_index($modelName)
 {
     $model = $this->getClassObject($modelName);
     $columnModel = $model::first();
     Input::flash();
     if (Input::get($modelName) != null && $this->addConditions($model, $modelName)->first() != null) {
         $columnModel = $this->addConditions($model, $modelName)->first();
     }
     if ($columnModel == null) {
         return Redirect::to("/lara_admin/models/{$modelName}/new");
     }
     $columns = $columnModel->columns();
     $sort_options = $this->setOrderOptions($columns);
     $models = $this->addConditions($model, $modelName)->order_by($sort_options["column_order"], $sort_options["sort_direction"])->paginate($model->perPage);
     $request_uri = Request::server("REQUEST_URI");
     $request_uri = preg_replace("/&order=[^&]*/", "", $request_uri);
     if (!preg_match("/\\?/i", Request::server("REQUEST_URI"))) {
         $request_uri .= "?";
     }
     //TODO function getCustomAction
     $name_custom_action = "lara_admin::" . Str::plural(Str::lower($modelName)) . "." . preg_replace("/action_/", "", __FUNCTION__);
     if (View::exists($name_custom_action) != false) {
         $view = View::make($name_custom_action, array("sort_options" => $sort_options, "request_uri" => $request_uri, "modelName" => $modelName, "modelInstance" => $model, "models" => $models, "columns" => $columns));
     } else {
         $view = View::make("lara_admin::models.index", array("sort_options" => $sort_options, "request_uri" => $request_uri, "modelName" => $modelName, "modelInstance" => $model, "models" => $models, "columns" => $columns));
     }
     $this->defaultAttrForLayout($modelName, $view);
     return $this->response_with(array("xml", "json", "csv"), $this->collectionToArray($models->results), true);
 }
예제 #2
0
 public function resource($arguments)
 {
     $pluralize = new Laravel\Pluralizer(Laravel\Config::get('strings'));
     foreach ($arguments as $key => $model) {
         $content = array();
         $nameClass = ucwords($model);
         $content[] = "<?php namespace Admin;";
         $content[] = "class {$nameClass} extends Appmodel{";
         $content[] = "\tpublic static \$table ='" . Str::plural($model) . "'; ";
         $content[] = "\tpublic \$index= array(); ";
         $content[] = "\tpublic \$new=array(); ";
         $content[] = "\tpublic \$edit= array(); ";
         $content[] = "\tpublic \$show= array(); ";
         $content[] = "\tpublic \$rules= array(); ";
         $content[] = "}";
         $DS = DIRECTORY_SEPARATOR;
         $path = path('bundle') . $DS . "lara_admin" . $DS . "models" . $DS . strtolower($model) . ".php";
         if (!file_exists($path)) {
             file_put_contents($path, implode(" \n ", $content));
             echo "done";
         } else {
             echo " already exists. send force like third parameter";
         }
     }
 }
예제 #3
0
파일: ext.php 프로젝트: SerdarSanri/LextJS
 public function generate($args)
 {
     if (count($args) != 1) {
         die(self::$usageMessage);
     }
     $model = $args[0];
     $table = Str::plural(Str::lower($model));
     $options = array('Model' => $model, 'Table' => $table, 'DefaultField' => 'text', 'ParentID' => 'parent_id', 'Leaf' => 'leaf');
     $r = new ReflectionClass($model);
     preg_match_all('#@(.*?)\\n#s', $r->getDocComment(), $annotations);
     if (!empty($annotations)) {
         foreach ($annotations[0] as $annotation) {
             preg_match('#@(?P<name>\\w+)[ ]*(\\([ ]*(?P<value>\\w+)[ ]*\\))?\\n#s', $annotation, $a);
             if (array_key_exists($a['name'], $options)) {
                 $options[$a['name']] = $a['value'];
             }
         }
     }
     $columns = DB::query('SHOW columns from ' . $table);
     if (Cache::has('ext' . $model, $columns)) {
         $was_cached = true;
     } else {
         Cache::forever('ext' . $model, $columns);
         $was_cached = false;
     }
     // Generate code
     $this->generateExtModel($columns, $model, $options);
     $this->generateGrid($columns, $model, $options, $was_cached);
     $this->generateForm($columns, $model, $options, $was_cached);
     $this->generateTree($model, $options, $was_cached);
     /**************************************************************/
     echo 'Task executed successfully';
 }
예제 #4
0
 /**
  * Get the @class (Class Name) associated with the model.
  *
  * @return string
  */
 public function getTable()
 {
     if (isset($this->table)) {
         return $this->table;
     }
     return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
 }
예제 #5
0
 /**
  *
  */
 public function fire()
 {
     // get ID for next step
     $selectedResource = $this->pickResource();
     $this->info('Retrieving resource data for ' . $selectedResource->ResourceID);
     // get meta Classes for Resource
     // now we need to know what tables to get
     $selectedClasses = $this->pickClasses($selectedResource->ResourceID);
     // we're going to get metadata to retrieve
     $fieldMetadata = [];
     // loop over selection and get table
     foreach ($selectedClasses as $class) {
         // pull meta for table
         $metaTable = $this->rets->getTable($selectedResource->ResourceID, (string) $class->ClassName);
         // time to create date
         $fieldMetadata = array_merge($fieldMetadata, $this->parseFields('class_' . (string) $class->ClassName, $metaTable));
     }
     // pull metadata
     if (!empty($fieldMetadata)) {
         $this->info('We need to pull data for ' . count($fieldMetadata) . ' ' . \Str::plural('field', count($fieldMetadata)));
         foreach ($fieldMetadata as $meta_id => $id) {
             $fieldData = $this->rets->getFieldMetadata($selectedResource->ResourceID, $meta_id);
             try {
                 RetsField::createFromXml($fieldData[0]);
             } catch (\Exception $e) {
                 $this->error($e->getMessage());
             }
         }
     } else {
         $this->info('Looks like we not able to find a single field that requires metadata look up. Skipping.');
     }
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     if (parent::fire() !== false) {
         if ($this->option('migration')) {
             $table = Str::plural(Str::snake(class_basename($this->argument('name'))));
             $this->call('make:rethink-migration', ['name' => "create_{$table}_table", '--create' => $table]);
         }
     }
 }
예제 #7
0
 public function hasMtm($model, $method = null, $modelName = null)
 {
     if (!$model) {
         throw new \Illuminate\Database\Eloquent\ModelNotFoundException();
     }
     $method = $method ?: \Str::plural(\Str::lower($modelName));
     return !$this->{$method}->filter(function ($nthModel) use($model) {
         return $nthModel->id == $model->id;
     })->isEmpty();
 }
예제 #8
0
파일: model.php 프로젝트: downleave/blog
 /**
  * This method is responsible for generation all
  * source from the templates, and populating the
  * files array.
  *
  * @return void
  */
 private function _model_generation()
 {
     $prefix = $this->bundle == DEFAULT_BUNDLE ? '' : Str::classify($this->bundle) . '_';
     // set up the markers for replacement within source
     $markers = array('#CLASS#' => $prefix . $this->class_prefix . $this->class, '#LOWER#' => $this->lower, '#TIMESTAMPS#' => $this->_timestamps);
     // loud our model template
     $template = Common::load_template('model/model.tpl');
     // holder for relationships source
     $relationships_source = '';
     // loop through our relationships
     foreach ($this->arguments as $relation) {
         // if we have a valid relation
         if (!strstr($relation, ':')) {
             continue;
         }
         // split
         $relation_parts = explode(':', Str::lower($relation));
         // we need two parts
         if (!count($relation_parts) == 2) {
             continue;
         }
         // markers for relationships
         $rel_markers = array('#SINGULAR#' => Str::lower(Str::singular($relation_parts[1])), '#PLURAL#' => Str::lower(Str::plural($relation_parts[1])), '#WORD#' => Str::classify(Str::singular($relation_parts[1])), '#WORDS#' => Str::classify(Str::plural($relation_parts[1])));
         // start with blank
         $relationship_template = '';
         // use switch to decide which template
         switch ($relation_parts[0]) {
             case "has_many":
             case "hm":
                 $relationship_template = Common::load_template('model/has_many.tpl');
                 break;
             case "belongs_to":
             case "bt":
                 $relationship_template = Common::load_template('model/belongs_to.tpl');
                 break;
             case "has_one":
             case "ho":
                 $relationship_template = Common::load_template('model/has_one.tpl');
                 break;
             case "has_and_belongs_to_many":
             case "hbm":
                 $relationship_template = Common::load_template('model/has_and_belongs_to_many.tpl');
                 break;
         }
         // add it to the source
         $relationships_source .= Common::replace_markers($rel_markers, $relationship_template);
     }
     // add a marker to replace the relationships stub
     // in the model template
     $markers['#RELATIONS#'] = $relationships_source;
     // add the generated model to the writer
     $this->writer->create_file('Model', $prefix . $this->class_prefix . $this->class, $this->bundle_path . 'models/' . $this->class_path . $this->lower . EXT, Common::replace_markers($markers, $template));
 }
예제 #9
0
 public function store()
 {
     //make plural, title case
     $title = mb_convert_case(Str::plural(Input::get('title')), MB_CASE_TITLE, 'UTF-8');
     //determine table name, todo check if unique
     $name = Str::slug($title, '_');
     //model name
     $model = Str::singular(Str::studly($title));
     //enforce predence always ascending
     $order_by = Input::get('order_by');
     $direction = Input::get('direction');
     if ($order_by == 'precedence') {
         $direction = 'asc';
     }
     //create entry in objects table for new object
     $object_id = DB::table(DB_OBJECTS)->insertGetId(['title' => $title, 'name' => $name, 'model' => $model, 'order_by' => $order_by, 'direction' => $direction, 'list_grouping' => Input::get('list_grouping'), 'updated_at' => new DateTime(), 'updated_by' => Auth::user()->id]);
     //create title field for table by default
     DB::table(DB_FIELDS)->insert(['title' => 'Title', 'name' => 'title', 'type' => 'string', 'visibility' => 'list', 'required' => 1, 'object_id' => $object_id, 'updated_at' => new DateTime(), 'updated_by' => Auth::user()->id, 'precedence' => 1]);
     self::addTable($name, true);
     self::saveSchema();
     return Redirect::action('InstanceController@index', $name);
 }
예제 #10
0
 public function getCommit($sessid)
 {
     $heads = Importsession::where('sessId', '=', $sessid)->where('isHead', '=', 1)->first();
     $heads = $heads['heads'];
     $imports = Importsession::where('sessId', '=', $sessid)->where('isHead', '=', 0)->take(200)->skip(0)->get();
     $headselect = array();
     foreach ($heads as $h) {
         $headselect[$h] = $h;
     }
     $title = $this->controller_name;
     $submit = is_null($this->import_commit_submit) ? strtolower($this->controller_name) . '/commit/' . $sessid : $this->import_commit_submit . '/' . $sessid;
     $controller_name = strtolower($this->controller_name);
     $import_validate_list = $this->import_validate_list;
     $this->title = $this->title == '' ? Str::plural($this->controller_name) : Str::plural($this->title);
     Breadcrumbs::addCrumb($this->title, URL::to($controller_name));
     Breadcrumbs::addCrumb('Import ' . $this->title, URL::to($controller_name . '/import'));
     Breadcrumbs::addCrumb('Preview', URL::to($controller_name . '/import'));
     return View::make('shared.commitselect')->with('title', $title)->with('submit', $submit)->with('headselect', $headselect)->with('import_validate_list', $import_validate_list)->with('heads', $heads)->with('back', $controller_name . '/import')->with('imports', $imports);
 }
예제 #11
0
 /**
  * @param $entity
  */
 protected function generateEntity($entity)
 {
     $temp = new RestfulOperations($entity);
     $temp->generate();
     $this->api('index')->apis([['path' => \Str::plural($entity)]]);
 }
예제 #12
0
 case 'transactions':
 case 'transfers':
     echo '<li><a href="/home/' . $segments[1] . '">' . ucfirst($segments[1]) . '</a> <span class="divider">/</span></li>';
     echo '<li class="active">Overview of all ' . $segments[1] . '</li>';
     break;
 case 'account':
 case 'budget':
 case 'category':
 case 'transaction':
 case 'transfer':
 case 'beneficiary':
 case 'target':
     // account has its own overview, so it needs to be visible in the
     // edit screen
     if (isset($segments[2])) {
         echo '<li><a href="/home/' . Str::plural($segments[1]) . '">' . ucfirst(Str::plural($segments[1])) . '</a> <span class="divider">/</span></li>';
         switch ($segments[2]) {
             case 'add':
                 echo '<li class="active">Add a new ' . $segments[1] . '</li>';
                 break;
             case 'edit':
                 if (!in_array($segments[1], array('transaction', 'transfer'))) {
                     echo '<li><a href="/home/' . $segments[1] . '/overview/' . $segments[3] . '">' . ucfirst($segments[1]) . ' overview</a> <span class="divider">/</span></li>';
                 }
                 echo '<li class="active">Edit ' . $segments[1] . '</li>';
                 break;
             case 'overview':
                 echo '<li class="active">' . ucfirst($segments[1]) . ' overview</li>';
                 break;
             case 'overspending':
                 echo '<li class="active">' . ucfirst($segments[1]) . ' overspending</li>';
예제 #13
0
 /**
  * Get the name of the table associated with the model.
  *
  * @return string
  */
 public static function table()
 {
     return static::$table ?: strtolower(Str::plural(class_basename(new static())));
 }
예제 #14
0
파일: template.php 프로젝트: ajb/rfpez
    <ul class="templates-list">
      <?php 
    echo View::make('projects.partials.template_lis')->with('templates', $templates)->with('project', $project);
    ?>
      <?php 
    if ($more_templates_count) {
        ?>
        <li class="show-more">
          <a class="show-more-templates-link" data-href="<?php 
        echo e(route('project_more_templates', array($project->id)));
        ?>
">See <?php 
        echo e($more_templates_count);
        ?>
 more <?php 
        echo e(Str::plural('template', $more_templates_count));
        ?>
...</a>
          <img class="spinner" src="<?php 
        echo e(asset('img/spinner.gif'));
        ?>
" />
        </li>
      <?php 
    }
    ?>
    </ul>
    <h5><?php 
    echo __("r.projects.template.scratch_header");
    ?>
</h5>
예제 #15
0
 /**
  * Get the plural form of an English word.
  *
  * @param  string  $value
  * @param  int     $count
  * @return string
  */
 function str_plural($value, $count = 2)
 {
     return Str::plural($value, $count);
 }
 /**
  * Generate resource (model, controller, and views)
  *
  * @param $args array  
  * @return void
  */
 public function resource($args)
 {
     if ($this->should_include_tests($args)) {
         $args = array_diff($args, array('with_tests'));
     }
     // Pluralize controller name
     if (!preg_match('/admin|config/', $args[0])) {
         $args[0] = Str::plural($args[0]);
     }
     // If only the resource name was provided, let's build out the full resource map.
     if (count($args) === 1) {
         $args = array($args[0], 'index', 'index:post', 'show', 'edit', 'new', 'update:put', 'destroy:delete', 'restful');
     }
     $this->controller($args);
     // Singular for everything else
     $resource_name = Str::singular(array_shift($args));
     // Should we include tests?
     if (isset($this->should_include_tests)) {
         $this->test(array_merge(array(Str::plural($resource_name)), $args));
     }
     if ($this->is_restful($args)) {
         // Remove that restful item from the array. No longer needed.
         $args = array_diff($args, array('restful'));
     }
     $args = $this->determine_views($args);
     // Let's take any supplied view names, and set them
     // in the resource name's directory.
     $views = array_map(function ($val) use($resource_name) {
         return "{$resource_name}.{$val}";
     }, $args);
     $this->view($views);
     $this->model($resource_name);
 }
예제 #17
0
 /**
  * Get cache id
  *
  * @return mixed
  */
 protected function cacheID()
 {
     return \Str::plural(\Str::lower($this->itemClass()));
 }
예제 #18
0
 public function getCommit($sessid)
 {
     $heads = Importsession::where('sessId', '=', $sessid)->where('isHead', '=', 1)->first();
     $heads = $heads['heads'];
     $imports = Importsession::where('sessId', '=', $sessid)->where('isHead', '=', 0)->get();
     $headselect = array();
     foreach ($heads as $h) {
         $headselect[$h] = $h;
     }
     $vl = $this->validateData($imports->toArray());
     $dbval = $vl['db'];
     $inval = $vl['in'];
     $title = $this->controller_name;
     $submit = strtolower($this->controller_name) . '/commit/' . $sessid;
     $controller_name = strtolower($this->controller_name);
     $this->title = $this->title == '' ? Str::plural($this->controller_name) : Str::plural($this->title);
     Breadcrumbs::addCrumb($this->title, URL::to($controller_name));
     Breadcrumbs::addCrumb('Import ' . $this->title, URL::to($controller_name . '/import'));
     Breadcrumbs::addCrumb('Preview', URL::to($controller_name . '/import'));
     return View::make('importer.commitselect')->with('title', $title)->with('submit', $submit)->with('headselect', $headselect)->with('heads', $heads)->with('dbval', $dbval)->with('inval', $inval)->with('back', $controller_name . '/import')->with('imports', $imports);
 }
예제 #19
0
    /**
     * Generates a new controller.
     * @param  Array $arguments Contains the name and fields.
     * @return 
     */
    public function model($arguments)
    {
        // Check if there are any arguments.
        if (count($arguments) == 0) {
            // Exit;
            echo "Error: No arguments given.";
            return false;
        }
        // Create the filename with the first argument being the name of the model.
        $filename = $arguments[0] . ".php";
        // Create half of the migration filename. We will need to prefix it with  // the date and the path.
        $mfilename = 'create_' . Str::plural(strtolower($arguments[0])) . "_table.php";
        // Get a CamelCase version of the name for the class name.
        $name = ucfirst($arguments[0]);
        // Get a plural definition of the name.
        $uname = Str::plural($arguments[0]);
        // Delete it from the array so we can loop through the rest of the arguments.
        unset($arguments[0]);
        // Create a new schema. With the plural name of the model for the table.
        $schema = '
		Schema::create(\'' . $uname . '\', function($table){

		';
        // Create the migration beginning. With a class.
        $migration = "<?php\n\nclass Create_" . $name . "s_Table{\n\n\t\t";
        // Check to see if there are any arguments passed.
        if (count($arguments) !== 0) {
            // Set the fields variable.
            $fields = null;
            // Append an increment 'id'. This is set on ALL tables by default.
            $fields .= " \t\$table->increments('id');";
            //Loop through each arguments to set their schema and properties.
            foreach ($arguments as $m) {
                // Seperate the argument by a ":". Left Side == Value, Right Side == Type.
                $explode = explode(':', $m);
                // Set the field name to the first index.
                $field_name = $explode[0];
                // Set the type to the second index if it's available. Otherwise default to a 'string'.
                $type = isset($explode[1]) ? $explode[1] : 'string';
                // Getting the length:
                $length_explode = explode("[", $type);
                $type = $length_explode[0];
                /**
                 * If there's more than one index, that means they included a       * length delimeter.
                 */
                if (count($length_explode) > 1) {
                    //Yup there's a length! But replace the last "]" with blank.
                    $length = str_replace("]", "", $length_explode[1]);
                    if (!is_numeric($length)) {
                        unset($length);
                    }
                }
                // ./count
                // Check which type and use the following code.
                switch ($type) {
                    case "integer":
                        $default_length = isset($length) && is_numeric($length) ? $length : 11;
                        if (!isset($length)) {
                            $fields .= "\n \t\t\t\$table->integer('{$field_name}');";
                        } else {
                            $fields .= "\n \t\t\t\$table->integer('{$field_name}', {$length});";
                        }
                        break;
                    case "string":
                        $default_length = isset($length) && is_numeric($length) ? $length : 100;
                        if (!isset($length)) {
                            $fields .= "\n \t\t\t\$table->string('{$field_name}', {$default_length});";
                        } else {
                            $fields .= "\n \t\t\t\$table->string('{$field_name}', {$default_length});";
                        }
                        break;
                    case "boolean":
                        $fields .= "\n \t\t\t\$table->boolean('{$field_name}');";
                        break;
                    case "timestamp":
                        $fields .= "\n \t\t\t\$table->timestamp('{$field_name}');";
                        break;
                    case "text":
                        if (!isset($length)) {
                            $fields .= "\n \t\t\t\$table->text('{$field_name}');";
                        } else {
                            $fields .= "\n \t\t\t\$table->text('{$field_name}', {$length});";
                        }
                        break;
                    case "blob":
                        $fields .= "\n \t\t\t\$table->blob('{$field_name}');";
                        break;
                    case "float":
                        $fields .= "\n \t\t\t\$table->float('{$field_name}');";
                        break;
                    case "date":
                        $fields .= "\n \t\t\t\$table->date('{$field_name}');";
                        break;
                }
                // ./switch
                unset($length);
            }
            // ./foreach
            // Add the timestamps;
            $fields .= "\n \t\t\t\$table->timestamps();";
            // Append the fields set in the switch statement to the schema block.
            $schema .= $fields;
        }
        // ./if
        // Append the closing }, and ) for the closure, and function call.
        $schema .= "\n \t\t});";
        // Append the "up" method that now contains the newly
        // created schema.
        $migration .= "\n\t\t\t\t\n \tpublic function up()\n\t{\n\t\t\t{$schema}\n\t}\n\t\t\t\t";
        // Append the migration file with a closing "}", which ends the class.
        $migration .= "\n}";
        // Get the path to the migration folder, and create the new file name by
        // prefixing the current date to the file.
        $mpath = realpath(dirname(__FILE__) . '\\..\\migrations\\') . '\\' . date('Y_m_d_His') . "_" . $mfilename;
        // Check if the file already exists, which will always return false
        // since the date and time will always be different.
        // TODO: Find a better way???
        if (!file_exists($mpath)) {
            // Write the new migration file.
            file_put_contents($mpath, $migration);
        } else {
            // The migration file has already been created.
            // This will always return FALSE right now.
            echo "The migration already exists.";
            // Close.
            return;
        }
        /**
         * Next Step: Create the model file.
         */
        // Start the file with a php tag and the opening class with the model name.
        $model = "<?php\n\t\t\t\nclass {$name} extends Eloquent{\n\t\t\t\n}\n\n\t\t";
        // Find the path to the models directory, and append the new file name.
        $path = realpath(dirname(__FILE__) . '\\..\\models\\') . '\\' . $filename;
        // Check if the model has already been created.
        // Return false if it has.
        // TODO: Maybe add an overwrite option??
        // TODO: Delete the previously created migration file, if the model
        // creation fails.
        if (!file_exists($path)) {
            // Create the new model file.
            file_put_contents($path, $model);
        } else {
            // Ooops.
            echo "Model already exists.";
            // TODO: Add the overwrite command???
        }
    }
예제 #20
0
 /**
  * Get the table associated with the model.
  *
  * @return string
  */
 public function getTable()
 {
     $table = \Config::get('auditing.table');
     if (isset($table)) {
         return $table;
     }
     return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
 }
예제 #21
0
 function showTransactions($object)
 {
     $id = intval(Input::get('id'));
     $start = new Carbon(Input::get('start'));
     $end = new Carbon(Input::get('end'));
     $objects = Str::plural($object);
     // we might filter on expenses or incomes:
     $modifier = Input::get('modifier');
     // we might need to filter on a certain object.
     // this object is called the child.
     // so the object might be an account, and the child might be beneficiary
     $children = Input::get('childType');
     // yes this is confusing.
     $child = !is_null($children) ? Str::singular($children) : null;
     // find the ID that this child signifies.
     // this might be a beneficiary name or a budget name
     $selection = Input::get('childValue');
     $selectedItem = false;
     // false means no selection made.
     if (!strstr($selection, '(no ') === false) {
         $selectedItem = null;
         // null means select where NULL.
     }
     if (!is_null($selection) && $selectedItem === false) {
         // find it:
         switch ($child) {
             default:
                 // just find it.
                 $items = Auth::user()->{$children}()->get();
                 foreach ($items as $item) {
                     if (Crypt::decrypt($item->name) == $selection) {
                         $selectedItem = $item;
                     }
                 }
                 break;
             case 'budget':
                 // keep the date in mind!
                 $split = explode('(', $selection);
                 $budget_name = trim($split[0]);
                 $dateStr = trim(str_replace(')', '', $split[1]));
                 $date = new Carbon($dateStr);
                 $budgets = Auth::user()->budgets()->where('date', '=', $date->format('Y-m-d'))->get();
                 foreach ($budgets as $b) {
                     if (Crypt::decrypt($b->name) == $budget_name) {
                         $selectedItem = $b;
                     }
                 }
                 break;
         }
     }
     //var_dump($selectedItem);exit;
     $db = Auth::user()->{$objects}()->find($id);
     // create (and find)  a cache key:
     $key = cacheKey('PieChart', $id, $start, $end, $objects, $children, $modifier, $selection);
     if (Cache::has($key)) {
         return Response::json(Cache::get($key));
     }
     if (!$db) {
         return App::abort(404);
     }
     // find the transactions and transfers for $object in range.
     $index = 0;
     $data = array('cols' => array(array('id' => 'date', 'label' => 'Date', 'type' => 'date'), array('id' => 'description', 'label' => 'Description', 'type' => 'string'), array('id' => 'amount', 'label' => 'Amount', 'type' => 'number'), array('id' => 'account', 'label' => 'Account(s)', 'type' => 'string'), array('id' => 'budget', 'label' => 'Budget', 'type' => 'string'), array('id' => 'category', 'label' => 'Category', 'type' => 'string'), array('id' => 'beneficiary', 'label' => 'Beneficiary', 'type' => 'string'), array('id' => 'target', 'label' => 'Target', 'type' => 'string')), 'rows' => array());
     $transactionsQuery = $db->transactions()->leftJoin('accounts', 'accounts.id', '=', 'account_id')->leftJoin('budgets', 'budgets.id', '=', 'budget_id')->leftJoin('categories', 'categories.id', '=', 'category_id')->leftJoin('beneficiaries', 'beneficiaries.id', '=', 'beneficiary_id')->orderBy('transactions.date', 'DESC')->where('transactions.date', '>=', $start->format('Y-m-d'))->where('transactions.date', '<=', $end->format('Y-m-d'));
     if ($modifier == 'income') {
         $transactionsQuery->where('transactions.amount', '>', 0);
     } else {
         if ($modifier == 'expenses') {
             $transactionsQuery->where('transactions.amount', '<', 0);
         }
     }
     if (is_null($selectedItem)) {
         $transactionsQuery->whereNull($child . '_id');
     } else {
         if (!is_null($selectedItem) && !$selectedItem === false) {
             $transactionsQuery->where($child . '_id', '=', $selectedItem->id);
         }
     }
     $transactions = $transactionsQuery->get(array('transactions.id', 'accounts.name AS account_name', 'budgets.name AS budget_name', 'categories.name AS category_name', 'beneficiaries.name AS beneficiary_name', 'transactions.date', 'description', 'transactions.amount', 'onetime'));
     foreach ($transactions as $t) {
         $date = new Carbon($t->date);
         $data['rows'][$index]['c'][0]['v'] = 'Date(' . intval($date->format('Y')) . ', ' . (intval($date->format('n')) - 1) . ', ' . intval($date->format('j')) . ')';
         $data['rows'][$index]['c'][1]['v'] = Crypt::decrypt($t->description);
         $data['rows'][$index]['c'][2]['v'] = floatval($t->amount);
         $data['rows'][$index]['c'][3]['v'] = is_null($t->account_name) ? null : Crypt::decrypt($t->account_name);
         $data['rows'][$index]['c'][4]['v'] = is_null($t->budget_name) ? null : Crypt::decrypt($t->budget_name);
         $data['rows'][$index]['c'][5]['v'] = is_null($t->category_name) ? null : Crypt::decrypt($t->category_name);
         $data['rows'][$index]['c'][6]['v'] = is_null($t->beneficiary_name) ? null : Crypt::decrypt($t->beneficiary_name);
         $data['rows'][$index]['c'][7]['v'] = null;
         $index++;
     }
     Cache::put($key, $data, 1440);
     return Response::json($data);
 }
예제 #22
0
 /**
  * Creates a camel plural
  */
 public function transformPluralCamel($key, $value)
 {
     return array(Str::plural(Str::camel($key)), Str::plural(Str::camel($value)));
 }
예제 #23
0
 public function doImport()
 {
     var_dump($_FILES);
     var_dump($_POST);
     exit;
     define('LESSEVENTS', true);
     if (strlen(Input::get('payload_text')) == 0) {
         $payload = Input::file('payload');
         $raw = File::get($payload);
     } else {
         $raw = Input::get('payload_text');
     }
     $json = json_decode($raw, true);
     $firstIcon = Icon::first();
     $old = array(Auth::user()->accounts()->get(), Auth::user()->budgets()->get(), Auth::user()->categories()->get(), Auth::user()->beneficiaries()->get(), Auth::user()->settings()->get(), Auth::user()->targets()->get());
     $mapping = array();
     $order = array('account', 'beneficiary', 'budget', 'category', 'target', 'transaction', 'transfer', 'setting');
     if (is_null($json)) {
         Session::flash('error', 'This is not a valid JSON file.');
         return View::make('home.import');
     }
     foreach ($order as $name) {
         $names = Str::plural($name);
         foreach ($json[$names] as $item) {
             $class = ucfirst($name);
             // overrule user ID
             if (isset($item['fireflyuser_id'])) {
                 $item['fireflyuser_id'] = Auth::user()->id;
             }
             // overrule possible account ID since we might need it here:
             if (isset($item['account_id'])) {
                 $item['account_id'] = $mapping['accounts'][intval($item['account_id'])];
             }
             // overrule account_from and account_to (only for transfers)
             if ($class == 'Transfer') {
                 $item['account_from'] = $mapping['accounts'][intval($item['account_from'])];
                 $item['account_to'] = $mapping['accounts'][intval($item['account_to'])];
             }
             // overrule possible icon ID
             if (isset($item['icon_id'])) {
                 $item['icon_id'] = intval($firstIcon->id);
             }
             // overrule possible beneficiary ID
             if (isset($item['beneficiary_id'])) {
                 $item['beneficiary_id'] = $mapping['beneficiaries'][intval($item['beneficiary_id'])];
             }
             // overrule possible category ID
             if (isset($item['category_id'])) {
                 $item['category_id'] = $mapping['categories'][intval($item['category_id'])];
             }
             // overrule possible budget ID
             if (isset($item['budget_id'])) {
                 $item['budget_id'] = $mapping['budgets'][intval($item['budget_id'])];
             }
             // overrule possible target ID
             if (isset($item['target_id'])) {
                 $item['target_id'] = $mapping['targets'][intval($item['target_id'])];
             }
             // overrule due date for targets:
             if (isset($item['duedate']) && $item['duedate'] == '0000-00-00') {
                 $item['duedate'] = null;
             }
             // remap settings:
             if ($class == 'Setting') {
                 if ($item['name'] == 'defaultCheckingAccount') {
                     $item['value'] = $mapping['accounts'][intval($item['value'])];
                 }
                 if ($item['name'] == 'defaultSavingsAccount') {
                     $item['value'] = $mapping['accounts'][intval($item['value'])];
                 }
             }
             // make validator:
             $validator = Validator::make($item, $class::$rules);
             // validate!
             if ($validator->fails()) {
                 // fail gracefully, log error:
                 Log::error('Validator failed on ' . $class . ': ' . print_r($validator->messages()->all(), true));
                 // show error
                 Session::flash('error', 'There is invalid ' . $class . ' data in the file.');
                 return View::make('home.import');
             } else {
                 // create the object, remember the ID.
                 $object = new $class($item);
                 // encrypt some fields:
                 if (isset($object->description)) {
                     $object->description = Crypt::encrypt($object->description);
                 }
                 if (isset($object->name) && $class != 'Setting') {
                     $object->name = Crypt::encrypt($object->name);
                 }
                 if ($class == 'Setting') {
                     $object->value = Crypt::encrypt($object->value);
                 }
                 // save:
                 $object->save();
                 // remember the mapping:
                 $oldID = intval($item['id']);
                 $newID = intval($object->id);
                 $mapping[$names][$oldID] = $newID;
             }
         }
     }
     // if this is where we end up we can safely delete
     // the old accounts. Deleting those drag EVERYTHING along with it.
     foreach ($old as $items) {
         foreach ($items as $item) {
             $item->delete();
         }
     }
     Session::flash('success', 'All data imported!');
     return Redirect::to('/home');
 }
예제 #24
0
 /**
  * Test the Str::plural and Str::singular methods.
  *
  * @group laravel
  */
 public function testStringsCanBeSingularOrPlural()
 {
     $this->assertEquals('user', Str::singular('users'));
     $this->assertEquals('users', Str::plural('user'));
     $this->assertEquals('User', Str::singular('Users'));
     $this->assertEquals('Users', Str::plural('User'));
     $this->assertEquals('user', Str::plural('user', 1));
     $this->assertEquals('users', Str::plural('user', 2));
 }
 /**
  * get model table columns
  *
  * @return mixed
  */
 protected function getColumns()
 {
     static $columns = [];
     if (!isset($columns[$this->modelClass])) {
         // if implemented "getAvailableFields"
         $callable = [$this->modelClass, 'getAvailableFields'];
         if (is_callable($callable)) {
             $columns[$this->modelClass] = call_user_func($callable);
         } else {
             /** @var \Illuminate\Database\Connection $connection */
             $connection = $this->_query()->getQuery()->getConnection();
             $columns[$this->modelClass] = $connection->getSchemaBuilder()->getColumnListing(str_replace('\\', '', Str::snake(Str::plural(class_basename($this->modelClass)))));
         }
     }
     return $columns[$this->modelClass];
 }
예제 #26
0
 /**
  * Generate resource (model, controller, and views)
  *
  * @param $args array  
  * @return void
  */
 public function resource($args)
 {
     // Pluralize controller name
     if (!preg_match('/admin|config/', $args[0])) {
         $args[0] = Str::plural($args[0]);
     }
     $this->controller($args);
     // Singular for everything else
     $resource_name = Str::singular(array_shift($args));
     // Let's take any supplied view names, and set them
     // in the resource name's directory.
     $views = array_map(function ($val) use($resource_name) {
         return "{$resource_name}.{$val}";
     }, $args);
     $this->view($views);
     $this->model($resource_name);
 }
예제 #27
0
파일: template_lis.php 프로젝트: ajb/rfpez
        <div class="title"><?php 
    echo e($template->title);
    ?>
</div>
        <div class="author"><?php 
    echo e($template->owner()->name);
    ?>
</div>
      </div>
      <div class="span3">
        <div class="forked">
          Forked <?php 
    echo e($template->fork_count);
    ?>
 <?php 
    echo e(Str::plural('time', $template->fork_count));
    ?>
        </div>
        <?php 
    if ($template->recommended) {
        ?>
          <div class="recommended">&#9733; Recommended Template</div>
        <?php 
    }
    ?>
      </div>
      <div class="span3">
        <a class="btn btn-info preview-button">Preview</a>
        <a class="btn btn-success" href="<?php 
    echo e(route('project_template_post', array($project->id, $template->id)));
    ?>
예제 #28
0
 /**
  * Generate resource (model, controller, and views)
  *
  * @param $args array  
  * @return void
  */
 public function resource($args)
 {
     // Pluralize controller name
     if (!preg_match('/admin|config/', $args[0])) {
         $args[0] = Str::plural($args[0]);
     }
     $this->controller($args);
     // Singular for everything else
     $resource_name = Str::singular(array_shift($args));
     if ($this->is_restful($args)) {
         // Remove that restful item from the array. No longer needed.
         $args = array_diff($args, array('restful'));
         $args = $this->determine_views($args);
     }
     // Let's take any supplied view names, and set them
     // in the resource name's directory.
     $views = array_map(function ($val) use($resource_name) {
         return "{$resource_name}.{$val}";
     }, $args);
     $this->view($views);
     $this->model($resource_name);
 }