public static function getDiff($from, $to) { $dStart = new DateTime(date('Y-m-d H:i', $from)); $dEnd = new DateTime(date('Y-m-d H:i', $to)); $dDiff = $dStart->diff($dEnd); if ($dDiff->days > 0) { $time = $dDiff->days; $word = "days"; } else { if ($dDiff->h > 0) { $time = $dDiff->h; $word = "hours"; } else { if ($dDiff->i > 0) { $time = $dDiff->i; $word = "minutes"; } else { return "Less than a minute ago"; } } } if ($time == 1) { $word = Str::singular($word); } return $time . " " . $word . " ago"; }
/** * Creates a typical form heading "Edit project X", "Add a client" * * @param string $verb The verb * @param string $noun The noun * @param string $object The model's representation (ex. $model->name) * @return string A form heading */ public static function form($verb, $noun, $object = null) { $article = $object ? 'the' : 'a'; $noun = \Str::singular($noun); $message = Babel::create(); $message->verb($verb)->article($article)->noun($noun); if ($object) { $message->object($object); } return $message->speak(); }
/** * 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)); }
public function getEdit($pic_id) { $pic_dir = $this->pic_dir . '/' . $pic_id; $pic_dir_temp = $pic_dir . '/tmp'; $formdata = array('_id' => $pic_id); $ps = Config::get('picture.sizes'); $prefixes = array(); foreach ($ps as $px) { $prefixes[] = $px['prefix']; } if (is_array($prefixes)) { $regex = implode('|^', $prefixes); $regex = '^tmp|^' . $regex; } else { $regex = '^tmp'; } if (file_exists($pic_dir)) { if (file_exists($pic_dir . '/tmp')) { } else { mkdir($pic_dir . '/tmp'); } } $pictures = glob($pic_dir . '/*'); if (is_array($pictures)) { $raw = ''; foreach ($pictures as $pic) { $pic = str_replace(array($pic_dir . '/', $pic_dir_temp), '', $pic); if (!preg_match('/' . $regex . '/', $pic)) { $raw = $pic; } } } copy($pic_dir . '/' . $raw, $pic_dir_temp . '/' . $raw); $image = Image::make($pic_dir_temp . '/' . $raw); $info = array(); $info['filename'] = $raw; $info['width'] = $image->width(); $info['height'] = $image->height(); $info['ratio'] = $image->width() / $image->height(); $src_url = URL::to('storage/media/' . $pic_id . '/tmp/' . $raw); $this->backlink = URL::to('property'); return View::make('picture.edit')->with('title', 'Edit ' . Str::singular($this->controller_name))->with('formdata', $formdata)->with('submit', URL::to('picture/edit'))->with('src_url', $src_url)->with('pic_info', $info)->with('pic_dir', $this->pic_dir)->with('pic_temp_dir', $this->pic_temp_dir)->with('back', $this->backlink)->with('pic_id', $pic_id); }
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); }
/** * 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); }
/** * Check if the $attr is a plural form of $field, case insensitive, * or if the $field contains the $attr * * @param string $field * @param string $attr * @return boolean */ protected function attrContains($field, $attr) { return $field == \Str::singular(strtoupper($attr)) || $field == \Str::singular($attr) || $field == strtoupper($attr) || \Str::contains($field, $attr); }
public static function addJoiningTable($object_name, $related_object_id) { //use field_name to store joining table $columns = [Str::singular(DB::table(DB_OBJECTS)->where('id', $related_object_id)->pluck('name')), Str::singular($object_name)]; sort($columns); $field_name = implode('_', $columns); //create joining table Schema::create($field_name, function ($table) use($columns) { foreach ($columns as $column) { $table->integer($column . '_id'); } }); }
public function postEdit($_id, $data = null) { $controller_name = strtolower($this->controller_name); //print_r(Session::get('permission')); $this->backlink = $this->backlink == '' ? $controller_name : $this->backlink; $validation = Validator::make($input = Input::all(), $this->validator); $actor = isset(Auth::user()->email) ? Auth::user()->fullname . ' - ' . Auth::user()->email : 'guest'; if ($validation->fails()) { Event::fire('log.a', array($controller_name, 'update', $actor, 'validation failed')); return Redirect::to($controller_name . '/edit/' . $_id)->withInput(Input::all())->withErrors($validation); } else { if (is_null($data)) { $data = Input::get(); } $id = new MongoId($_id); $data['lastUpdate'] = new MongoDate(); unset($data['csrf_token']); unset($data['_id']); // process tags by default if (isset($data['tags'])) { $tags = $this->tagToArray($data['tags']); $data['tagArray'] = $tags; $this->saveTags($tags); } $model = $this->model; $data = $this->beforeUpdate($id, $data); if ($obj = $model->where('_id', $id)->update($data)) { $obj = $this->afterUpdate($id, $data); if ($obj != false) { Event::fire('log.a', array($controller_name, 'update', $actor, json_encode($obj))); return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saved successfully'); } } else { Event::fire('log.a', array($controller_name, 'update', $actor, 'saving failed')); return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saving failed'); } } }
/** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $this->init(); $data = $this->model->find($id); $this->model->whereId($id)->delete(); Event::fire('activity', array('message' => 'deleted ' . Str::singular($this->subject) . ' ' . $id . '.')); return json_encode(array('success' => true, 'data' => $data)); }
public function postEdit($_id, $data = null) { $is_mongo = false; if ($this->model instanceof Jenssegers\Mongodb\Model) { $is_mongo = true; } $controller_name = strtolower($this->controller_name); //print_r(Session::get('permission')); $this->backlink = $this->backlink == '' ? $controller_name : $this->backlink; $validation = Validator::make($input = Input::all(), $this->validator); $actor = isset(Auth::user()->email) ? Auth::user()->fullname . ' - ' . Auth::user()->email : 'guest'; if ($validation->fails()) { Event::fire('log.a', array($controller_name, 'update', $actor, 'validation failed')); return Redirect::to($controller_name . '/edit/' . $_id)->withInput(Input::all())->withErrors($validation); } else { if (is_null($data)) { $data = Input::get(); } if ($is_mongo) { $id = new MongoId($_id); $data['lastUpdate'] = new MongoDate(); } else { $id = $_id; $data['lastUpdate'] = date('Y-m-d H:i:s', time()); } //`_token` = 6UZKgUN9JxzDN5MDQcgDMJmN5l2kHoCyIggGfsT0, `lastUpdate` = 2015-10-31 16:41:19, `updated_at` = 2015-10-31 16:41:19 unset($data['csrf_token']); unset($data['_id']); // process tags by default if (isset($data['tags'])) { $tags = $this->tagToArray($data['tags']); $data['tagArray'] = $tags; $this->saveTags($tags); } $model = $this->model; $data = $this->beforeUpdate($id, $data); if ($is_mongo) { $obj = $model->where('_id', $id)->update($data); } else { $obj = $model->where('id', $id)->update($data); } if ($obj) { $obj = $this->afterUpdate($id, $data); if ($obj != false) { Event::fire('log.a', array($controller_name, 'update', $actor, json_encode($obj))); return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saved successfully'); } } else { Event::fire('log.a', array($controller_name, 'update', $actor, 'saving failed')); return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saving failed'); } } }
public function post_image_list_delete() { if (Input::has('rel') and Input::has('lid') and Input::has('fid')) { $where = Input::get('rel'); $list_id = Input::get('lid'); $file_id = Input::get('fid'); $singular = Str::singular($where); DB::table('files_' . $where)->where_cmsfile_id($file_id)->where('cms' . $singular . '_id', '=', $list_id)->delete(); return true; } return false; }
/** * 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); }
/** * 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); }
public function postEdit($id, $data = null) { $controller_name = strtolower($this->controller_name); //print_r(Session::get('permission')); $this->backlink = $this->backlink == '' ? $controller_name : $this->backlink; $validation = Validator::make($input = Input::all(), $this->validator); if ($validation->fails()) { return Redirect::to($controller_name . '/edit/' . $id)->withInput(Input::all())->withErrors($validation); //->with_input(Input::all()); } else { if (is_null($data)) { $data = Input::get(); } $id = new MongoId($data['id']); $data['lastUpdate'] = new MongoDate(); unset($data['csrf_token']); unset($data['id']); //print_r($data); //exit(); $model = $this->model; $data = $this->beforeUpdate($id, $data); if ($obj = $model->where('_id', $id)->update($data)) { $obj = $this->afterUpdate($id, $data); if ($obj != false) { return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saved successfully'); } } else { return Redirect::to($this->backlink)->with('notify_success', ucfirst(Str::singular($controller_name)) . ' saving failed'); } } }
public static function getKey($table_name) { if (ctype_digit(strval($table_name))) { $table_name = DB::table(DB_OBJECTS)->where('id', $table_name)->pluck('name'); } return Str::singular($table_name) . '_id'; }
/** * 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)); }
/** * Creates a camel singular */ public function transformSingularCamel($key, $value) { return array(Str::singular(Str::camel($key)), Str::singular(Str::camel($value))); }
function isActiveLink($segment, $checkSingular = false, $active = 'dvs-active') { if ($checkSingular == false) { return Request::is($segment) ? $active : ''; } return Request::is($segment) || Request::is(Str::singular($segment)) ? $active : ''; }
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); }
public function toXML($data = null, $structure = null, $basenode = 'result') { if ($data === null and !func_num_args()) { $data = $this->_data; } // turn off compatibility mode as simple xml throws a wobbly if you don't. if (ini_get('zend.ze1_compatibility_mode') == 1) { ini_set('zend.ze1_compatibility_mode', 0); } if ($structure === null) { $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><{$basenode} />"); } // Force it to be something useful if (!is_array($data) and !is_object($data)) { $data = (array) $data; } foreach ($data as $key => $value) { //change false/true to 0/1 if (is_bool($value)) { $value = (int) $value; } // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... $key = \Str::singular($basenode) != $basenode ? \Str::singular($basenode) : 'item'; } // replace anything not alpha numeric $key = preg_replace('/[^a-z_\\-0-9]/i', '', $key); // if there is another array found recursively call this function if (is_array($value) or is_object($value)) { $node = $structure->addChild($key); // recursive call. $this->toXML($value, $node, $key); } else { // add single node. $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8"); $structure->addChild($key, $value); } } return $structure->asXML(); }
function getRelationKey() { return \Str::singular($this->relation) . '_id'; }
/** * Get the singular form of an English word. * * @param string $value * @return string */ function str_singular($value) { return Str::singular($value); }
/** * Get the correct class to call according to the created field * * @param string $method The field created * * @return string The correct class */ protected function getClassFromMethod($method) { // If the field's name directly match a class, call it $class = Str::singular(Str::title($method)); $studly_class = Str::singular(Str::studly($method)); foreach ($this->repositories as $repository) { if (class_exists($repository . $studly_class)) { return $repository . $studly_class; } else { if (class_exists($repository . $class)) { return $repository . $class; } } } // Else convert known fields to their classes switch ($method) { case 'submit': case 'link': case 'reset': $class = Former::FIELDSPACE . 'Button'; break; case 'multiselect': $class = Former::FIELDSPACE . 'Select'; break; default: $class = Former::FIELDSPACE . 'Input'; break; } return $class; }