protected function makeCustomPostType(Post $model) { $postTypeSlug = strtolower(snake_case(class_basename($model))); if ($model instanceof CustomPostType) { $singular = property_exists($model, 'singular') ? $model->singular : str_replace(['-', '_'], ' ', $postTypeSlug); $plural = property_exists($model, 'plural') ? $model->plural : str_plural(str_replace(['-', '_'], ' ', $postTypeSlug)); $postTypeData = $model->customPostTypeData(); if (!is_array($postTypeData)) { $postTypeData = []; } $result = register_post_type($postTypeSlug, $this->buildPostTypeData($singular, $plural, $postTypeData)); if (!$result instanceof \WP_Error) { $this->postTypes[$postTypeSlug] = get_class($model); if (property_exists($model, 'placeholderText')) { add_filter('enter_title_here', function ($default) use($postTypeSlug, $model) { if ($postTypeSlug == get_current_screen()->post_type) { $default = $model->placeholderText; } return $default; }); } } } else { $this->postTypes[$postTypeSlug] = get_class($model); } }
/** * Build the class name from the migration file. * * @todo Find a better way than doing this. This feels so icky all over * whenever I look back at this. * Maybe I can find something that's actually in native Laravel * database classes. * * @param string $file * @return Migration */ private function createMigration(string $file) { $basename = str_replace('.php', '', class_basename($file)); $filename = substr($basename, 18); $classname = studly_case($filename); return new $classname(); }
/** * Prepare the widgets used by this action * @param Model $model * @return void */ public function initForm($model) { $context = $this->formGetContext(); $config = $this->makeConfig($this->config->form); $config->model = $model; $config->arrayName = class_basename($model); $config->context = $context; /* * Form Widget with extensibility */ $this->formWidget = $this->makeWidget('Backend\\Widgets\\Form', $config); $this->formWidget->bindEvent('form.extendFieldsBefore', function () { $this->controller->formExtendFieldsBefore($this->formWidget); }); $this->formWidget->bindEvent('form.extendFields', function () { $this->controller->formExtendFields($this->formWidget); }); $this->formWidget->bindEvent('form.beforeRefresh', function ($saveData) { return $this->controller->formExtendRefreshData($this->formWidget, $saveData); }); $this->formWidget->bindEvent('form.refresh', function ($result) { return $this->controller->formExtendRefreshResults($this->formWidget, $result); }); $this->formWidget->bindToController(); /* * Detected Relation controller behavior */ if ($this->controller->isClassExtendedWith('Backend.Behaviors.RelationController')) { $this->controller->initRelation($model); } $this->prepareVars($model); }
/** * Send the given notification. * * @param mixed $notifiable * @param \Illuminate\Notifications\Notification $notification * @return void */ public function send($notifiable, Notification $notification) { if (!$notifiable->routeNotificationFor('mail')) { return; } $message = $notification->toMail($notifiable); if ($message instanceof Mailable) { return $message->send($this->mailer); } $this->mailer->send($message->view, $message->data(), function ($m) use($notifiable, $notification, $message) { $recipients = empty($message->to) ? $notifiable->routeNotificationFor('mail') : $message->to; if (!empty($message->from)) { $m->from($message->from[0], isset($message->from[1]) ? $message->from[1] : null); } if (is_array($recipients)) { $m->bcc($recipients); } else { $m->to($recipients); } $m->subject($message->subject ?: Str::title(Str::snake(class_basename($notification), ' '))); foreach ($message->attachments as $attachment) { $m->attach($attachment['file'], $attachment['options']); } foreach ($message->rawAttachments as $attachment) { $m->attachData($attachment['data'], $attachment['name'], $attachment['options']); } }); }
/** * Set the parent -> child relation. * * @param string $relation * @param Eloquent $parent */ public function setRelation($relation, $parent) { $this->relation = $relation; $function_call = call_user_func_array([$parent, $relation], []); $type = class_basename(get_class($function_call)); switch ($type) { case 'BelongsTo': $this->is_parent = true; $this->pivot_table = null; $this->local_key_attribute = $function_call->getForeignKey(); $this->parent_key_attribute = $function_call->getOtherKey(); break; case 'BelongsToMany': $this->is_parent = false; $this->pivot_table = $function_call->getTable(); $this->local_key_attribute = $function_call->getOtherKey(); $this->parent_key_attribute = $function_call->getForeignKey(); break; case 'HasOne': case 'HasMany': $this->is_parent = false; $this->pivot_table = null; $this->parent_key_attribute = $function_call->getPlainForeignKey(); break; default: throw new Exception('Unhandled relation type'); break; } $this->setModel($function_call->getRelated()); }
public function format(array $record) { $vars = $this->normalize($record); $output = $this->format; if (isset($record['context']['exception']) && in_array(class_basename($record['context']['exception']), \Config::get('laraext.log.skip_trace'))) { $vars['message'] = get_class($record['context']['exception']) . ":" . $record['context']['exception']->getMessage(); } if (\App::isBooted() && \Auth::check()) { $vars['user'] = \Auth::user()->id; } else { $vars['user'] = "******"; } foreach ($vars['extra'] as $var => $val) { if (false !== strpos($output, '%extra.' . $var . '%')) { $output = str_replace('%extra.' . $var . '%', $this->stringify($val), $output); unset($vars['extra'][$var]); } } if ($this->ignoreEmptyContextAndExtra) { if (empty($vars['context'])) { unset($vars['context']); $output = str_replace('%context%', '', $output); } if (empty($vars['extra'])) { unset($vars['extra']); $output = str_replace('%extra%', '', $output); } } foreach ($vars as $var => $val) { if (false !== strpos($output, '%' . $var . '%')) { $output = str_replace('%' . $var . '%', $this->stringify($val), $output); } } return $output; }
public static function boot() { parent::boot(); static::creating(function ($model) { $carpayment = CarPayment::find($model->carpaymentid); $model->provinceid = $carpayment->provinceid; $model->branchid = $carpayment->branchid; $model->createdby = Auth::user()->id; $model->createddate = date("Y-m-d H:i:s"); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::created(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Add', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::updating(function ($model) { $carpayment = CarPayment::find($model->carpaymentid); $model->provinceid = $carpayment->provinceid; $model->branchid = $carpayment->branchid; $model->accountingDetailReceiveAndPays()->delete(); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::updated(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Update', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::deleting(function ($model) { $model->accountingDetailReceiveAndPays()->delete(); }); static::deleted(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Delete', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); }
/** * Returns attributes for the resource * * @return mixed[] */ public function getResourceAttributes() { $attributes = $this->attributesToArray(); // detect any translated attributes if (in_array(config('jsonapi.encoding.translatable_trait'), class_uses($this))) { foreach ($this->translatedAttributes as $key) { $attributes[$key] = $this->{$key}; } } // unset primary key field unset($attributes[$this->getKeyName()]); // unset reserved fieldname "type" // reset it as modelname-type if that is not in use yet if (array_key_exists('type', $attributes)) { $typeRecast = Str::snake(class_basename($this) . '-type', '-'); if (!array_key_exists($typeRecast, $attributes)) { $attributes[$typeRecast] = $attributes['type']; } unset($attributes['type']); } // map all fieldnames to dasherized case foreach ($attributes as $key => $value) { $dasherized = str_replace('_', '-', $key); if ($key !== $dasherized) { $attributes[$dasherized] = $value; unset($attributes[$key]); } } return $attributes; }
public function byDefault($site = null) { $model = $this->getModel(); $modelName = strtolower(class_basename($model)); $pref = $modelName != 'site' ? $modelName . ':' : ''; if (empty($site)) { $settings = !empty($model->id) ? $model->getSettings() : Model\Site::$site->getSettings(); } else { $settings = $site->getSettings(); } if (!empty($settings)) { $count = !empty($settings['site'][$pref . 'count']) ? $settings['site'][$pref . 'count'] : 0; $pagination = !empty($settings['site'][$pref . 'pagination']) ? $settings['site'][$pref . 'pagination'] : 0; $sort_fields = !empty($settings['site'][$pref . 'sort_fields']) ? $settings['site'][$pref . 'sort_fields'] : ''; $sort_type = !empty($settings['site'][$pref . 'sort_type']) ? $settings['site'][$pref . 'sort_type'] : ''; if ($sort_type == 'RAND()') { $this->orderBy(DB::raw('RAND()')); } else { if ($sort_fields) { $sort_type ? $this->orderBy($sort_fields, $sort_type) : $this->orderBy($sort_fields); } } if ($count) { $pagination ? $this->paginate($count) : $this->take($count); } } return $this; }
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { // 404 page when a model is not found if ($e instanceof ModelNotFoundException) { if ($request->ajax() || $request->wantsJson()) { return response()->json(['error' => 404, 'mensaje' => 'Recurso no encontrado'], 404); } return response()->view('errors.404', [], 404); } if ($this->isHttpException($e)) { if ($request->ajax() || $request->wantsJson()) { return response()->json(['error' => 404, 'mensaje' => 'Recurso no encontrado!'], 404); } return $this->renderHttpException($e); } else { // Custom error 500 view on production if (app()->environment() == 'production') { if ($request->ajax() || $request->wantsJson()) { return response()->json(['error' => ['exception' => class_basename($e) . ' in ' . basename($e->getFile()) . ' line ' . $e->getLine() . ': ' . $e->getMessage()]], 500); } return response()->view('errors.500', [], 500); } return parent::render($request, $e); } }
/** * Returns an array of registered fields, keyed by field slug, * values in readable format * * @return array */ public function getFieldTypes() { return array_map(function ($value) { $class_name = class_basename($value); return ucfirst(strtolower(preg_replace('/\\B([A-Z])/', ' $1', $class_name))); }, $this->getRegistrar()->getRegisteredFields()); }
/** * Get the primary key for the model. * * @return string */ public function getKeyName() { if (isset($this->primaryKey)) { return $this->primaryKey; } return 'id_' . str_replace('\\', '', snake_case(class_basename($this))); }
/** * Create a new event instance. * * @return void */ public function __construct($location, User $user) { $this->user = $user; //sukuriam paminejima duomenu bazeje. $mention = \maze\Mention::create(['user_id' => $user->id, 'object_type' => class_basename($location), 'object_id' => $location->id]); $this->notifiable = $mention; }
public function article($category_slug, $slug) { $key = snake_case(class_basename($this) . '_' . __FUNCTION__ . '_' . $category_slug . '_' . $slug); if ($this->cache->has($key)) { $view = $this->cache->get($key); } else { $category = $this->category->where('slug', $category_slug)->first(); $filters = [['name' => 'enabled', 'value' => 1], ['name' => 'slug', 'value' => $slug]]; if (is_object($category)) { $category_id = $category->id; $filters[] = ['name' => 'category_id', 'value' => $category_id]; } if ($this->cache->has($slug)) { $content = $this->cache->get($slug); } else { $content = $this->content->filterAll($filters); if ($content->count()) { $content = $content->first(); } else { return redirect()->route('404'); } $this->cache->put($slug, $content, 60); } $content->category = $category; $view = view('pages.content_show', compact('content'))->render(); } return $view; }
/** * 系统的默认表名会将类名变为复数,如 org 将会变为 orgs; * 复写该类取消这一功能,声明 Model 时将类名与表名保持一致即可 */ public function getTable() { if (isset($this->table)) { return $this->table; } return str_replace('\\', '', Str::snake(class_basename($this))); }
/** * Get the collection name associated with the model. * * @return string */ public function getCollection() { if (isset($this->collection)) { return $this->collection; } return str_replace('\\', '', snake_case(str_plural(class_basename($this)))); }
public static function boot() { parent::boot(); static::creating(function ($model) { $carpreemption = CarPreemption::find($model->carpreemptionid); $model->provinceid = $carpreemption->provinceid; $model->branchid = $carpreemption->branchid; $model->createdby = Auth::user()->id; $model->createddate = date("Y-m-d H:i:s"); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::created(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Add', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); $carpreemption = CarPreemption::find($model->carpreemptionid); $carpreemption->status = 2; $carpreemption->save(); }); static::updating(function ($model) { $carpreemption = CarPreemption::find($model->carpreemptionid); $model->provinceid = $carpreemption->provinceid; $model->branchid = $carpreemption->branchid; $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::updated(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Update', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::deleted(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Delete', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); $carpreemption = CarPreemption::find($model->carpreemptionid); $carpreemption->status = 0; $carpreemption->save(); }); }
/** * Get the segments of the option field. * * @param string $field * @return array * @throws \Exception */ private function parseSegments($field) { $field = starts_with('\\', $field) ? $field : '\\' . $field; $segments = explode(':', $field); if (count($segments) < 2) { throw new \Exception('--includes option should be consist of string value of model, separated by colon(:), and string value of relationship. e.g. App\\User:author, App\\Comment:comments:true. If the third element is provided as true, yes, or 1, the command will interpret the include as an collection.'); } $fqcn = array_shift($segments); // if (! class_exists($fqcn)) { // throw new \Exception( // 'Not existing Model - ' . $fqcn // ); // } $relationship = array_shift($segments); $type = in_array(array_shift($segments), ['yes', 'y', 'true', true, '1', 1]) ? 'collection' : 'item'; $namespace = config('api.transformer.namespace'); $namespace = starts_with($namespace, '\\') ? $namespace : '\\' . $namespace; $namespace = ends_with($namespace, '\\') ? $namespace : $namespace . '\\'; $obj = new \stdClass(); $obj->type = $type; $obj->fqcn = $fqcn; $obj->model = ltrim($fqcn, '\\'); $obj->basename = class_basename($fqcn); $obj->relationship = $relationship; $obj->method = 'include' . ucfirst($relationship); $obj->transformer = $namespace . ucfirst($obj->basename) . 'Transformer'; return $obj; }
public static function boot() { parent::boot(); static::creating(function ($model) { if ($model->carsubmodelid == 0) { CommissionExtraCar::where('commissionextraid', $model->commissionextraid)->where('carmodelid', $model->carmodelid)->delete(); } $model->createdby = Auth::user()->id; $model->createddate = date("Y-m-d H:i:s"); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::created(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Add', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::updating(function ($model) { if ($model->carsubmodelid == 0) { CommissionExtraCar::where('id', '!=', $model->id)->where('commissionextraid', $model->commissionextraid)->where('carmodelid', $model->carmodelid)->delete(); } $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::updated(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Update', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::deleted(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Delete', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); }
function getControllerName() { $action = app('request')->route()->getAction(); $controller = class_basename($action['controller']); list($controller, $action) = explode('@', $controller); return $controller; }
/** * @param $id * @return Model|null * * Eloquent implementation for getInstance method for ParsableInterface * Returns a model instance based on identifier */ public function getInstance($id) { if (class_exists($repoClassName = "App\\Repositories\\" . class_basename($this) . "Repository")) { return (new $repoClassName())->find($id); } return $this->find($id); }
/** * Execute the job. */ public function handle() { // Find the tracking record for this job. If there // is none, simply return and do nothing. if (!$this->trackOrDismiss()) { return; } // Do the update work and catch any errors // that may come of it. $this->updateJobStatus(['status' => 'Working']); // Attempt to run the Updaters based on the // type of key we are working with. foreach ($this->load_workers() as $worker) { try { $this->updateJobStatus(['output' => 'Processing: ' . class_basename($worker)]); // Perform the update (new $worker())->call(); $this->decrementErrorCounters(); } catch (APIException $e) { // If we should not continue, simply return. if (!$this->handleApiException($e)) { return; } continue; } catch (ConnectionException $e) { $this->handleConnectionException($e); continue; } } // Foreach worker // Mark the Job as complete. $this->updateJobStatus(['status' => 'Done', 'output' => null]); }
public function changeString($format = null, \Closure $replacements = null) { $change = $this->change; if (is_string($change)) { $change = ['a' => $change, self::C_OLD => null, self::C_NEW => null]; } if ($replacements) { if (!($change = $replacements($change))) { return ''; } } if (!$format) { $class = strtolower(class_basename($this)); $types = [self::U_ADDED => 'add', self::U_DELETED => 'delete']; $type = @$types[$this->type] ?: 'change'; $path = [$class, $type]; if ($attr = @$change['a']) { $path[] = $attr; } while ($path) { if (Lang::has($key = "updates." . join('.', $path))) { break; } else { $key = null; } array_shift($path); } $format = Lang::get($key ?: "updates.change"); } return preg_replace_callback(['"\\{:([\\w\\d_]+)\\}"', '":([\\w\\d_]+)"'], function ($match) use($change) { return isset($change[$match[1]]) ? $change[$match[1]] : null; }, $format); }
/** * Get the collection associated with the model. * * @return string */ public function getCollectionName() { if (static::$collection) { return static::$collection; } return str_replace('\\', '', Str::snake(Str::plural(class_basename($this)))); }
/** * Build the class with the given name. * * @param string $name * @return string */ protected function buildClass($name) { $stub = parent::buildClass($name); $stub = str_replace('DummyCommand', class_basename($this->option('command')), $stub); $stub = str_replace('DummyFullCommand', $this->option('command'), $stub); return $stub; }
protected function setCommonVariable() { // Achieve that segment $this->accessUrl = config('cmsharenjoy.access_url'); // Get the action name $routeArray = Str::parseCallback(Route::currentRouteAction(), null); if (last($routeArray) != null) { // Remove 'controller' from the controller name. $controller = str_replace('Controller', '', class_basename(head($routeArray))); // Take out the method from the action. $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', last($routeArray)); // post, report $this->onController = strtolower($controller); session()->put('onController', $this->onController); view()->share('onController', $this->onController); // get-create, post-create $this->onMethod = Str::slug(Request::method() . '-' . $action); session()->put('onMethod', $this->onMethod); view()->share('onMethod', $this->onMethod); // create, update $this->onAction = strtolower($action); session()->put('onAction', $this->onAction); view()->share('onAction', $this->onAction); } // Brand name from setting $this->brandName = Setting::get('brand_name'); // Share some variables to views view()->share('brandName', $this->brandName); view()->share('langLocales', config('cmsharenjoy.locales')); view()->share('activeLanguage', session('sharenjoy.backEndLanguage')); // Set the theme // $this->theme = Theme::uses('front'); // Message view()->share('messages', Message::getMessageBag()); }
public function checkPermission() { $request = app('request'); if (isset($request)) { $route = $request->route(); if (isset($route)) { $action = $route->getAction(); $controller = class_basename($action['controller']); list($controller, $action) = explode('Controller@', $controller); $this->permission = strtolower($controller); if (isset($this->actionList[strtolower($request->method())])) { $this->actionName = $this->actionList[strtolower($request->method())]; } } } JWTAuth::parseToken(); //echo $this->actionName.'.'.$this->permission; // and you can continue to chain methods $user = JWTAuth::parseToken()->authenticate(); if ($user->can($this->actionName . '.' . $this->permission)) { // you can pass an id or slug return true; } else { return false; } }
public function __construct() { $urlname = get_class($this); $urlname = class_basename($urlname); $this->urlname = Str::lower($urlname); $this->name = trans('groups.' . $this->urlname); }
public static function boot() { parent::boot(); static::creating(function ($model) { $model->effectivefrom = date('Y-m-d', strtotime($model->effectivefrom)); $model->effectiveto = date('Y-m-d', strtotime($model->effectiveto)); $model->createdby = Auth::user()->id; $model->createddate = date("Y-m-d H:i:s"); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::created(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Add', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::updating(function ($model) { $model->effectivefrom = date('Y-m-d', strtotime($model->effectivefrom)); $model->effectiveto = date('Y-m-d', strtotime($model->effectiveto)); $model->modifiedby = Auth::user()->id; $model->modifieddate = date("Y-m-d H:i:s"); }); static::updated(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Update', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); static::deleted(function ($model) { Log::create(['employeeid' => Auth::user()->id, 'operation' => 'Delete', 'date' => date("Y-m-d H:i:s"), 'model' => class_basename(get_class($model)), 'detail' => $model->toJson()]); }); }
/** * Get the default foreign key name for the model. * * @return string */ public function getForeignKey() { if (empty($this->foreignKey)) { return Str::snake(class_basename($this)) . '_id'; } return $this->foreignKey; }