sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function _print_gutenberg_styles() { $screen = get_current_screen(); if ( ! $screen || 'post' !== $screen->base ) { return; } $post = get_post(); $use_gutenberg_plugin = function_exists( '\is_gutenberg_page' ) && \is_gutenberg_page(); $use_block_editor = function_exists( '\use_block_editor_for_post' ) && \use_block_editor_for_post( $post ); if ( ! $post || ! $use_gutenberg_plugin && ! $use_block_editor ) { return; } echo '<style id="wp-customizer-framework-print-styles">'; do_action( 'inc2734_wp_customizer_framework_print_gutenberg_styles' ); echo '</style>'; }
Print styles from registerd styles @return void
entailment
public function _customize_register( \WP_Customize_Manager $wp_customize ) { $controls = Control_Manager::get_controls(); foreach ( $controls as $control ) { $wp_customize->add_setting( $control->get_id(), $control->get_setting_args() ); if ( ! $control->section() ) { continue; } $control->register_control( $wp_customize ); $section = $control->section(); $panel = $section->panel(); $args = $section->get_args(); if ( ! empty( $panel ) ) { $args = array_merge( $args, [ 'panel' => $panel->get_id(), ] ); } if ( ! $wp_customize->get_section( $section->get_id() ) && $args ) { $wp_customize->add_section( $section->get_id(), $args ); } if ( ! empty( $panel ) && ! $wp_customize->get_panel( $panel->get_id() ) ) { $wp_customize->add_panel( $panel->get_id(), $panel->get_args() ); } $partial = $control->partial(); if ( $partial ) { $wp_customize->selective_refresh->add_partial( $partial->get_id(), $partial->get_args() ); } } }
Setup customizer @param WP_Customize_Manager $wp_customize @return void
entailment
public function setDomainResults($users, Domain $domain, $val, $info='') { if (!is_array($users)) { $users = (array)$users; } foreach ($users as $user) { $this->results[$user . '@' . $domain->getDomain()] = array( 'result' => $val, 'info' => $info ); } }
Helper to set results for all the users on a domain to a specific value @param array $users Array of users (usernames) @param Domain $domain The domain @param int $val Value to set 1 or 0 ( Valid,Invalid ) @param String $info Optional , can be used to give additional information about the result
entailment
protected function getOtherKey() { if ($this->otherKey) { return $this->otherKey; } if (is_callable([$this->form->model(), $this->column]) && ($relation = $this->form->model()->{$this->column}()) instanceof BelongsToMany ) { /* @var BelongsToMany $relation */ $fullKey = $relation->getQualifiedRelatedPivotKeyName(); return $this->otherKey = substr($fullKey, strpos($fullKey, '.') + 1); } throw new \Exception('Column of this field must be a `BelongsToMany` relation.'); }
Get other key for this many-to-many relation. @throws \Exception @return string
entailment
public function view($id) { $this->builder->setMode(Builder::MODE_VIEW); $this->builder->setResourceId($id); $this->setFieldValue($id); return $this; }
@param $id @return $this
entailment
public function destroy($id) { $ids = explode(',', $id); foreach ($ids as $id) { if (empty($id)) { continue; } $this->deleteFilesAndImages($id); $this->model->find($id)->delete(); } return true; }
Destroy data entity and remove files. @param $id @return mixed
entailment
protected function deleteFilesAndImages($id) { $data = $this->model->with($this->getRelations()) ->findOrFail($id)->toArray(); $this->builder->fields()->filter(function ($field) { return $field instanceof Field\File; })->each(function (File $file) use ($data) { $file->setOriginal($data); $file->destroy(); }); }
Remove files or images in record. @param $id
entailment
public function store() { $data = Input::all(); // Handle validation errors. if ($validationMessages = $this->validationMessages($data)) { return back()->withInput()->withErrors($validationMessages); } if (($response = $this->prepare($data)) instanceof Response) { return $response; } DB::transaction(function () { $inserts = $this->prepareInsert($this->updates); foreach ($inserts as $column => $value) { $this->model->setAttribute($column, $value); } $this->model->save(); $this->updateRelation($this->relations); }); if (($response = $this->complete($this->saved)) instanceof Response) { return $response; } if ($response = $this->ajaxResponse(trans('admin.save_succeeded'))) { return $response; } return $this->redirectAfterStore(); }
Store a new record. @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\Http\JsonResponse
entailment
protected function getRelationInputs($inputs = []) { $relations = []; foreach ($inputs as $column => $value) { if (method_exists($this->model, $column)) { $relation = call_user_func([$this->model, $column]); if ($relation instanceof Relation) { $relations[$column] = $value; } } } return $relations; }
Get inputs for relations. @param array $inputs @return array
entailment
protected function handleEditable(array $input = []) { if (array_key_exists('_editable', $input)) { $name = $input['name']; $value = $input['value']; array_forget($input, ['pk', 'value', 'name']); array_set($input, $name, $value); } return $input; }
Handle editable update. @param array $input @return array
entailment
protected function handleFileDelete(array $input = []) { if (array_key_exists(Field::FILE_DELETE_FLAG, $input)) { $input[Field::FILE_DELETE_FLAG] = $input['key']; unset($input['key']); } Input::replace($input); return $input; }
@param array $input @return array
entailment
protected function handleOrderable($id, array $input = []) { if (array_key_exists('_orderable', $input)) { $model = $this->model->find($id); if ($model instanceof Sortable) { 1 === $input['_orderable'] ? $model->moveOrderUp() : $model->moveOrderDown(); return true; } } return false; }
Handle orderable update. @param int $id @param array $input @return bool
entailment
protected function prepareUpdate(array $updates, $oneToOneRelation = false) { $prepared = []; foreach ($this->builder->fields() as $field) { $columns = $field->column(); // If column not in input array data, then continue. if (!array_has($updates, $columns)) { continue; } if ($this->invalidColumn($columns, $oneToOneRelation)) { continue; } $value = $this->getDataByColumn($updates, $columns); $value = $field->prepare($value); if (is_array($columns)) { foreach ($columns as $name => $column) { array_set($prepared, $column, $value[$name]); } } elseif (is_string($columns)) { array_set($prepared, $columns, $value); } } return $prepared; }
Prepare input data for update. @param array $updates @param bool $oneToOneRelation if column is one-to-one relation @return array
entailment
protected function prepareInsert($inserts) { if ($this->isHasOneRelation($inserts)) { $inserts = array_dot($inserts); } foreach ($inserts as $column => $value) { if (is_null($field = $this->getFieldByColumn($column))) { unset($inserts[$column]); continue; } $inserts[$column] = $field->prepare($value); } $prepared = []; foreach ($inserts as $key => $value) { array_set($prepared, $key, $value); } return $prepared; }
Prepare input data for insert. @param $inserts @return array
entailment
protected function getDataByColumn($data, $columns) { if (is_string($columns)) { return array_get($data, $columns); } if (is_array($columns)) { $value = []; foreach ($columns as $name => $column) { if (!array_has($data, $column)) { continue; } $value[$name] = array_get($data, $column); } return $value; } }
@param array $data @param string|array $columns @return array|mixed
entailment
protected function getFieldByColumn($column) { return $this->builder->fields()->first( function (Field $field) use ($column) { if (is_array($field->column())) { return in_array($column, $field->column(), true); } return $field->column() === $column; } ); }
Find field object by column. @param $column @return mixed
entailment
protected function setFieldValue($id) { $relations = $this->getRelations(); $this->model = $this->model->with($relations)->findOrFail($id); // static::doNotSnakeAttributes($this->model); $data = $this->model->toArray(); $this->builder->fields()->each(function (Field $field) use ($data) { $field->fill($data); }); }
Set all fields value in form. @param $id
entailment
public function getRelations() { $relations = $columns = []; foreach ($this->builder->fields() as $field) { $columns[] = $field->column(); } foreach (array_flatten($columns) as $column) { if (str_contains($column, '.')) { list($relation) = explode('.', $column); if (method_exists($this->model, $relation) && $this->model->$relation() instanceof Relation ) { $relations[] = $relation; } } elseif (method_exists($this->model, $column) && !method_exists(Model::class, $column) ) { $relations[] = $column; } } return array_unique($relations); }
Get all relations of model from callable. @return array
entailment
public function input($key, $value = null) { if (is_null($value)) { return array_get($this->inputs, $key); } return array_set($this->inputs, $key, $value); }
Get or set input data. @param string $key @param null $value @return array|mixed
entailment
public static function registerBuiltinFields() { $map = [ 'button' => \Jblv\Admin\Form\Field\Button::class, 'checkbox' => \Jblv\Admin\Form\Field\Checkbox::class, 'color' => \Jblv\Admin\Form\Field\Color::class, 'currency' => \Jblv\Admin\Form\Field\Currency::class, 'date' => \Jblv\Admin\Form\Field\Date::class, 'dateRange' => \Jblv\Admin\Form\Field\DateRange::class, 'datetime' => \Jblv\Admin\Form\Field\Datetime::class, 'dateTimeRange' => \Jblv\Admin\Form\Field\DatetimeRange::class, 'datetimeRange' => \Jblv\Admin\Form\Field\DatetimeRange::class, 'decimal' => \Jblv\Admin\Form\Field\Decimal::class, 'display' => \Jblv\Admin\Form\Field\Display::class, 'divider' => \Jblv\Admin\Form\Field\Divide::class, 'divide' => \Jblv\Admin\Form\Field\Divide::class, 'embeds' => \Jblv\Admin\Form\Field\Embeds::class, 'editor' => \Jblv\Admin\Form\Field\Editor::class, 'email' => \Jblv\Admin\Form\Field\Email::class, 'file' => \Jblv\Admin\Form\Field\File::class, 'hasMany' => \Jblv\Admin\Form\Field\HasMany::class, 'hidden' => \Jblv\Admin\Form\Field\Hidden::class, 'id' => \Jblv\Admin\Form\Field\Id::class, 'image' => \Jblv\Admin\Form\Field\Image::class, 'ip' => \Jblv\Admin\Form\Field\Ip::class, 'map' => \Jblv\Admin\Form\Field\Map::class, 'mobile' => \Jblv\Admin\Form\Field\Mobile::class, 'month' => \Jblv\Admin\Form\Field\Month::class, 'multipleSelect' => \Jblv\Admin\Form\Field\MultipleSelect::class, 'number' => \Jblv\Admin\Form\Field\Number::class, 'password' => \Jblv\Admin\Form\Field\Password::class, 'radio' => \Jblv\Admin\Form\Field\Radio::class, 'rate' => \Jblv\Admin\Form\Field\Rate::class, 'select' => \Jblv\Admin\Form\Field\Select::class, 'slider' => \Jblv\Admin\Form\Field\Slider::class, 'switch' => \Jblv\Admin\Form\Field\SwitchField::class, 'text' => \Jblv\Admin\Form\Field\Text::class, 'textarea' => \Jblv\Admin\Form\Field\Textarea::class, 'time' => \Jblv\Admin\Form\Field\Time::class, 'timeRange' => \Jblv\Admin\Form\Field\TimeRange::class, 'url' => \Jblv\Admin\Form\Field\Url::class, 'year' => \Jblv\Admin\Form\Field\Year::class, 'html' => \Jblv\Admin\Form\Field\Html::class, 'tags' => \Jblv\Admin\Form\Field\Tags::class, 'icon' => \Jblv\Admin\Form\Field\Icon::class, 'multipleFile' => \Jblv\Admin\Form\Field\MultipleFile::class, 'multipleImage' => \Jblv\Admin\Form\Field\MultipleImage::class, 'captcha' => \Jblv\Admin\Form\Field\Captcha::class, 'listbox' => \Jblv\Admin\Form\Field\Listbox::class, ]; foreach ($map as $abstract => $class) { static::extend($abstract, $class); } }
Register builtin fields.
entailment
public static function collectFieldAssets() { if (!empty(static::$collectedAssets)) { return static::$collectedAssets; } $css = collect(); $js = collect(); foreach (static::$availableFields as $field) { if (!method_exists($field, 'getAssets')) { continue; } $assets = call_user_func([$field, 'getAssets']); $css->push(array_get($assets, 'css')); $js->push(array_get($assets, 'js')); } return static::$collectedAssets = [ 'css' => $css->flatten()->unique()->filter()->toArray(), 'js' => $js->flatten()->unique()->filter()->toArray(), ]; }
Collect assets required by registered field. @return array
entailment
public function condition($inputs) { if (!array_has($inputs, $this->column)) { return; } $this->value = array_get($inputs, $this->column); $value = array_filter($this->value, function ($val) { return '' !== $val; }); if (empty($value)) { return; } if (!isset($value['start'])) { return $this->buildCondition($this->column, '<=', $value['end']); } if (!isset($value['end'])) { return $this->buildCondition($this->column, '>=', $value['start']); } $this->query = 'whereBetween'; return $this->buildCondition($this->column, $this->value); }
Get condition of this filter. @param array $inputs @return mixed
entailment
public function authenticate(array $data) { $this->rules = [ 'email' => 'required|email', 'password' => 'required', ]; $remember = false; if (isset($data['remember'])) { $remember = $data['remember']; } $this->validate($data); if (!$user = $this->sentinel->authenticate($data, $remember)) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.incorrect')); } return $user; }
{@inheritDoc}
entailment
public function register(array $data, $validate = true) { $this->rules = [ 'email' => 'required|unique:users', 'password' => 'required|confirmed', 'password_confirmation' => 'required', ]; if ($validate) { $this->validate($data); } if (!config('laraflock.dashboard.activations')) { $this->registerAndActivate($data, false); return true; } try { $user = $this->sentinel->register($data); } catch (QueryException $e) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.create')); } if (!$user instanceof EloquentUser) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.create')); } if (!isset($data['role'])) { $data['role'] = config('laraflock.dashboard.defaultRole'); } if (!$role = $this->sentinel->findRoleBySlug($data['role'])) { throw new RolesException(trans('dashboard::dashboard.errors.role.found')); } $role->users() ->attach($user); if (!$activation = $this->illuminateActivationRepository->create($user)) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.activation.create')); } return $activation; }
{@inheritDoc}
entailment
public function registerAndActivate(array $data, $validate = true) { $this->rules = [ 'email' => 'required|unique:users', 'password' => 'required|confirmed', 'password_confirmation' => 'required', ]; if ($validate) { $this->validate($data); } try { $user = $this->sentinel->registerAndActivate($data); } catch (QueryException $e) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.create')); } if (!isset($data['role'])) { $data['role'] = config('laraflock.dashboard.defaultRole'); } if (!$role = $this->sentinel->findRoleBySlug($data['role'])) { throw new RolesException(trans('dashboard::dashboard.errors.role.found')); } $role->users() ->attach($user); return; }
{@inheritDoc}
entailment
public function activate(array $data, $validate = true) { $this->rules = [ 'email' => 'required|email', 'activation_code' => 'required', ]; if ($validate) { $this->validate($data); } $user = $this->findByCredentials(['login' => $data['email']]); if (!$this->illuminateActivationRepository->complete($user, $data['activation_code'])) { throw new AuthenticationException(trans('dashboard::dashboard.errors.auth.activation.complete')); } return true; }
{@inheritDoc}
entailment
public function column($width, $content) { $column = new Column($content, $width); $this->addColumn($column); }
Add a column. @param int $width @param $content
entailment
public function getData() { $this->validate('merchantId', 'merchantKey'); $data = array(); $data['merchantid'] = $this->getMerchantId(); $data['merchantkey'] = $this->getMerchantKey(); $data['sha1'] = $this->generateSignature(); return $data; }
{@inheritdoc}
entailment
public function create(array $data, $validate = true) { $this->rules = [ 'name' => 'required', 'slug' => 'required|unique:permissions', ]; if ($validate) { $this->validate($data); } try { $permission = $this->permission->create($data); } catch (QueryException $e) { throw new PermissionsException(trans('dashboard::dashboard.errors.permission.create')); } return $permission; }
{@inheritDoc}
entailment
public function update(array $data, $id, $validate = true) { if (!$permission = $this->getById($id)) { throw new PermissionsException(trans('dashboard::dashboard.errors.permission.found')); } $this->rules = [ 'name' => 'required', 'slug' => 'required|alpha_dash', ]; if ($permission->slug != $data['slug']) { $this->rules['slug'] = 'required|alpha_dash|unique:permissions'; } if ($validate) { $this->validate($data); } $permission->name = $data['name']; $permission->slug = $data['slug']; $permission->save(); return $permission; }
{@inheritDoc}
entailment
public function delete($id) { if (!$permission = $this->getById($id)) { throw new PermissionsException(trans('dashboard::dashboard.errors.permission.found')); } $permission->delete(); return true; }
{@inheritDoc}
entailment
private function renderDirectoryItem(string $name, string $link, ResultAggregateInterface $result, string $pathToRoot): string { $deadCount = $result->getDeadCount(); $undeadCount = $result->getUndeadCount(); $totalCount = $deadCount + $undeadCount; $class = 'success'; if ($undeadCount) { if ($undeadCount < $totalCount) { $class = 'warning'; } else { $class = 'danger'; } } $bar = $this->renderBar($deadCount, $totalCount); $this->directoryItemTemplate->setVar([ 'name' => $name, 'path_to_root' => $pathToRoot, 'icon' => $result instanceof AnalyzerFileResult ? 'code' : 'directory', 'link' => $link, 'class' => $class, 'bar' => $bar, 'total' => $totalCount, 'numDead' => $deadCount, 'numUndead' => $undeadCount, ]); return $this->directoryItemTemplate->render(); }
@param string $name @param string $link @param ResultAggregateInterface $result @param string $pathToRoot @return string
entailment
public function store(Request $request) { try { $this->roleRepositoryInterface->create($request->all()); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('roles.create') ->withErrors($e->getErrors()) ->withInput(); } Flash::success(trans('dashboard::dashboard.flash.role.create.success')); return redirect()->route('roles.index'); }
Store a newly created resource in storage. @param Request $request @return $this
entailment
public function edit($id) { if (!$role = $this->roleRepositoryInterface->getById($id)) { Flash::error(trans('dashboard::dashboard.errors.role.found')); return redirect()->route('roles.index'); } $permissions = $this->permissionRepositoryInterface->getAll(); return $this->view('roles.edit')->with(['role' => $role, 'permissions' => $permissions]); }
Show the form for editing the specified resource. @param int $id @return Response
entailment
public function delete($id) { try { $this->roleRepositoryInterface->delete($id); } catch (RolesException $e) { Flash::error($e->getMessage()); return redirect()->route('roles.index'); } Flash::success(trans('dashboard::dashboard.flash.role.delete.success')); return redirect()->route('roles.index'); }
Remove the specified resource from storage. @param int $id @return \Illuminate\Http\RedirectResponse
entailment
public function condition($inputs) { $value = array_get($inputs, $this->column); if (is_null($value)) { return; } $this->value = $value; return $this->buildCondition($this->column, '>=', $this->value); }
Get condition of this filter. @param array $inputs @return array|mixed|void
entailment
public function condition($inputs) { $value = array_get($inputs, $this->column ?: static::getQueryHash($this->where, $this->label)); if (is_null($value)) { return; } $this->input = $this->value = $value; return $this->buildCondition($this->where->bindTo($this)); }
Get condition of this filter. @param array $inputs @return array|mixed|void
entailment
protected function setupDefaultOptions() { $defaultOptions = [ 'overwriteInitial' => false, 'initialPreviewAsData' => true, 'browseLabel' => trans('admin.browse'), 'showRemove' => false, 'showUpload' => false, // 'initialCaption' => $this->initialCaption($this->value), 'deleteExtraData' => [ $this->formatName($this->column) => static::FILE_DELETE_FLAG, static::FILE_DELETE_FLAG => '', '_token' => csrf_token(), '_method' => 'PUT', ], ]; if ($this->form instanceof Form) { $defaultOptions['deleteUrl'] = $this->form->resource().'/'.$this->form->model()->getKey(); } $this->options($defaultOptions); }
Set default options form image field.
entailment
public function disk($disk) { if (!array_key_exists($disk, config('filesystems.disks'))) { $error = new MessageBag([ 'title' => 'Config error.', 'message' => "Disk [$disk] not configured, please add a disk config in `config/filesystems.php`.", ]); return session()->flash('error', $error); } $this->storage = Storage::disk($disk); return $this; }
Set disk for storage. @param string $disk Disks defined in `config/filesystems.php`. @return $this
entailment
protected function upload(UploadedFile $file) { $this->renameIfExists($file); return $this->storage->putFileAs($this->getDirectory(), $file, $this->name); }
Upload file and delete original file. @param UploadedFile $file @return mixed
entailment
public function objectUrl($path) { if (URL::isValidUrl($path)) { return $path; } return Storage::disk(config('admin.upload.disk'))->url($path); }
Get file visit url. @param $path @return string
entailment
public function getPaymentMethods() { $methods = array(); if (isset($this->data->merchant->payments)) { foreach ($this->data->merchant->payments->payment as $method) { $method = (string) $method; $name = isset($this->names[$method]) ? $this->names[$method] : ucfirst($method); $methods[] = new PaymentMethod($method, $name); } } return $methods; }
{@inheritdoc}
entailment
public function column($name, $value = null) { if (is_null($value)) { $column = array_get($this->data, $name); return $this->dump($column); } if ($value instanceof \Closure) { $value = $value->call($this, $this->column($name)); } array_set($this->data, $name, $value); return $this; }
Get or set value of column in this row. @param $name @param null $value @return $this|mixed
entailment
public function index() { return Admin::content(function (Content $content) { $content->header(trans('admin.lang.menu')); $content->description(trans('admin.:lang.list')); $content->row(function (Row $row) { $row->column(6, $this->treeView()->render()); $row->column(6, function (Column $column) { $form = new \Jblv\Admin\Widgets\Form(); $form->action(admin_url('auth/menu')); $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions()); $form->text('title', trans('admin.title'))->rules('required'); $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp()); $form->text('uri', trans('admin.uri')); $form->multipleSelect('roles', trans('admin.roles'))->options(Role::all()->pluck('name', 'id')); $column->append((new Box(trans('admin.new'), $form))->style('success')); }); }); }); }
Index interface. @return Content
entailment
public static function extend( $placeholder, array $selectors ) { if ( ! isset( static::$placeholders[ $placeholder ] ) ) { static::$placeholders[ $placeholder ] = []; } static::$placeholders[ $placeholder ] = array_merge( static::$placeholders[ $placeholder ], $selectors ); }
Set selectors. Styles of these selectors output like extend of Sass. @param string $placeholder @param array $selectors @return void
entailment
public function create(array $data, $validate = true) { $this->rules = [ 'slug' => 'required|alpha_dash|unique:roles', 'name' => 'required|alpha_dash|unique:roles', ]; if ($validate) { $this->validate($data); } // Convert the checkbox values of "1" to true, so permission checking works with Sentinel. if (isset($data['permissions'])) { foreach ($data['permissions'] as $permission => $value) { $data['permissions'][$permission] = true; } } try { $role = $this->sentinel->getRoleRepository() ->createModel() ->create($data); } catch (QueryException $e) { throw new RolesException(trans('dashboard::dashboard.errors.role.create')); } return $role; }
{@inheritDoc}
entailment
public function update(array $data, $id, $validate = true) { if (!$role = $this->getById($id)) { throw new RolesException(trans('dashboard::dashboard.errors.role.found')); } if ($role->name != $data['name']) { $this->rules['name'] = 'required|alpha_dash|unique:roles'; } else { $this->rules['name'] = 'required|alpha_dash'; } if ($role->slug != $data['slug']) { $this->rules['slug'] = 'required|alpha_dash|unique:roles'; } else { $this->rules['slug'] = 'required|alpha_dash'; } if ($validate) { $this->validate($data); } // Convert the checkbox values of "1" to true, so permission checking works with Sentinel. if (isset($data['permissions'])) { foreach ($data['permissions'] as $permission => $value) { $data['permissions'][$permission] = true; } } else { $data['permissions'] = []; } $role->name = $data['name']; $role->slug = $data['slug']; $role->permissions = $data['permissions']; $role->save(); return $role; }
{@inheritDoc}
entailment
public function delete($id) { if (!$role = $this->getById($id)) { throw new RolesException(trans('dashboard::dashboard.errors.role.found')); } $role->delete(); return true; }
{@inheritDoc}
entailment
public static function add( $section_id, array $args ) { $section = static::_section( $section_id, $args ); static::$sections[ $section->get_id() ] = $section; return $section; }
Add Section @param string $section_id @param array $args @return Section
entailment
public function saveOrder($serialize) { $tree = json_decode($serialize, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException(json_last_error_msg()); } $this->model->saveOrder($tree); return true; }
Save tree order from a input. @param string $serialize @return bool
entailment
protected function script() { $deleteConfirm = trans('admin.delete_confirm'); $saveSucceeded = trans('admin.save_succeeded'); $refreshSucceeded = trans('admin.refresh_succeeded'); $deleteSucceeded = trans('admin.delete_succeeded'); $confirm = trans('admin.confirm'); $cancel = trans('admin.cancel'); $nestableOptions = json_encode($this->nestableOptions); return <<<SCRIPT $('#{$this->elementId}').nestable($nestableOptions); $('.tree_branch_delete').click(function() { var id = $(this).data('id'); swal({ title: "$deleteConfirm", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "$confirm", closeOnConfirm: false, cancelButtonText: "$cancel" }, function(){ $.ajax({ method: 'post', url: '{$this->path}/' + id, data: { _method:'delete', _token:LA.token, }, success: function (data) { $.pjax.reload('#pjax-container'); if (typeof data === 'object') { if (data.status) { swal(data.message, '', 'success'); } else { swal(data.message, '', 'error'); } } } }); }); }); $('.{$this->elementId}-save').click(function () { var serialize = $('#{$this->elementId}').nestable('serialize'); $.post('{$this->path}', { _token: LA.token, _order: JSON.stringify(serialize) }, function(data){ $.pjax.reload('#pjax-container'); toastr.success('{$saveSucceeded}'); }); }); $('.{$this->elementId}-refresh').click(function () { $.pjax.reload('#pjax-container'); toastr.success('{$refreshSucceeded}'); }); $('.{$this->elementId}-tree-tools').on('click', function(e){ var target = $(e.target), action = target.data('action'); if (action === 'expand') { $('.dd').nestable('expandAll'); } if (action === 'collapse') { $('.dd').nestable('collapseAll'); } }); SCRIPT; }
Build tree grid scripts. @return string
entailment
public function catchAll() { $isCatchallDomain = null; if($this->options['catchAllEnabled']){ try{ $isCatchallDomain = $this->transport->getSmtp()->acceptsAnyRecipient($this->dom); }catch (\Exception $e) { $this->statusManager->setStatus($this->users, $this->dom, $this->options['catchAllIsValid'], 'error while on CatchAll test: '.$e ); } // if a catchall domain is detected, and we consider // accounts on such domains as invalid, mark all the // users as invalid and move on if ($isCatchallDomain) { if (!$this->options['catchAllIsValid']) { $this->statusManager->setStatus($this->users, $this->dom, $this->options['catchAllIsValid'],'catch all detected'); return true; } } } }
Do a catch-all test for the domain . This increases checking time for a domain slightly, but doesn't confuse users.
entailment
public function mailFrom($fromUser,$fromDomain) { if (!($this->transport->getSmtp()->mail($fromUser. '@' . $fromDomain))) { // MAIL FROM not accepted, we can't talk $this->statusManager->setStatus($this->users, $this->dom, $this->options['noCommIsValid'],'MAIL FROM not accepted'); } }
MAIL FROM @param $fromUser @param $fromDomain @throws \SmtpValidatorEmail\Exception\ExceptionNoHelo
entailment
public function closeConnection () { if ( $this->transport->getSmtp()->isConnect()) { $this->transport->getSmtp()->rset(); $this->transport->getSmtp()->disconnect(); } }
Close connection
entailment
public function boot() { // Setup Default namespace until config file is published. if (!$namespace = config('laraflock.dashboard.viewNamespace')) { $namespace = 'dashboard'; } // Load & Publish views. $this->loadViewsFrom(__DIR__ . '/../Resources/views', $namespace); $this->publishes([ __DIR__ . '/../Resources/views' => base_path('resources/views/vendor/' . $namespace), ], 'views'); // Load translations. $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'dashboard'); // Publish config. $config = realpath(__DIR__ . '/../config.php'); $this->mergeConfigFrom($config, 'laraflock.dashboard'); $this->publishes([ $config => config_path('laraflock.dashboard.php'), ], 'config'); // Use package routes. if (config('laraflock.dashboard.routes')) { include __DIR__ . '/../routes.php'; } // Publish migrations. $migrations = realpath(__DIR__ . '/../Database/Migrations'); $this->publishes([ $migrations => database_path('/migrations'), ], 'migrations'); // Publish assets. $this->publishes([ __DIR__ . '/../Resources/assets' => public_path('vendor/laraflock'), ], 'public'); // Setup interfaces. $this->setupInterfaces(); }
{@inheritDoc}
entailment
protected function setupMiddleware() { $this->app['router']->middleware('user', UserMiddleware::class); $this->app['router']->middleware('roles', RoleMiddleware::class); $this->app['router']->middleware('permissions', PermissionMiddleware::class); }
Register the middleware to the application Register the following middleware: - \Laraflock\Dashboard\Middleware\UserMiddleware - \Laraflock\Dashboard\Middleware\RoleMiddleware - \Laraflock\Dashboard\Middleware\PermissionMiddleware
entailment
protected function setupProviders() { // Register Sentinel Package // - Used for authentication, authorization, roles, and permissions. $this->app->register(SentinelServiceProvider::class); // Register Ekko Package // - Used for blade templates to trigger active classes for navigation items. $this->app->register(EkkoServiceProvider::class); // Register Flash Package // - Used for easy flash session notifications and messages. $this->app->register(FlashServiceProvider::class); // Register Form Package // - Used for HTML form building with easy and readable API. $this->app->register(FormServiceProvider::class); // Register Bootstrap Form Package // - Used for HTML form building with easy and readable API (Bootstrap 3). $this->app->register(BootFormsServiceProvider::class); }
Register the providers to the application. This will register packages that this package is dependent on. Register the following providers: - Sentinel - Ekko - Flash - Form - BootForm
entailment
protected function setupInterfaces() { // Bind the Auth Repository Interface $this->app->bind( 'Laraflock\Dashboard\Repositories\Auth\AuthRepositoryInterface', config('laraflock.dashboard.authRepositoryClass') ); // Bind the Permission Repository Interface $this->app->bind( 'Laraflock\Dashboard\Repositories\Permission\PermissionRepositoryInterface', config('laraflock.dashboard.permissionRepositoryClass') ); // Bind the Role Repository Interface $this->app->bind( 'Laraflock\Dashboard\Repositories\Role\RoleRepositoryInterface', config('laraflock.dashboard.roleRepositoryClass') ); // Bind the User Repository Interface $this->app->bind( 'Laraflock\Dashboard\Repositories\User\UserRepositoryInterface', config('laraflock.dashboard.userRepositoryClass') ); // Bind the Module Repository Interface $this->app->singleton( 'Laraflock\Dashboard\Repositories\Module\ModuleRepositoryInterface', config('laraflock.dashboard.moduleRepositoryClass') ); }
Register Interface Bindings
entailment
protected function setupConsoleCommands() { // Share dashboard:install command with the application. $this->app['dashboard::install'] = $this->app->share(function () { return new InstallerCommand(); }); // Share dashboard:setup command with the application. $this->app['dashboard::setup'] = $this->app->share(function () { return new SetupCommand(); }); // Share dashboard:fresh command with the application. $this->app['dashboard::fresh'] = $this->app->share(function () { return new FreshCommand(); }); // Share dashboard:uninstall command with the application. $this->app['dashboard::uninstall'] = $this->app->share(function () { return new UninstallCommand(); }); // Adds dashboard:install to the console kernel. $this->commands('dashboard::install'); // Adds dashboard:setup to the console kernel. $this->commands('dashboard::setup'); // Adds dashboard:fresh to the console kernel. $this->commands('dashboard::fresh'); // Adds dashboard:uninstall to the console kernel. $this->commands('dashboard::uninstall'); }
Register the console commands to the application. Register the following commands: - dashboard:install - dashboard:fresh
entailment
protected function setupFacades() { // Setup alias loader. $loader = AliasLoader::getInstance(); // Load Sentinel // - Activation // - Reminder // - Sentinel $loader->alias('Activation', Activation::class); $loader->alias('Reminder', Reminder::class); $loader->alias('Sentinel', Sentinel::class); // Load Flash $loader->alias('Flash', Flash::class); // Load Ekko $loader->alias('Ekko', Ekko::class); // Carbon $loader->alias('Carbon', Carbon::class); // Load Form // - Form // - BootForm $loader->alias('Form', Form::class); $loader->alias('BootForm', BootForm::class); }
Register the Facades to the application. Registers the following facades: - Activation - Reminder - Sentinel - Flash - Ekko - Form - BootForm
entailment
public function update(Request $request, $id) { if ($request->input('action') == 'update_account') { try { $this->userRepositoryInterface->update($request->all(), $id); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('account.edit') ->withErrors($e->getErrors()) ->withInput(); } catch (UsersException $e) { Flash::error($e->getMessage()); return redirect()->route('dashboard.index'); } Flash::success(trans('dashboard::dashboard.flash.account.success')); return redirect()->route('account.edit'); } if ($request->input('action') == 'change_password') { try { $this->userRepositoryInterface->updatePassword($request->all()); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('account.edit') ->withErrors($e->getErrors()); } catch (AuthenticationException $e) { Flash::error(trans('dashboard::dashboard.flash.password.fail')); return redirect() ->route('account.edit'); } Flash::success(trans('dashboard::dashboard.flash.password.success')); return redirect()->route('account.edit'); } }
Update account information. @param \Illuminate\Http\Request $request @param $id @return $this|\Illuminate\Http\RedirectResponse
entailment
public function register_control( \WP_Customize_Manager $wp_customize ) { $this->args['type'] = 'multiple-checkbox'; $wp_customize->add_control( new Customize_Control\Multiple_Checkbox_Control( $wp_customize, $this->get_id(), $this->_generate_register_control_args() ) ); }
Add control @param WP_Customize_Manager $wp_customize @see https://developer.wordpress.org/reference/classes/wp_customize_manager/add_control/ @see https://developer.wordpress.org/reference/classes/wp_customize_manager/add_setting/
entailment
public function sanitize_callback() { return function( $value ) { if ( ! is_array( $value ) ) { $value = explode( ',', $value ); } $sanitized_values = []; foreach ( $value as $v ) { if ( ! array_key_exists( $v, $this->args['choices'] ) ) { continue; } $sanitized_values[] = $v; } $sanitized_values = array_map( 'sanitize_text_field', $sanitized_values ); return implode( ',', $sanitized_values ); }; }
Sanitize callback function @return string|function Function name or function for sanitize
entailment
protected function generateSignature() { return sha1( $this->getTransactionId() . $this->getEntranceCode() . $this->getAmountInteger() . $this->getShopId() . $this->getMerchantId() . $this->getMerchantKey() ); }
{@inheritdoc}
entailment
public function getData() { $this->validate( 'amount', 'transactionId', 'returnUrl', 'notifyUrl' ); if (!$this->getTestMode() && $this->getIssuer() == 99) { throw new InvalidRequestException("The issuer can only be '99' in testMode!"); } $data = array( 'shopid' => $this->getShopId(), 'merchantid' => $this->getMerchantId(), 'merchantkey' => $this->getMerchantKey(), 'payment' => $this->getPaymentMethod(), 'purchaseid' => $this->getTransactionId(), 'amount' => $this->getAmountInteger(), 'issuerid' => $this->getIssuer(), 'entrancecode' => $this->getEntranceCode(), 'description' => $this->getDescription(), 'including' => $this->getIncluding(), 'days' => $this->getDays(), 'returnurl' => $this->getReturnUrl(), 'cancelurl' => $this->getCancelUrl(), 'notifyurl' => $this->getNotifyUrl(), 'sha1' => $this->generateSignature(), 'testmode' => $this->getTestMode(), ); /** @var \Omnipay\Common\CreditCard $card */ $card = $this->getCard(); if ($card) { if ($this->getPaymentMethod() == 'overboeking' || $this->getPaymentMethod() == 'klarna') { $data['billing_mail'] = $card->getEmail(); $data['billing_firstname'] = $card->getBillingFirstName(); $data['billing_lastname'] = $card->getBillingLastName(); } if ($this->getPaymentMethod() == 'klarna') { $data['billing_company'] = $card->getBillingCompany(); $data['billing_address1'] = $card->getBillingAddress1(); $data['billing_address2'] = $card->getBillingAddress2(); $data['billing_zip'] = $card->getBillingPostcode(); $data['billing_city'] = $card->getBillingCity(); $data['billing_country'] = $card->getBillingCountry(); $data['billing_phone'] = $card->getBillingPhone(); $data['birthdate'] = date('dmY', strtotime($card->getBirthday())); if ($this->getMakeInvoice()) { $data['makeinvoice'] = $this->getMakeInvoice(); } if ($this->getMailInvoice()) { $data['mailinvoice'] = $this->getMailInvoice(); } $data['billing_countrycode'] = $this->getBillingCountrycode(); $data['shipping_countrycode'] = $this->getShippingCountrycode(); // only used for klarna account (required for klarna invoice as -1) $data['pclass'] = - 1; $data = array_merge($data, $this->getItemData()); } $data['shipping_mail'] = $card->getEmail(); $data['shipping_firstname'] = $card->getShippingFirstName(); $data['shipping_lastname'] = $card->getShippingLastName(); $data['shipping_company'] = $card->getShippingCompany(); $data['shipping_address1'] = $card->getShippingAddress1(); $data['shipping_address2'] = $card->getShippingAddress2(); $data['shipping_zip'] = $card->getShippingPostcode(); $data['shipping_city'] = $card->getShippingCity(); $data['shipping_country'] = $card->getShippingCountry(); $data['shipping_phone'] = $card->getShippingPhone(); } return $data; }
{@inheritdoc}
entailment
public function sendData($data) { $httpResponse = $this->httpClient->request( 'POST', $this->endpoint, [ 'Content-Type' => 'application/x-www-form-urlencoded' ], http_build_query($data) ); return $this->response = new PurchaseResponse($this, $this->parseXmlResponse($httpResponse)); }
{@inheritdoc}
entailment
protected function formatName($column) { if (is_string($column)) { $name = explode('.', $column); if (1 === count($name)) { return $name[0]; } $html = array_shift($name); foreach ($name as $piece) { $html .= "[$piece]"; } return $html; } if (is_array($this->column)) { $names = []; foreach ($this->column as $key => $name) { $names[$key] = $this->formatName($name); } return $names; } return ''; }
Format the name of the field. @param string $column @return array|mixed|string
entailment
public function fill($data) { // Field value is already setted. // if (!is_null($this->value)) { // return; // } if (is_array($this->column)) { foreach ($this->column as $key => $column) { $this->value[$key] = array_get($data, $column); } return; } $this->value = array_get($data, $this->column); }
Fill data to the field. @param array $data
entailment
public function setOriginal($data) { if (is_array($this->column)) { foreach ($this->column as $key => $column) { $this->original[$key] = array_get($data, $column); } return; } $this->original = array_get($data, $this->column); }
Set original value to the field. @param array $data
entailment
public function rules($rules = null, $messages = []) { if ($rules instanceof \Closure) { $this->rules = $rules; } if (is_string($rules)) { $rules = array_filter(explode('|', "{$this->rules}|$rules")); $this->rules = implode('|', $rules); } $this->validationMessages = $messages; return $this; }
Get or set rules. @param null $rules @param array $messages @return $this
entailment
public function getValidator(array $input) { if ($this->validator) { return $this->validator->call($this, $input); } $rules = $attributes = []; if (!$fieldRules = $this->getRules()) { return false; } if (is_string($this->column)) { if (!array_has($input, $this->column)) { return false; } $input = $this->sanitizeInput($input, $this->column); $rules[$this->column] = $fieldRules; $attributes[$this->column] = $this->label; } if (is_array($this->column)) { foreach ($this->column as $key => $column) { if (!array_key_exists($column, $input)) { continue; } $input[$column.$key] = array_get($input, $column); $rules[$column.$key] = $fieldRules; $attributes[$column.$key] = $this->label."[$column]"; } } return Validator::make($input, $rules, $this->validationMessages, $attributes); }
Get validator for this field. @param array $input @return bool|Validator
entailment
protected function sanitizeInput($input, $column) { if ($this instanceof Field\MultipleSelect) { $value = array_get($input, $column); array_set($input, $column, array_filter($value)); } return $input; }
Sanitize input data. @param array $input @param string $column @return array
entailment
public function open($options = []) { $attributes = []; if (self::MODE_EDIT === $this->mode) { $this->addHiddenField((new Form\Field\Hidden('_method'))->value('PUT')); } $this->addRedirectUrlField(); $attributes['action'] = $this->getAction(); $attributes['method'] = array_get($options, 'method', 'post'); $attributes['accept-charset'] = 'UTF-8'; $attributes['class'] = array_get($options, 'class'); if ($this->hasFile()) { $attributes['enctype'] = 'multipart/form-data'; } $html = []; foreach ($attributes as $name => $value) { $html[] = "$name=\"$value\""; } return '<form '.implode(' ', $html).' pjax-container>'; }
Open up a new HTML form. @param array $options @return string
entailment
public function submitButton() { if (self::MODE_VIEW === $this->mode) { return ''; } if (!$this->options['enableSubmit']) { return ''; } if (self::MODE_EDIT === $this->mode) { $text = trans('admin.save'); } else { $text = trans('admin.submit'); } return <<<EOT <div class="btn-group pull-right"> <button type="submit" class="btn btn-info pull-right" data-loading-text="<i class='fa fa-spinner fa-spin '></i> $text">$text</button> </div> EOT; }
Submit button of form.. @return string
entailment
protected function removeReservedFields() { if (!$this->isMode(static::MODE_CREATE)) { return; } $reservedColumns = [ $this->form->model()->getKeyName(), $this->form->model()->getCreatedAtColumn(), $this->form->model()->getUpdatedAtColumn(), ]; $this->fields = $this->fields()->reject(function (Field $field) use ($reservedColumns) { return in_array($field->column(), $reservedColumns, true); }); }
Remove reserved fields like `id` `created_at` `updated_at` in form fields.
entailment
public static function register( $selectors, $properties, $media_query = null ) { if ( ! is_array( $selectors ) ) { $selectors = explode( ',', $selectors ); } if ( ! is_array( $properties ) ) { $properties = explode( ';', $properties ); } static::$styles[] = [ 'selectors' => $selectors, 'properties' => $properties, 'media_query' => $media_query, ]; }
Registers style setting @param string|array $selectors @param string|array $properties @param string $media_query @return void
entailment
public function authentication(Request $request) { try { $this->authRepositoryInterface->authenticate($request->all()); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('auth.login') ->withErrors($e->getErrors()); } catch (AuthenticationException $e) { Flash::error($e->getMessage()); return redirect()->route('auth.login'); } return redirect()->route('dashboard.index'); }
Authenticate and Validate login input. @param Request $request @return $this|\Illuminate\Http\RedirectResponse
entailment
public function registration(Request $request) { if (!config('laraflock.dashboard.registration')) { Flash::error(trans('dashboard::dashboard.flash.registration.not_active')); return redirect()->route('auth.login'); } try { $this->authRepositoryInterface->register($request->all()); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('auth.register') ->withErrors($e->getErrors()) ->withInput(); } catch (RolesException $e) { Flash::error($e->getMessage()); return redirect() ->route('auth.register') ->withInput(); } if (!config('laraflock.dashboard.activations')) { Flash::success(trans('dashboard::dashboard.flash.registration.activated')); return redirect()->route('auth.login'); } Flash::success(trans('dashboard::dashboard.flash.registration.created')); return redirect()->route('auth.login'); }
Register the user. @param \Illuminate\Http\Request $request @return $this|\Illuminate\Http\RedirectResponse
entailment
public function activate(Request $request) { if (!$email = $request->get('email')) { $email = null; } if (!$code = $request->get('code')) { $code = null; } if (!config('laraflock.dashboard.activations')) { Flash::error(trans('dashboard::dashboard.flash.activation.not_active')); return redirect()->route('auth.login'); } return $this->view('auth.activate')->with(['email' => $email, 'code' => $code]); }
Display activate screen. @param \Illuminate\Http\Request $request @return $this|\Illuminate\Http\RedirectResponse
entailment
public function activation(Request $request) { if (!config('laraflock.dashboard.activations')) { Flash::error(trans('dashboard::dashboard.flash.activation.not_active')); return redirect()->route('auth.login'); } try { $this->authRepositoryInterface->activate($request->all()); } catch (FormValidationException $e) { Flash::error($e->getMessage()); return redirect() ->route('auth.activate') ->withErrors($e->getErrors()) ->withInput(); } catch (AuthenticationException $e) { Flash::error($e->getMessage()); return redirect() ->route('auth.activate') ->withInput(); } Flash::success(trans('dashboard::dashboard.flash.activation.success')); return redirect()->route('auth.login'); }
Activate a user. @param \Illuminate\Http\Request $request @return $this
entailment
public function render_content() { if ( empty( $this->choices ) ) { return; } ?> <?php if ( ! empty( $this->label ) ) : ?> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <?php endif; ?> <?php if ( ! empty( $this->description ) ) : ?> <span class="description customize-control-description"><?php echo esc_html( $this->description ); ?></span> <?php endif; ?> <?php $multi_values = ( ! is_array( $this->value() ) ) ? explode( ',', $this->value() ) : $this->value(); ?> <ul> <?php foreach ( $this->choices as $value => $label ) : ?> <li> <label> <input type="checkbox" value="<?php echo esc_attr( $value ); ?>" <?php checked( in_array( $value, $multi_values ) ); ?> /> <?php echo esc_html( $label ); ?> </label> </li> <?php endforeach; ?> </ul> <input type="hidden" <?php $this->link(); ?> value="<?php echo esc_attr( implode( ',', $multi_values ) ); ?>" /> <?php }
Render the control's content @return void
entailment
public function partial( $args = null ) { if ( is_null( $args ) ) { return $this->partial; } elseif ( is_array( $args ) ) { $this->partial = new Partial( $this->get_id(), $args ); } }
Control joined to Partial @param array|null $args
entailment
public function _set_default_value( $value ) { if ( is_null( $value ) || false === $value ) { if ( isset( $this->args['default'] ) ) { return $this->args['default']; } } return $value; }
Set default theme_mod @param mixed $value @return mixed
entailment
public function handle() { $files = new Filesystem; $files->deleteDirectory(app_path('Http/Controllers/Auth')); $files->delete(base_path('database/migrations/2014_10_12_000000_create_users_table.php')); $files->delete(base_path('database/migrations/2014_10_12_100000_create_password_resets_table.php')); $this->info('Original Auth removed! Enjoy your fresh start.'); }
Execute the console command. @return void
entailment
protected function generateSignature() { return sha1( $this->getTransactionReference() . $this->getShopId() . $this->getMerchantId() . $this->getMerchantKey() ); }
{@inheritdoc}
entailment
public function getData() { $this->validate('merchantId', 'merchantKey'); $data = array( 'shopid' => $this->getShopId(), 'merchantid' => $this->getMerchantId(), 'merchantkey' => $this->getMerchantKey(), 'trxid' => $this->getTransactionReference(), 'sha1' => $this->generateSignature(), ); return $data; }
{@inheritdoc}
entailment
public function sendData($data) { if ($data['trxid']) { $httpResponse = $this->httpClient->request( 'POST', $this->endpoint, [ 'Content-Type' => 'application/x-www-form-urlencoded' ], http_build_query($data) ); return $this->response = new CompletePurchaseResponse($this, $this->parseXmlResponse($httpResponse)); } else { $data = array('transaction' => (object) $this->httpRequest->query->all()); return $this->response = new CompletePurchaseResponse($this, (object) $data); } }
{@inheritdoc}
entailment
protected function inExceptArray($request) { foreach (config('admin.operation_log.except') as $except) { if ('/' !== $except) { $except = trim($except, '/'); } $methods = []; if (Str::contains($except, ':')) { list($methods, $except) = explode(':', $except); $methods = explode(',', $methods); } $methods = array_map('strtoupper', $methods); if ($request->is($except) && (empty($methods) || in_array($request->method(), $methods, true))) { return true; } } return false; }
Determine if the request has a URI that should pass through CSRF verification. @param \Illuminate\Http\Request $request @return bool
entailment
public static function rgba( $hex, $percent ) { $hex = static::_hex_normalization( $hex ); $rgba = []; for ( $i = 0; $i < 3; $i ++ ) { $dec = hexdec( substr( $hex, $i * 2, 2 ) ); $rgba[] = $dec; } $rgba = implode( ',', $rgba ); $rgba = "rgba({$rgba}, $percent)"; return $rgba; }
hex to rgba @param hex $hex @param int $percent @return rgba
entailment
private static function _get_hue( $hex ) { $red = hexdec( substr( $hex, 0, 2 ) ); $green = hexdec( substr( $hex, 2, 2 ) ); $blue = hexdec( substr( $hex, 4, 2 ) ); if ( $red === $green && $red === $blue ) { return 0; } $hue = static::_get_hue_based_max_rgb( $red, $green, $blue ); if ( 0 > $hue ) { $hue += 360; } return $hue; }
Return hue from hex @param hex $hex @return hue
entailment
private static function _get_hue_based_max_rgb( $red, $green, $blue ) { $max_rgb = max( $red, $green, $blue ); $min_rgb = min( $red, $green, $blue ); $diff_max_min_rgb = $max_rgb - $min_rgb; if ( $red === $max_rgb ) { $hue = 60 * ( $diff_max_min_rgb ? ( $green - $blue ) / $diff_max_min_rgb : 0 ); } elseif ( $green === $max_rgb ) { $hue = 60 * ( $diff_max_min_rgb ? ( $blue - $red ) / $diff_max_min_rgb : 0 ) + 120; } elseif ( $blue === $max_rgb ) { $hue = 60 * ( $diff_max_min_rgb ? ( $red - $green ) / $diff_max_min_rgb : 0 ) + 240; } return $hue; }
Return hue from max rgb @param dec $red @param dec $green @param dec $blue @return hue
entailment
private static function _get_saturation( $hex ) { $red = hexdec( substr( $hex, 0, 2 ) ); $green = hexdec( substr( $hex, 2, 2 ) ); $blue = hexdec( substr( $hex, 4, 2 ) ); $max_rgb = max( $red, $green, $blue ); $min_rgb = min( $red, $green, $blue ); $cnt = round( ( $max_rgb + $min_rgb ) / 2 ); if ( 127 >= $cnt ) { $tmp = ( $max_rgb + $min_rgb ); $saturation = $tmp ? ( $max_rgb - $min_rgb ) / $tmp : 0; } else { $tmp = ( 510 - $max_rgb - $min_rgb ); $saturation = ( $tmp ) ? ( ( $max_rgb - $min_rgb ) / $tmp ) : 0; } return $saturation * 100; }
Return saturation from hex @param hex $hex @return saturation
entailment
private static function _get_luminance( $hex ) { $red = hexdec( substr( $hex, 0, 2 ) ); $green = hexdec( substr( $hex, 2, 2 ) ); $blue = hexdec( substr( $hex, 4, 2 ) ); $max_rgb = max( $red, $green, $blue ); $min_rgb = min( $red, $green, $blue ); return ( $max_rgb + $min_rgb ) / 2 / 255 * 100; }
Return luminance from hex @param hex $hex @return luminance
entailment
public static function addBreadcrumbList() { $view = Yii::$app->getView(); $breadcrumbList = []; if (isset($view->params['breadcrumbs'])) { $position = 1; foreach ($view->params['breadcrumbs'] as $breadcrumb) { if (is_array($breadcrumb)) { $breadcrumbList[] = (object)[ "@type" => "http://schema.org/ListItem", "http://schema.org/position" => $position, "http://schema.org/item" => (object)[ "@id" => Url::to($breadcrumb['url'], true), "http://schema.org/name" => $breadcrumb['label'], ] ]; } else { // Is it ok to omit URL here or not? Google is not clear on that: // http://stackoverflow.com/questions/33688608/how-to-markup-the-last-non-linking-item-in-breadcrumbs-list-using-json-ld $breadcrumbList[] = (object)[ "@type" => "http://schema.org/ListItem", "http://schema.org/position" => $position, "http://schema.org/item" => (object)[ "http://schema.org/name" => $breadcrumb, ] ]; } $position++; } } $doc = (object)[ "@type" => "http://schema.org/BreadcrumbList", "http://schema.org/itemListElement" => $breadcrumbList ]; JsonLDHelper::add($doc); }
Adds BreadcrumbList schema.org markup based on the application view `breadcrumbs` parameter
entailment
public static function add($doc, $context = null) { if (is_null($context)) { // Using a simple context from the following comment would end up replacing `@type` keyword with `type` alias, // which is not recognized by Google's SDTT. So using a workaround instead // http://stackoverflow.com/questions/35879351/google-structured-data-testing-tool-fails-to-validate-type-as-an-alias-of-type //$context = (object)["@context" => "http://schema.org"]; $context = (object)[ "@context" => (object)["@vocab" => "http://schema.org/"] ]; } $compacted = JsonLD::compact((object)$doc, $context); // We need to register it with "application/ld+json" script type, which is not possible with registerJs(), // so passing to layout where it can be registered via JsonLDHelper::registerScripts() using Html::script $view = Yii::$app->getView(); $view->params['jsonld'][] = json_encode($compacted, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); }
Compacts JSON-LD document, encodes and adds to the application view `jsonld` parameter, so it can later be registered using JsonLDHelper::registerScripts(). @param array|object $doc The JSON-LD document @param array|null|object|string $context optional context. If not specified, schema.org vocabulary will be used.
entailment
public static function registerScripts() { $view = Yii::$app->getView(); if (isset($view->params['jsonld'])) { foreach ($view->params['jsonld'] as $jsonld) { echo Html::script($jsonld, ['type' => 'application/ld+json']); } } }
Registers JSON-LD scripts stored in the application view `jsonld` parameter. This should be invoked in the <head> section of your layout.
entailment
public function parse(int $type, $annotation): array { if ($type !== self::TYPE_METHOD) { throw new AnnotationException('`@View` must be defined on class method!'); } ViewRegister::bindView( $this->className, $this->methodName, $annotation->getTemplate(), $annotation->getLayout() ); return []; }
Parse object @param int $type Class or Method or Property @param View $annotation Annotation object @return array Return empty array is nothing to do! When class type return [$beanName, $className, $scope, $alias, $size] is to inject bean When property type return [$propertyValue, $isRef] is to reference value
entailment
private function extractParameters(FuncCall $node): array { $params = []; foreach ($node->args as $arg) { if ($arg->value instanceof String_) { $params[] = $arg->value->value; } else { $params[] = null; } } return $params; }
@param FuncCall $node @return string[]
entailment
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); $response = $this->responseView($request, $response); return $response; }
@param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Server\RequestHandlerInterface $handler @return \Psr\Http\Message\ResponseInterface @throws \Throwable
entailment
private function responseView(ServerRequestInterface $request, ResponseInterface $response) { $ctx = Context::mustGet(); $views = ViewRegister::getViews(); // the info of view model $controllerClass = $ctx->get('controllerClass'); $controllerAction = $ctx->get('controllerAction'); $actionId = $controllerClass . '@' . $controllerAction; if (!isset($views[$actionId])) { return $response; } // Get layout and template [$layout, $template] = $views[$actionId]; // accept and the of response $accepts = $request->getHeader('accept'); $currentAccept = \current($accepts); /* @var \Swoft\Http\Message\Response $response */ $responseAttribute = AttributeEnum::RESPONSE_ATTRIBUTE; $data = $response->getAttribute($responseAttribute); // the condition of view $isTextHtml = !empty($currentAccept) && $response->isMatchAccept($currentAccept, 'text/html'); $isTemplate = $controllerClass && $response->isArrayable($data) && $template; // show view if ($isTextHtml && $isTemplate) { if ($data instanceof Arrayable) { $data = $data->toArray(); } /* @var \Swoft\View\Renderer $view */ $view = \Swoft::getBean('view'); $content = $view->render($template, $data, $layout); $response = $response ->withContent($content) ->withAttribute($responseAttribute, null) ->withoutHeader('Content-Type')->withAddedHeader('Content-Type', 'text/html'); } return $response; }
@param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Message\ResponseInterface|\Swoft\Http\Message\Response $response @return \Psr\Http\Message\ResponseInterface @throws \Throwable
entailment