sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function _createAddress(array $response, $type) { switch($type) { case AbstractAddress::TYPE_SHIPPING: $model = new ShippingAddress(); break; case AbstractAddress::TYPE_BILLING: $model = new BillingAddress(); break; default: return null; } $model->setName($response[AbstractAddress::FIELD_NAME]) ->setStreetAddress($response[AbstractAddress::FIELD_STREET_ADDRESS]) ->setStreetAddressAddition($response[AbstractAddress::FIELD_STREET_ADDRESS_ADDITION]) ->setPostalCode($response[AbstractAddress::FIELD_POSTAL_CODE]) ->setCity($response[AbstractAddress::FIELD_CITY]) ->setState($response[AbstractAddress::FIELD_STATE]) ->setCountry($response[AbstractAddress::FIELD_COUNTRY]) ->setPhone($response[AbstractAddress::FIELD_PHONE]); return $model; }
Creates and fills a shipping- / billing address model. @param array $response @param string $type @return null|BillingAddress|ShippingAddress
entailment
private function _handleRecursive($response, $resourceName) { $result = null; if (isset($response['id'])) { $result = $this->_convertResponseToModel($response, $resourceName); } else if (!is_null($response)) { $paymentArray = array(); foreach ($response as $paymentData) { array_push($paymentArray, $this->_convertResponseToModel($paymentData, $resourceName)); } $result = $paymentArray; } return $result; }
Handles the multidimensional param arrays during model creation @param array $response @param string $resourceName @return array|null|Base
entailment
public function convertErrorToModel(array $response, $resourceName = null) { $errorModel = new Error(); $httpStatusCode = isset($response['header']['status']) ? $response['header']['status'] : null; $errorModel->setHttpStatusCode($httpStatusCode); $responseCode = isset($response['body']['data']['response_code']) ? $response['body']['data']['response_code'] : null; $errorModel->setResponseCode($responseCode); $errorCode = 'Undefined Error. This should not happen!'; $rawError = array(); if (isset($this->_errorCodes[$responseCode])) { $errorCode = $this->_errorCodes[$responseCode]; } if (isset($resourceName) && isset($response['body']['data'])) { try { $errorModel->setRawObject($this->convertResponse($response['body']['data'], $resourceName)); } catch (\Exception $e) { } } if (isset($response['body'])) { if (is_array($response['body'])) { if (isset($response['body']['error'])) { $rawError = $response['body']['error']; if (is_array($response['body']['error'])) { $errorCode = $this->getErrorMessageFromArray($response['body']['error']); } elseif (is_string($response['body']['error'])) { $errorCode = $response['body']['error']; } } } elseif (is_string($response['body'])) { $json = json_decode($response['body'], true); if (isset($json['error'])) { $errorCode = $json['error']; $rawError = $json['error']; } } } $errorModel->setErrorMessage($errorCode); $errorModel->setErrorResponseArray(array('error' => $rawError)); return $errorModel; }
Generates an error model based on the provided response array @param array $response @param string $resourceName @return Error
entailment
public function validateResponse(array $response) { $returnValue = false; if (isset($response['header']) && isset($response['header']['status']) && $response['header']['status'] >= 200 && $response['header']['status'] < 300 ) { $returnValue = true; } return $returnValue; }
Validates the data responded by the API Just checks the header status is successful. @param array $response @return boolean True if valid
entailment
public function toArray() { return array( static::FIELD_NAME => $this->_name, static::FIELD_STREET_ADDRESS => $this->_streetAddress, static::FIELD_STREET_ADDRESS_ADDITION => $this->_streetAddressAddition, static::FIELD_CITY => $this->_city, static::FIELD_POSTAL_CODE => $this->_postalCode, static::FIELD_COUNTRY => $this->_country, static::FIELD_STATE => $this->_state, static::FIELD_PHONE => $this->_phone, ); }
Converts model to array. @return array
entailment
public function toArray() { return array( static::FIELD_NAME => $this->_name, static::FIELD_DESCRIPTION => $this->_description, static::FIELD_ITEM_NUMBER => $this->_itemNumber, static::FIELD_AMOUNT => $this->_amount, static::FIELD_QUANTITY => $this->_quantity, static::FIELD_URL => $this->_url, ); }
Converts model to array. @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': if (!is_null($this->getPayment())) { $parameterArray['payment'] = $this->getPayment(); } else { $parameterArray['token'] = $this->getToken(); } $parameterArray['amount'] = $this->getAmount(); $parameterArray['currency'] = $this->getCurrency(); $parameterArray['description'] = $this->getDescription(); if (!is_null($this->getClient())) { $parameterArray['client'] = $this->getClient(); } if(!is_null($this->getSource())) { $parameterArray['source'] = $this->getSource(); } break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; case 'delete': break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = parent::parameterize($method); if ('create' == $method) { if ($this->getFirstName()) { $parameterArray['first_name'] = $this->getFirstName(); } if ($this->getLastName()) { $parameterArray['last_name'] = $this->getLastName(); } if ($this->getCountry()) { $parametersArray['country'] = $this->getCountry(); } if ($this->getClientEmail()) { $parametersArray['client_email'] = $this->getClientEmail(); } if ($this->getBillingAddress()) { $parametersArray['billing_address'] = $this->getBillingAddress(); } if ($this->getClientPhoneNumber()) { $parametersArray['client_phone_number'] = $this->getClientPhoneNumber(); } } return $parameterArray; }
Returns an array of parameters customized for the given method name @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': case 'update': $parameterArray['email'] = $this->getEmail(); $parameterArray['description'] = $this->getDescription(); break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; case 'delete': break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': if(!is_null($this->getUrl())){ $parameterArray['url'] = $this->getUrl(); }else{ $parameterArray['email'] = $this->getEmail(); } $parameterArray['event_types'] = $this->getEventTypes(); if (!is_null($this->getActive())) { $parameterArray['active'] = $this->getActive(); } break; case 'update': if(!is_null($this->getUrl())){ $parameterArray['url'] = $this->getUrl(); }else{ $parameterArray['email'] = $this->getEmail(); } $parameterArray['event_types'] = $this->getEventTypes(); if (!is_null($this->getActive())) { $parameterArray['active'] = $this->getActive(); } break; case 'delete': break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = parent::parameterize($method); if ('create' == $method) { if ($this->getCountry()) { $parametersArray['country'] = $this->getCountry(); } if ($this->getClientEmail()) { $parametersArray['client_email'] = $this->getClientEmail(); } if ($this->getBillingAddress()) { $parametersArray['billing_address'] = $this->getBillingAddress(); } } return $parameterArray; }
Returns an array of parameters customized for the given method name @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': $parameterArray['Identifier'] = $this->getIdentifier(); break; case 'update': $parameterArray['Identifier'] = $this->getIdentifier(); break; case 'delete': break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': $parameterArray['amount'] = $this->getAmount(); $parameterArray['currency'] = $this->getCurrency(); $parameterArray['interval'] = $this->getInterval(); $parameterArray['name'] = $this->getName(); $parameterArray['trial_period_days'] = $this->getTrialPeriodDays(); break; case 'update': if (!is_null($this->getUpdateSubscriptions())) { $parameterArray['update_subscriptions'] = $this->getUpdateSubscriptions(); } $parameterArray['name'] = $this->getName(); $parameterArray['amount'] = $this->getAmount(); $parameterArray['currency'] = $this->getCurrency(); $parameterArray['interval'] = $this->getInterval(); $parameterArray['trial_period_days'] = $this->getTrialPeriodDays(); break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; case 'delete': if (!is_null($this->getRemoveWithSubscriptions())) { $parameterArray['remove_with_subscriptions'] = $this->getRemoveWithSubscriptions(); } break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': if (!is_null($this->getClient())) { $parameterArray['client'] = $this->getClient(); } if (!is_null($this->getOffer())) { $parameterArray['offer'] = $this->getOffer(); } $parameterArray['payment'] = $this->getPayment(); if (!is_null($this->getAmount())) { $parameterArray['amount'] = $this->getAmount(); } if (!is_null($this->getCurrency())) { $parameterArray['currency'] = $this->getCurrency(); } if (!is_null($this->getInterval())) { $parameterArray['interval'] = $this->getInterval(); } if (!is_null($this->getName())) { $parameterArray['name'] = $this->getName(); } if (!is_null($this->getPeriodOfValidity())) { $parameterArray['period_of_validity'] = $this->getPeriodOfValidity(); } if (!is_null($this->getTrialEnd())) { $parameterArray['trial_end'] = $this->getTrialEnd(); } if (!is_null($this->getStartAt())) { $parameterArray['start_at'] = $this->getStartAt(); } if (!is_null($this->getMandateReference())) { $parameterArray['mandate_reference'] = $this->getMandateReference(); } break; case 'update': if (!is_null($this->getOffer())) { $parameterArray['offer'] = $this->getOffer(); } if (!is_null($this->getPayment())) { $parameterArray['payment'] = $this->getPayment(); } else { $parameterArray['token'] = $this->getToken(); } if (!is_null($this->getAmount())) { $parameterArray['amount'] = $this->getAmount(); } if (!is_null($this->getCurrency())) { $parameterArray['currency'] = $this->getCurrency(); } if (!is_null($this->getInterval())) { $parameterArray['interval'] = $this->getInterval(); } if (!is_null($this->getName())) { $parameterArray['name'] = $this->getName(); } if (!is_null($this->getPause())) { $parameterArray['pause'] = $this->getPause(); } if (!is_null($this->getPeriodOfValidity())) { $parameterArray['period_of_validity'] = $this->getPeriodOfValidity(); } if (!is_null($this->getTrialEnd())) { $parameterArray['trial_end'] = $this->getTrialEnd(); } if (!is_null($this->getAmountChangeType())) { $parameterArray['amount_change_type'] = $this->getAmountChangeType(); } if (!is_null($this->getOfferChangeType())) { $parameterArray['offer_change_type'] = $this->getOfferChangeType(); } if (!is_null($this->getMandateReference())) { $parameterArray['mandate_reference'] = $this->getMandateReference(); } break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; case 'delete': if (!is_null($this->getRemove())){ $parameterArray['remove'] = $this->getRemove(); } break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function parameterize($method) { $parameterArray = array(); switch ($method) { case 'create': $parameterArray['token'] = $this->getToken(); $parameterArray['client'] = $this->getClient(); break; case 'delete': break; case 'getOne': $parameterArray['count'] = 1; $parameterArray['offset'] = 0; break; case 'getAll': $parameterArray = $this->getFilter(); break; } return $parameterArray; }
Returns an array of parameters customized for the argumented methodname @param string $method @return array
entailment
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'compound' => false, 'data_class' => null, 'empty_data' => null, 'multiple' => false, 'strict_decode' => true, ]) ->setAllowedTypes('strict_decode', 'bool') ; }
{@inheritdoc}
entailment
public function transform($value) { if (! $value instanceof \SplFileInfo) { return ''; } if (false === $file = @file_get_contents($value->getPathname(), FILE_BINARY)) { throw new TransformationFailedException(sprintf('Unable to read the "%s" file', $value->getPathname())); } return base64_encode($file); }
{@inheritdoc}
entailment
public function reverseTransform($value) { if (empty($value)) { return null; } try { return new UploadedBase64EncodedFile(new Base64EncodedFile($value, $this->strict)); } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } }
{@inheritdoc}
entailment
private function restoreToTemporary($encoded, $strict = true) { if (substr($encoded, 0, 5) === 'data:') { if (substr($encoded, 0, 7) !== 'data://') { $encoded = substr_replace($encoded, 'data://', 0, 5); } $source = @fopen($encoded, 'r'); if ($source === false) { throw new FileException('Unable to decode strings as base64'); } $meta = stream_get_meta_data($source); if ($strict) { if (!isset($meta['base64']) || $meta['base64'] !== true) { throw new FileException('Unable to decode strings as base64'); } } if (false === $path = tempnam($directory = sys_get_temp_dir(), 'Base64EncodedFile')) { throw new FileException(sprintf('Unable to create a file into the "%s" directory', $path)); } if (null !== $extension = (new MimeTypeExtensionGuesser())->guess($meta['mediatype'])) { $path .= '.' . $extension; } if (false === $target = @fopen($path, 'w+b')) { throw new FileException(sprintf('Unable to write the file "%s"', $path)); } if (false === @stream_copy_to_stream($source, $target)) { throw new FileException(sprintf('Unable to write the file "%s"', $path)); } if (false === @fclose($target)) { throw new FileException(sprintf('Unable to write the file "%s"', $path)); } if (false === @fclose($source)) { throw new FileException(sprintf('Unable to close data stream')); } return $path; } if (false === $decoded = base64_decode($encoded, $strict)) { throw new FileException('Unable to decode strings as base64'); } if (false === $path = tempnam($directory = sys_get_temp_dir(), 'Base64EncodedFile')) { throw new FileException(sprintf('Unable to create a file into the "%s" directory', $directory)); } if (false === file_put_contents($path, $decoded, FILE_BINARY)) { throw new FileException(sprintf('Unable to write the file "%s"', $path)); } return $path; }
@param string $encoded @param bool $strict @return string @throws FileException
entailment
public function index(Request $request) { // GET THE SLUG, ex. 'posts', 'pages', etc. $slug = $this->getSlug($request); // GET THE DataType based on the slug $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Check permission $this->authorize('browse', app($dataType->model_name)); if ($dataType->pagination === 'ajax') { return $this->indexAjax($request); } $getter = $dataType->pagination === 'php' ? 'paginate' : 'get'; $search = (object) ['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')]; $searchable = $dataType->pagination === 'php' ? array_keys(SchemaManager::describeTable(app($dataType->model_name)->getTable())->toArray()) : ''; $orderBy = $request->get('order_by'); $sortOrder = $request->get('sort_order', null); // Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType if (strlen($dataType->model_name) != 0) { $model = app($dataType->model_name); $query = $model; if (method_exists($model, 'adminList')) { $query = $model->adminList(); } $query->select('*'); $relationships = $this->getRelationships($dataType); // If a column has a relationship associated with it, we do not want to show that field $this->removeRelationshipField($dataType, 'browse'); if ($search->value && $search->key && $search->filter) { $search_filter = ($search->filter == 'equals') ? '=' : 'LIKE'; $search_value = ($search->filter == 'equals') ? $search->value : '%'.$search->value.'%'; $query = $query->where($search->key, $search_filter, $search_value); } if ($orderBy && in_array($orderBy, $dataType->fields())) { $querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'DESC'; $dataTypeContent = call_user_func([ $query = $query->with($relationships)->orderBy($orderBy, $querySortOrder), $getter, ]); } elseif ($model->timestamps) { $dataTypeContent = call_user_func([$query->latest($model::CREATED_AT), $getter]); } else { $dataTypeContent = call_user_func([$query->with($relationships)->orderBy($model->getKeyName(), 'DESC'), $getter]); } // Replace relationships' keys for labels and create READ links if a slug is provided. $dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType); } else { // If Model doesn't exist, get data from table name $dataTypeContent = call_user_func([DB::table($dataType->name), $getter]); $model = false; } // Check if CRUD is Translatable if (($isModelTranslatable = is_crud_translatable($model))) { $dataTypeContent->load('translations'); } // Check if server side pagination is enabled $isServerSide = $dataType->isServerSide(); $view = 'admin::crud.browse'; if (view()->exists("admin::$slug.browse")) { $view = "admin::$slug.browse"; } return Admin::view($view, compact( 'dataType', 'dataTypeContent', 'isModelTranslatable', 'search', 'orderBy', 'sortOrder', 'searchable', 'isServerSide' )); }
****************************************
entailment
private function indexAjax(Request $request) { // GET THE SLUG, ex. 'posts', 'pages', etc. $slug = $this->getSlug($request); // GET THE DataType based on the slug $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Check permission $this->authorize('browse', app($dataType->model_name)); $isServerSide = false; $isModelTranslatable = false; $columns = $dataType->fields(); $pagination = $dataType->pagination; $view='admin::crud.browse-ajax'; if (view()->exists("admin::$slug.browse-ajax")) { $view = "admin::$slug.browse-ajax"; } return Admin::view($view, compact( 'dataType', 'slug', 'isServerSide', 'isModelTranslatable', 'columns', 'pagination' )); }
****************************************
entailment
public function getAjaxList(Request $request) // GET THE SLUG, ex. 'posts', 'pages', etc. { // GET THE SLUG, ex. 'posts', 'pages', etc. $slug = $request->slug; // GET THE DataType based on the slug $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Check permission $this->authorize('browse', app($dataType->model_name)); $model = app($dataType->model_name); $query = $model->select('*'); if (method_exists($model, 'adminList')) { $query = $model->adminList()->select('*'); } if (!isset($request->order)) { if ($model->timestamps) { $query = $query->latest($model::CREATED_AT); } else { $relationships = $this->getRelationships($dataType); $query = $query->with($relationships)->orderBy($model->getKeyName(), 'DESC'); } } $query = DataTables::of($query); foreach ($dataType->ajaxList() as $dataRow) { $query->editColumn($dataRow->field, function($dataTypeContent) use($request, $slug, $dataRow){ $content = $dataTypeContent->{$dataRow->field}; $handler = AbstractHandler::initial($dataRow->type); if (method_exists($handler, 'getContentForList')) { $content = $handler->getContentForList($request, $slug, $dataRow, $dataTypeContent); } return $content; }); if ($dataRow->type == 'relationship') { $query->filterColumn($dataRow->field, function ($query, $keyword) use($dataRow){ $relationship = json_decode($dataRow->details); $ids = app($relationship->model)->where($relationship->label, 'like', "%$keyword%")->pluck($relationship->key); $query->whereIn($relationship->column, $ids); }); } } return $query ->addColumn('delete_checkbox', function($dataTypeContent) { return '<input type="checkbox" name="row_id" id="checkbox_' . $dataTypeContent->id . '" value="' . $dataTypeContent->id . '">'; }) ->addColumn('actions', function($dataTypeContent) use($dataType){ return Admin::view('admin::list.datatable.buttons', ['data' => $dataTypeContent, 'dataType' => $dataType]); }) ->rawColumns(array_merge($dataType->ajaxListFields(), ['delete_checkbox', 'actions'])) ->make(true); }
****************************************
entailment
public function store(Request $request) { $slug = $this->getSlug($request); $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); $model = app($dataType->model_name); // Check permission $this->authorize('edit', $model); if ($model instanceof ModelValidator) { // Model validation $validator = $model->validate($request); } else { // Crud validation $validator = $this->validateCrud($request->all(), $dataType->addRows); } if ($validator->fails()) { return response()->json(['errors' => $validator->messages()]); } if (!$request->ajax()) { $data = $this->insertUpdateData($request, $slug, $dataType->addRows, new $dataType->model_name()); event(new CrudDataAdded($request, $slug, $dataType, $data)); $redirect = redirect(admin_route($dataType->slug . ".index")); if ($dataType->isBackToParentCrud()) { $requestQuery = (object) $request->query(); $redirect = redirect(admin_route($requestQuery->crud_slug . '.' . $requestQuery->crud_action, $requestQuery->crud_id)); } if ($dataType->isBackToEdit()) { $redirect = redirect(admin_route($dataType->slug . '.edit', $data->id)); } return $redirect->with([ 'message' => __('admin.generic.successfully_updated')." {$dataType->display_name_singular}", 'alert-type' => 'success', ]); } }
POST (C)RUD - Store data. @param \Illuminate\Http\Request $request @return \Illuminate\Http\RedirectResponse
entailment
public function show(Request $request, $id) { $slug = $this->getSlug($request); $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Compatibility with Model binding. $id = $id instanceof Model ? $id->{$id->getKeyName()} : $id; $relationships = $this->getRelationships($dataType); if (strlen($dataType->model_name) != 0) { $model = app($dataType->model_name); $dataTypeContent = call_user_func([$model->with($relationships), 'findOrFail'], $id); } else { // If Model doest exist, get data from table name $dataTypeContent = DB::table($dataType->name)->where('id', $id)->first(); } // Replace relationships' keys for labels and create READ links if a slug is provided. $dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType, true); // If a column has a relationship associated with it, we do not want to show that field $this->removeRelationshipField($dataType, 'read'); // Check permission $this->authorize('read', $dataTypeContent); // Check if CRUD is Translatable $isModelTranslatable = is_crud_translatable($dataTypeContent); $view = 'admin::crud.read'; if (view()->exists("admin::$slug.read")) { $view = "admin::$slug.read"; } return Admin::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable')); }
****************************************
entailment
public function edit(Request $request, $id) { $slug = $this->getSlug($request); $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Compatibility with Model binding. $id = $id instanceof Model ? $id->{$id->getKeyName()} : $id; $relationships = $this->getRelationships($dataType); $dataTypeContent = (strlen($dataType->model_name) != 0) ? app($dataType->model_name)->with($relationships)->findOrFail($id) : DB::table($dataType->name)->where('id', $id)->first(); // If Model doest exist, get data from table name foreach ($dataType->editRows as $key => $row) { $details = json_decode($row->details); $dataType->editRows[$key]['col_width'] = isset($details->width) ? $details->width : 100; } // If a column has a relationship associated with it, we do not want to show that field $this->removeRelationshipField($dataType, 'edit'); // Check permission $this->authorize('edit', $dataTypeContent); // Check if CRUD is Translatable $isModelTranslatable = is_crud_translatable($dataTypeContent); $view = 'admin::crud.edit-add'; if (view()->exists("admin::$slug.edit-add")) { $view = "admin::$slug.edit-add"; } return Admin::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable')); }
****************************************
entailment
public function update(Request $request, $id) { $slug = $this->getSlug($request); $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Compatibility with Model binding. $id = $id instanceof Model ? $id->{$id->getKeyName()} : $id; $model = call_user_func([$dataType->model_name, 'findOrFail'], $id); // Check permission $this->authorize('edit', $model); if ($model instanceof ModelValidator) { // Model validation $validator = $model->validate($request); } else { // Crud validation $validator = $this->validateCrud($request->all(), $dataType->addRows); } if ($validator->fails()) { return response()->json(['errors' => $validator->messages()]); } if (!$request->ajax()) { $this->insertUpdateData($request, $slug, $dataType->editRows, $model); event(new CrudDataUpdated($request, $slug, $dataType, $model)); $redirect = redirect(admin_route($dataType->slug . ".index")); if ($dataType->isBackToParentCrud()) { $requestQuery = (object) $request->query(); $redirect = redirect(admin_route($requestQuery->crud_slug . '.' . $requestQuery->crud_action, $requestQuery->crud_id)); } if ($dataType->isBackToEdit()) { $redirect = redirect()->back(); } return $redirect->with([ 'message' => __('admin.generic.successfully_updated')." {$dataType->display_name_singular}", 'alert-type' => 'success', ]); } }
POST CR(U)D
entailment
public function destroy(Request $request, $id) { $slug = $this->getSlug($request); $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Check permission $this->authorize('delete', app($dataType->model_name)); // Init array of IDs $ids = []; if (empty($id)) { // Bulk delete, get IDs from POST $ids = explode(',', $request->ids); } else { // Single item delete, get ID from URL or Model Binding $ids[] = $id instanceof Model ? $id->{$id->getKeyName()} : $id; } foreach ($ids as $id) { $data = call_user_func([$dataType->model_name, 'findOrFail'], $id); $this->cleanup($dataType, $data); } $displayName = count($ids) > 1 ? $dataType->display_name_plural : $dataType->display_name_singular; $res = $data->destroy($ids); $data = $res ? [ 'message' => __('admin.generic.successfully_deleted')." {$displayName}", 'alert-type' => 'success', ] : [ 'message' => __('admin.generic.error_deleting')." {$displayName}", 'alert-type' => 'error', ]; if ($res) { event(new CrudDataDeleted($dataType, $data, $ids)); } $requestQuery = (object) $request->query(); if ($dataType->isBackToParentCrud($requestQuery)) { return redirect() ->route("admin.{$requestQuery->crud_slug}.{$requestQuery->crud_action}", $requestQuery->crud_id) ->with([ 'message' => __('admin.generic.successfully_added_new')." {$dataType->display_name_singular}", 'alert-type' => 'success', ]); } return redirect()->route("admin.{$dataType->slug}.index", $request->query())->with($data); }
****************************************
entailment
protected function cleanup($dataType, $data) { // Delete Translations, if present if (is_crud_translatable($data)) { $data->deleteAttributeTranslations($data->getTranslatableAttributes()); } // Delete Images $this->deleteCrudImages($data, $dataType->deleteRows->where('type', 'image')); // Delete Files foreach ($dataType->deleteRows->where('type', 'file') as $row) { $files = json_decode($data->{$row->field}); if ($files) { foreach ($files as $file) { $this->deleteFileIfExists($file->download_link); } } } }
Remove translations, images and files related to a CRUD item. @param \Illuminate\Database\Eloquent\Model $dataType @param \Illuminate\Database\Eloquent\Model $data @return void
entailment
public function deleteCrudImages($data, $rows) { foreach ($rows as $row) { $this->deleteFileIfExists($data->{$row->field}); $options = json_decode($row->details); if (isset($options->thumbnails)) { foreach ($options->thumbnails as $thumbnail) { $ext = explode('.', $data->{$row->field}); $extension = '.'.$ext[count($ext) - 1]; $path = str_replace($extension, '', $data->{$row->field}); $thumb_name = $thumbnail->name; $this->deleteFileIfExists($path.'-'.$thumb_name.$extension); } } } if ($rows->count() > 0) { event(new CrudImagesDeleted($data, $rows)); } }
Delete all images related to a CRUD item. @param \Illuminate\Database\Eloquent\Model $data @param \Illuminate\Database\Eloquent\Model $rows @return void
entailment
public function up() { // Create table for storing roles Schema::create('data_types', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('slug')->unique(); $table->string('display_name_singular'); $table->string('display_name_plural'); $table->string('icon')->nullable(); $table->string('model_name')->nullable(); $table->string('description')->nullable(); $table->boolean('generate_permissions')->default(false); $table->timestamps(); }); // Create table for storing roles Schema::create('data_rows', function (Blueprint $table) { $table->increments('id'); $table->integer('data_type_id')->unsigned(); $table->string('field'); $table->string('type'); $table->string('display_name')->nullable(); $table->boolean('required')->default(false); $table->boolean('browse')->default(true); $table->boolean('read')->default(true); $table->boolean('edit')->default(true); $table->boolean('add')->default(true); $table->boolean('delete')->default(true); $table->text('details')->nullable(); $table->foreign('data_type_id')->references('id')->on('data_types') ->onUpdate('cascade')->onDelete('cascade'); }); }
Run the migrations. @return void
entailment
protected function relationToLink(Model $item, DataType $dataType) { $relations = $item->getRelations(); if (!empty($relations) && array_filter($relations)) { foreach ($relations as $field => $relation) { if (isset($this->relation_field[$field])) { $field = $this->relation_field[$field]; } else { $field = snake_case($field); } $crud_data = $dataType->browseRows->where('field', $field)->first(); if (is_null($crud_data) || !isset($crud_data->details) || !isset(json_decode($crud_data->details)->relationship)) { continue; } $relationData = json_decode($crud_data->details)->relationship; if (!isset($relationData->label) || !isset($relationData->page_slug)) { continue; } if ($crud_data->type == 'select_multiple') { $relationItems = []; foreach ($relation as $model) { $relationItem = new \stdClass(); $relationItem->{$field} = $model[$relationData->label]; if (isset($relationData->page_slug)) { $id = $model->id; $relationItem->{$field.'_page_slug'} = url($relationData->page_slug, $id); } $relationItems[] = $relationItem; } $item[$field] = $relationItems; continue; // Go to the next relation } if (!is_object($item[$field])) { $item[$field] = $relation[$relationData->label]; } else { $tmp = $item[$field]; $item[$field] = $tmp; } if (isset($relationData->page_slug) && $relation) { $id = $relation->id; $item[$field.'_page_slug'] = url($relationData->page_slug, $id); } } } return $item; }
Create the URL for relationship's anchors in BROWSE and READ views. @param Model $item Object to modify @param DataType $dataType @return Model $item
entailment
public function cropPhotos($event) { $this->filesystem = config('admin.storage.disk'); $this->folder = config('admin.images.cropper.folder') . '/' . $event->slug; $this->quality = config('admin.images.cropper.quality', 100); $this->request = $event->request; $this->dataType = $event->dataType; $this->model = $event->model; $cropperImages = $this->dataType->rows()->whereType('image') ->where('details', 'like', '%cropper%')->get(); foreach ($cropperImages as $dataRow) { $details = json_decode($dataRow->details); if (!isset($details->cropper)) { continue; } if (!$this->request->{$dataRow->field}) { continue; } $this->cropPhoto($details->cropper, $dataRow); } return true; }
Save cropped photos. @param Illuminate\Http\Request $request @param string $slug @param Illuminate\Database\Eloquent\Collection $dataType @param Illuminate\Database\Eloquent\Model $model @return bool
entailment
private function cropPhoto($cropper, $dataRow) { $folder = $this->folder; $disk = Storage::disk($this->filesystem); //If a folder is not exists, then make the folder if (!$disk->exists($folder)) { $disk->makeDirectory($folder); } $itemId = $this->model->id; foreach ($cropper as $cropParam) { $inputName = $dataRow->field.'_'.$cropParam->name; $params = json_decode($this->request->get($inputName)); if (!is_object($params)) { return false; } $imageName = $this->request->{$dataRow->field}; $image = Image::make($disk->path($imageName)); $image->crop( (int) $params->w, (int) $params->h, (int) $params->x, (int) $params->y ); $image->resize($cropParam->size->width, $cropParam->size->height); $photoName = $folder.'/'.$inputName.'_'.$itemId.'_'.$cropParam->size->name.'.'.$image->extension; if (isset($cropParam->watermark) && file_exists($cropParam->watermark)) { $watermark = Image::make(public_path() . '/' . $cropParam->watermark); $watermark->resize($cropParam->size->width, null); $image->insert($watermark); } $image->save($disk->path($photoName), $this->quality); if (!empty($cropParam->resize)) { foreach ($cropParam->resize as $cropParamResize) { $image->resize($cropParamResize->width, $cropParamResize->height, function ($constraint) { $constraint->aspectRatio(); }); $photoName = $folder.'/'.$inputName.'_'.$itemId.'_'.$cropParamResize->name.'.'.$image->extension; $image->save($disk->path($photoName), $this->quality); } } $this->model->{$dataRow->field} = $imageName; $this->model->save(); } }
Crop photo by coordinates. @param array $cropper @param Illuminate\Database\Eloquent\Collection $dataRow @return void
entailment
public function getCroppedPhoto($column, $prefix, $suffix) { $extension = 'jpeg'; if (isset($this->$column)) { $extension = pathinfo($this->$column, PATHINFO_EXTENSION) ?: $extension; } $photoName = config('admin.images.cropper.folder') .'/'.str_replace('_', '-', $this->getTable()) .'/'.$column.'_'.$prefix.'_'.$this->id.'_'.$suffix.'.'.$extension; return Storage::disk($this->filesystem)->url($photoName); }
Get the cropped photo url. @param string $column @param string $prefix @param string $suffix @return string
entailment
public function getLocation($column) { $model = self::select(DB::Raw('ST_AsText('.$column.') AS '.$column)) ->where('id', $this->id) ->first(); return isset($model) ? $model->$column : ''; }
Get location as WKT from Geometry for given field. @param string $column @return string
entailment
public function getCoordinates() { $coords = []; if (!empty($this->spatial)) { foreach ($this->spatial as $column) { $clear = trim(preg_replace('/[a-zA-Z\(\)]/', '', $this->getLocation($column))); if (!empty($clear)) { foreach (explode(',', $clear) as $point) { list($lat, $lng) = explode(' ', $point); $coords[] = [ 'lat' => $lat, 'lng' => $lng, ]; } } } } return $coords; }
Format and return array of (lat,lng) pairs of points fetched from the database. @return array $coords
entailment
public function run() { $dataType = DataType::where('slug', 'posts')->firstOrFail(); if (!$dataType->exists) { return false; } FormDesigner::firstOrCreate([ 'data_type_id' => $dataType->id, 'options' => json_encode([ [ 'class' => 'col-md-8', 'panels' => [ [ 'class' => 'panel', 'title' => '<i class="admin-character"></i> Post Title The title for your post', 'fields' => [ 'title', ], ], [ 'class' => 'panel', 'title' => 'Post Content', 'fields' => [ 'body', ], ], [ 'class' => 'panel', 'title' => 'Excerpt <small>Small description of this post</small>', 'fields' => [ 'excerpt', ], ], ], ], [ 'class' => 'col-md-4', 'panels' => [ [ 'class' => 'panel panel-warning', 'title' => 'Post Details', 'fields' => [ 'slug', 'status', 'category_id', 'featured', ], ], [ 'class' => 'panel panel-primary', 'title' => 'Post Image', 'fields' => [ 'image', ], ], [ 'class' => 'panel panel-info', 'title' => 'admin.post.seo_content', 'fields' => [ 'meta_keywords', 'meta_description', 'seo_title', ], ], ], ], ]), ]); }
Run the database seeds. @return void
entailment
public function handle(Filesystem $filesystem) { $this->info('Publishing the Admin assets, database, language, and config files'); $this->call('vendor:publish', ['--provider' => AdminServiceProvider::class]); $this->call('vendor:publish', ['--provider' => ImageServiceProviderLaravel5::class]); $this->info('Migrating the database tables into your application'); $this->call('migrate'); $this->info('Attempting to set Admin User model as parent to App\User'); if (file_exists(app_path('User.php'))) { $str = file_get_contents(app_path('User.php')); if ($str !== false) { $str = str_replace('extends Authenticatable', "extends \LaravelAdminPanel\Models\User", $str); file_put_contents(app_path('User.php'), $str); } } else { $this->warn('Unable to locate "app/User.php". Did you move this file?'); $this->warn('You will need to update this manually. Change "extends Authenticatable" to "extends \LaravelAdminPanel\Models\User" in your User model'); } $this->info('Dumping the autoloaded files and reloading all new files'); $composer = $this->findComposer(); $process = new Process($composer.' dump-autoload'); $process->setWorkingDirectory(base_path())->run(); $this->info('Adding Admin routes to routes/web.php'); $routes_contents = $filesystem->get(base_path('routes/web.php')); if (false === strpos($routes_contents, 'Admin::routes()')) { $filesystem->append( base_path('routes/web.php'), "\n\nRoute::group(['prefix' => 'admin'], function () {\n Admin::routes();\n});\n" ); } \Route::group(['prefix' => 'admin'], function () { \Admin::routes(); }); $this->info('Seeding data into the database'); $this->seed('AdminDatabaseSeeder'); if ($this->option('with-dummy')) { $this->seed('AdminDummyDatabaseSeeder'); } $this->info('Adding the storage symlink to your public folder'); $this->call('storage:link'); $this->info('Successfully installed Admin! Enjoy'); }
Execute the console command. @param \Illuminate\Filesystem\Filesystem $filesystem @return void
entailment
public function add(Request $request, $table) { Admin::canOrFail('browse_database'); $data = $this->prepopulateInfo($table); $data['fieldOptions'] = SchemaManager::describeTable($table); return Admin::view('admin::tools.database.edit-add-crud', $data); }
@param \Illuminate\Http\Request $request @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
entailment
protected function prepareOptions() { if (!empty($this->configuration)) { if (isset($this->configuration['theme'])) { $this->theme = $this->configuration['theme']; } if (isset($this->configuration['modules']['formula'])) { $this->_katex = true; } if (isset($this->configuration['modules']['syntax'])) { $this->_highlight = true; } $this->_quillConfiguration = $this->configuration; } else { if (!empty($this->theme)) { $this->_quillConfiguration['theme'] = $this->theme; } if (!empty($this->bounds)) { $this->_quillConfiguration['bounds'] = new JsExpression($this->bounds); } if (!empty($this->debug)) { $this->_quillConfiguration['debug'] = $this->debug; } if (!empty($this->placeholder)) { $this->_quillConfiguration['placeholder'] = $this->placeholder; } if (!empty($this->formats)) { $this->_quillConfiguration['formates'] = $this->formats; } if (!empty($this->modules)) { foreach ($this->modules as $module => $config) { $this->_quillConfiguration['modules'][$module] = $config; if ($module === 'formula') { $this->_katex = true; } if ($module === 'syntax') { $this->_highlight = true; } } } if (!empty($this->toolbarOptions)) { $this->_quillConfiguration['modules']['toolbar'] = $this->renderToolbar(); } } }
Prepares Quill configuration.
entailment
public function registerClientScript() { $view = $this->view; if ($this->_katex) { $katexAsset = KatexAsset::register($view); $katexAsset->version = $this->katexVersion; } if ($this->_highlight) { $highlightAsset = HighlightAsset::register($view); $highlightAsset->version = $this->highlightVersion; $highlightAsset->style = $this->highlightStyle; } $asset = QuillAsset::register($view); $asset->theme = $this->theme; $asset->version = $this->quillVersion; $configs = Json::encode($this->_quillConfiguration); $editor = 'q_' . preg_replace('~[^0-9_\p{L}]~u', '_', $this->id); $js = "var $editor=new Quill(\"#editor-{$this->id}\",$configs);"; $js .= "document.getElementById(\"editor-{$this->id}\").onclick=function(e){document.querySelector(\"#editor-{$this->id} .ql-editor\").focus();};"; $js .= "$editor.on('text-change',function(){document.getElementById(\"{$this->_fieldId}\").value=$editor.root.innerHTML;});"; if (!empty($this->js)) { $js .= str_replace('{quill}', $editor, $this->js); } $view->registerJs($js, View::POS_END); }
Registers widget assets. Note that Quill works without jQuery.
entailment
public function renderToolbar() { if ($this->toolbarOptions === self::TOOLBAR_BASIC) { return [ [ 'bold', 'italic', 'underline', 'strike', ], [ ['list' => 'ordered'], ['list' => 'bullet'], ], [ ['align' => []], ], [ 'link', ], ]; } if ($this->toolbarOptions === self::TOOLBAR_FULL) { return [ [ ['font' => []], [ 'size' => [ 'small', false, 'large', 'huge', ], ], ], [ 'bold', 'italic', 'underline', 'strike', ], [ ['color' => []], ['background' => []], ], [ ['script' => 'sub'], ['script' => 'super'], ], [ ['header' => 1], ['header' => 2], 'blockquote', 'code-block', ], [ ['list' => 'ordered'], ['list' => 'bullet'], ['indent' => '-1'], ['indent' => '+1'], ], [ ['direction' => 'rtl'], ['align' => []], ], [ 'link', 'image', 'video', ], [ 'clean', ], ]; } return $this->toolbarOptions; }
Prepares predefined set of buttons. @return bool|array
entailment
protected function getAdministratorRole() { $role = Admin::model('Role')->firstOrNew([ 'name' => 'admin', ]); if (!$role->exists) { $role->fill([ 'display_name' => 'Administrator', ])->save(); } return $role; }
Get the administrator role, create it if it does not exists. @return mixed
entailment
public static function display($menuName, $type = null, array $options = []) { // GET THE MENU - sort collection in blade $menu = static::where('name', '=', $menuName) ->with(['parent_items.children' => function ($q) { $q->orderBy('order'); }]) ->first(); // Check for Menu Existence if (!isset($menu)) { return false; } event(new MenuDisplay($menu)); // Convert options array into object $options = (object) $options; // Set static vars values for admin menus if (in_array($type, ['admin', 'admin_menu'])) { $permissions = Admin::model('Permission')->all(); $dataTypes = Admin::model('DataType')->all(); $prefix = trim(route('admin.dashboard', [], false), '/'); $user_permissions = null; if (!Auth::guest()) { $user = Admin::model('User')->find(Auth::id()); $user_permissions = $user->role->permissions->pluck('key')->toArray(); } $options->user = (object) compact('permissions', 'dataTypes', 'prefix', 'user_permissions'); // change type to blade template name - TODO funky names, should clean up later $type = 'admin::menu.'.$type; } else { if (is_null($type)) { $type = 'admin::menu.default'; } elseif ($type == 'bootstrap' && !view()->exists($type)) { $type = 'admin::menu.bootstrap'; } } if (!isset($options->locale)) { $options->locale = app()->getLocale(); } return new \Illuminate\Support\HtmlString( \Illuminate\Support\Facades\View::make($type, ['items' => $menu->parent_items->sortBy('order'), 'options' => $options])->render() ); }
Display menu. @param string $menuName @param string|null $type @param array $options @return string
entailment
public function run() { $count = Admin::model('Post')->count(); $string = trans_choice('admin.dimmer.post', $count); return view('admin::dimmer', array_merge($this->config, [ 'icon' => 'admin-news', 'title' => "{$count} {$string}", 'text' => __('admin.dimmer.post_text', ['count' => $count, 'string' => Str::lower($string)]), 'button' => [ 'text' => __('admin.dimmer.post_link_text'), 'link' => route('admin.posts.index'), ], 'image' => admin_asset('images/widget-backgrounds/02.jpg'), ])); }
Treat this method as a controller action. Return view() or other content to display.
entailment
public function thumbnail($type) { // We take image from posts field $image = $this->attributes['image']; // We need to get extension type ( .jpeg , .png ...) $ext = pathinfo($image, PATHINFO_EXTENSION); // We remove extension from file name so we can append thumbnail type $name = rtrim($image, '.'.$ext); // We merge original name + type + extension return $name.'-'.$type.'.'.$ext; }
Method for returning specific thumbnail for post.
entailment
public function register() { $this->app->register(AdminEventServiceProvider::class); $this->app->register(ImageServiceProvider::class); $this->app->register(WidgetServiceProvider::class); $this->app->register(DoctrineSupportServiceProvider::class); $loader = AliasLoader::getInstance(); $loader->alias('Admin', AdminFacade::class); $this->app->singleton('admin', function () { return new Admin(); }); $this->loadHelpers(); $this->registerAlertComponents(); $this->registerFormFields(); $this->registerWidgets(); $this->registerConfigs(); if ($this->app->runningInConsole()) { $this->registerPublishableResources(); $this->registerConsoleCommands(); } if (!$this->app->runningInConsole() || config('app.env') == 'testing') { $this->registerAppCommands(); } }
Register the application services.
entailment
public function boot(Router $router, Dispatcher $event) { if (config('admin.user.add_default_role_on_register')) { $app_user = config('admin.user.namespace'); $app_user::created(function ($user) { if (is_null($user->role_id)) { AdminFacade::model('User')->findOrFail($user->id) ->setRole(config('admin.user.default_role')) ->save(); } }); } $this->loadViewsFrom(__DIR__.'/../resources/views', 'admin'); if (app()->version() >= 5.4) { $router->aliasMiddleware('admin.user', AdminMiddleware::class); if (config('app.env') == 'testing') { $this->loadMigrationsFrom(realpath(__DIR__.'/migrations')); } } else { $router->middleware('admin.user', AdminMiddleware::class); } $this->registerGates(); $this->registerViewComposers(); $event->listen('admin.alerts.collecting', function () { $this->addStorageSymlinkAlert(); }); $this->bootTranslatorCollectionMacros(); }
Bootstrap the application services. @param \Illuminate\Routing\Router $router
entailment
protected function addStorageSymlinkAlert() { if (app('router')->current() !== null) { $currentRouteAction = app('router')->current()->getAction(); } else { $currentRouteAction = null; } $routeName = is_array($currentRouteAction) ? array_get($currentRouteAction, 'as') : null; if ($routeName != 'admin.dashboard') { return; } $storage_disk = (!empty(config('admin.storage.disk'))) ? config('admin.storage.disk') : 'public'; if (request()->has('fix-missing-storage-symlink') && !file_exists(public_path('storage'))) { $this->fixMissingStorageSymlink(); } elseif (!file_exists(public_path('storage')) && $storage_disk == 'public') { $alert = (new Alert('missing-storage-symlink', 'warning')) ->title(__('admin.error.symlink_missing_title')) ->text(__('admin.error.symlink_missing_text')) ->button(__('admin.error.symlink_missing_button'), '?fix-missing-storage-symlink=1'); AdminFacade::addAlert($alert); } }
Add storage symlink alert.
entailment
protected function registerAlertComponents() { $components = ['title', 'text', 'button']; foreach ($components as $component) { $class = 'LaravelAdminPanel\\Alert\\Components\\'.ucfirst(camel_case($component)).'Component'; $this->app->bind("admin.alert.components.{$component}", $class); } }
Register alert components.
entailment
protected function registerWidgets() { $default_widgets = ['LaravelAdminPanel\\Widgets\\UserDimmer', 'LaravelAdminPanel\\Widgets\\PostDimmer', 'LaravelAdminPanel\\Widgets\\PageDimmer']; $widgets = config('admin.dashboard.widgets', $default_widgets); foreach ($widgets as $widget) { Widget::group('admin::dimmers')->addWidget($widget); } }
Register widget.
entailment
protected function checkPermission(User $user, $model, $action) { $dataType = Admin::model('DataType'); $dataType = $dataType->where('model_name', get_class($model))->first(); return $user->hasPermission($action.'_'.$dataType->slug); }
Check if user has an associated permission. @param \LaravelAdminPanel\Contracts\User $user @param object $model @param string $action @return bool
entailment
public function handle(CrudAdded $crud) { if (config('admin.add_crud_permission') && file_exists(base_path('routes/web.php'))) { // Create permission // // Permission::generateFor(snake_case($crud->dataType->slug)); $role = Role::where('name', 'admin')->firstOrFail(); // Get permission for added table $permissions = Permission::where(['slug' => $crud->dataType->slug])->get()->pluck('id')->all(); // Assign permission to admin $role->permissions()->attach($permissions); } }
Create Permission for a given CRUD. @param CrudAdded $event @return void
entailment
public function handle($event) { $needCrop = $event->dataType->rows() ->whereType('image') ->where('details', 'like', '%cropper%') ->exists(); if ($needCrop) { $event->model->cropPhotos($event); } }
Crop the images for a given CRUD. @param $event @return void
entailment
public function up() { Schema::table('data_types', function (Blueprint $table) { $table->string('pagination', 10)->default('js')->after('generate_permissions'); if (Schema::hasColumn('permissions', 'server_side')) { $table->dropColumn('server_side'); } }); }
Run the migrations. @return void
entailment
protected function generateContent($stub, $class) { $namespace = config('admin.controllers.namespace', 'LaravelAdminPanel\\Http\\Controllers'); $content = str_replace( 'DummyNamespace', $namespace, $stub ); $content = str_replace( 'FullBaseDummyClass', 'LaravelAdminPanel\\Http\\Controllers\\'.$class, $content ); $content = str_replace( 'BaseDummyClass', 'Base'.$class, $content ); $content = str_replace( 'DummyClass', $class, $content ); return $content; }
Generate real content from stub. @param $stub @param $class @return mixed
entailment
public function delete_file_folder(Request $request) { $folderLocation = $request->folder_location; $fileFolder = $request->file_folder; $type = $request->type; $success = true; $error = ''; if (is_array($folderLocation)) { $folderLocation = rtrim(implode('/', $folderLocation), '/'); } $location = "{$this->directory}/{$folderLocation}"; $fileFolder = "{$location}/{$fileFolder}"; if ($type == 'folder') { if (!Storage::disk($this->filesystem)->deleteDirectory($fileFolder)) { $error = __('admin.media.error_deleting_folder'); $success = false; } } elseif (!Storage::disk($this->filesystem)->delete($fileFolder)) { $error = __('admin.media.error_deleting_file'); $success = false; } return compact('success', 'error'); }
Delete File or Folder with 5.3
entailment
public function move_file(Request $request) { $source = $request->source; $destination = $request->destination; $folderLocation = $request->folder_location; $success = false; $error = ''; if (is_array($folderLocation)) { $folderLocation = rtrim(implode('/', $folderLocation), '/'); } $location = "{$this->directory}/{$folderLocation}"; $source = "{$location}/{$source}"; $destination = strpos($destination, '/../') !== false ? $this->directory.'/'.dirname($folderLocation).'/'.str_replace('/../', '', $destination) : "{$location}/{$destination}"; if (!file_exists($destination)) { if (Storage::disk($this->filesystem)->move($source, $destination)) { $success = true; } else { $error = __('admin.media.error_moving'); } } else { $error = __('admin.media.error_already_exists'); } return compact('success', 'error'); }
NEEDS TESTING
entailment
public function upload(Request $request) { try { $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix(); $allowedImageMimeTypes = [ 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/svg+xml', ]; if (in_array($request->file->getMimeType(), $allowedImageMimeTypes)) { $file = $request->file->store($request->upload_path, $this->filesystem); $image = Image::make($realPath.$file); if ($request->file->getClientOriginalExtension() == 'gif') { copy($request->file->getRealPath(), $realPath.$file); } else { $image->orientate()->save($realPath.$file); } } else { $file = $request->file->move($realPath, $request->file->getClientOriginalName()); } $success = true; $message = __('admin.media.success_uploaded_file'); $path = preg_replace('/^public\//', '', $file); } catch (Exception $e) { $success = false; $message = $e->getMessage(); $path = ''; } return response()->json(compact('success', 'message', 'path')); }
Upload Working with 5.3
entailment
public function remove(Request $request) { try { // GET THE SLUG, ex. 'posts', 'pages', etc. $slug = $request->get('slug'); // GET image name $image = $request->get('image'); // GET record id $id = $request->get('id'); // GET field name $field = $request->get('field'); // GET THE DataType based on the slug $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first(); // Check permission Admin::canOrFail('delete_'.$dataType->name); // Load model and find record $model = app($dataType->model_name); $data = $model::find([$id])->first(); // Check if field exists if (!isset($data->{$field})) { throw new Exception(__('admin.generic.field_does_not_exist'), 400); } // Check if valid json if (is_null(@json_decode($data->{$field}))) { throw new Exception(__('admin.json.invalid'), 500); } // Decode field value $fieldData = @json_decode($data->{$field}, true); // Flip keys and values $fieldData = array_flip($fieldData); // Check if image exists in array if (!array_key_exists($image, $fieldData)) { throw new Exception(__('admin.media.image_does_not_exist'), 400); } // Remove image from array unset($fieldData[$image]); // Generate json and update field $data->{$field} = json_encode(array_values(array_flip($fieldData))); $data->save(); return response()->json([ 'data' => [ 'status' => 200, 'message' => __('admin.media.image_removed'), ], ]); } catch (Exception $e) { $code = 500; $message = __('admin.generic.internal_error'); if ($e->getCode()) { $code = $e->getCode(); } if ($e->getMessage()) { $message = $e->getMessage(); } return response()->json([ 'data' => [ 'status' => $code, 'message' => $message, ], ], $code); } }
REMOVE FILE
entailment
public function crop(Request $request) { $createMode = $request->get('createMode') === 'true'; $x = $request->get('x'); $y = $request->get('y'); $height = $request->get('height'); $width = $request->get('width'); $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix(); $originImagePath = $realPath.$request->upload_path.'/'.$request->originImageName; try { if ($createMode) { // create a new image with the cpopped data $fileNameParts = explode('.', $request->originImageName); array_splice($fileNameParts, count($fileNameParts) - 1, 0, 'cropped_'.time()); $newImageName = implode('.', $fileNameParts); $destImagePath = $realPath.$request->upload_path.'/'.$newImageName; } else { // override the original image $destImagePath = $originImagePath; } Image::make($originImagePath)->crop($width, $height, $x, $y)->save($destImagePath); $success = true; $message = __('admin.media.success_crop_image'); } catch (Exception $e) { $success = false; $message = $e->getMessage(); } return response()->json(compact('success', 'message')); }
Crop Image
entailment
public function registerAssetFiles($view) { switch ($this->theme) { case Quill::THEME_SNOW: $this->css = [$this->url . $this->version . '/quill.snow.css']; break; case Quill::THEME_BUBBLE: $this->css = [$this->url . $this->version . '/quill.bubble.css']; break; default: $this->css = [$this->url . $this->version . '/quill.core.css']; } $this->js = [$this->url . $this->version . '/quill.min.js']; parent::registerAssetFiles($view); }
Register CSS and JS file based on theme and version. @param \yii\web\View $view the view that the asset files are to be registered with.
entailment
public function down() { if (Schema::hasColumn('permissions', 'table_name')) { return false; } Schema::table('permissions', function (Blueprint $table) { $table->renameColumn('slug', 'table_name'); }); $dataTypes = DataType::all(); $permissions = Permission::whereNotNull('table_name')->get(); foreach ($permissions as $permission) { $dataType = $dataTypes->where('slug', $permission->table_name)->first(); if ($dataType && $dataType->slug) { $permission->key = str_replace($dataType->slug, $dataType->name, $permission->key); $permission->table_name = $dataType->name; $permission->save(); } } }
Reverse the migrations. @return void
entailment
public function run() { $role = Role::firstOrNew(['name' => 'admin']); if (!$role->exists) { $role->fill([ 'display_name' => 'Administrator', ])->save(); } $role = Role::firstOrNew(['name' => 'user']); if (!$role->exists) { $role->fill([ 'display_name' => 'Normal User', ])->save(); } }
Auto generated seed file.
entailment
public function handle(CrudAdded $crud) { if (config('admin.add_crud_menu_item') && file_exists(base_path('routes/web.php'))) { require base_path('routes/web.php'); $menu = Menu::where('name', 'admin')->firstOrFail(); $menuItem = MenuItem::firstOrNew([ 'menu_id' => $menu->id, 'title' => $crud->dataType->display_name_plural, 'url' => '/'.config('admin.prefix', 'admin').'/'.$crud->dataType->slug, ]); $order = Admin::model('MenuItem')->highestOrderMenuItem(); if (!$menuItem->exists) { $menuItem->fill([ 'target' => '_self', 'icon_class' => $crud->dataType->icon, 'color' => null, 'parent_id' => null, 'order' => $order, ])->save(); } } }
Create a MenuItem for a given CRUD. @param CrudAdded $event @return void
entailment
public function sortByUrl() { $params = $_GET; $isDesc = isset($params['sort_order']) && $params['sort_order'] != 'asc'; if ($this->isCurrentSortField() && $isDesc) { $params['sort_order'] = 'asc'; } else { $params['sort_order'] = 'desc'; } $params['order_by'] = $this->field; return url()->current().'?'.http_build_query($params); }
Build the URL to sort data type by this field. @return string Built URL
entailment
protected function checkPermission(User $user, $model, $action) { $regex = str_replace('/', '\/', preg_quote(route('admin.dashboard'))); $slug = preg_replace('/'.$regex.'/', '', $model->link(true)); $slug = str_replace('/', '', explode('/', ltrim($slug, '/'))[0]); if (!isset(self::$datatypes[$slug])) { self::$datatypes[$slug] = DataType::where('slug', $slug)->first(); } if ($str = self::$datatypes[$slug]) { $slug = $str->slug; } if ($slug == '') { $slug = 'admin'; } // If permission doesn't exist, we can't check it! if (!Admin::model('Permission')->where('key', 'browse_'.$slug)->exists()) { return true; } return $user->hasPermission('browse_'.$slug); }
Check if user has an associated permission. @param User $user @param object $model @param string $action @return bool
entailment
public function run() { $postDataType = DataType::where('slug', 'posts')->firstOrFail(); $pageDataType = DataType::where('slug', 'pages')->firstOrFail(); $userDataType = DataType::where('slug', 'users')->firstOrFail(); $categoryDataType = DataType::where('slug', 'categories')->firstOrFail(); $menuDataType = DataType::where('slug', 'menus')->firstOrFail(); $roleDataType = DataType::where('slug', 'roles')->firstOrFail(); $formDesignerDataType = DataType::where('slug', 'form-designer')->firstOrFail(); $dataRow = $this->dataRow($postDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'ID', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($postDataType, 'author_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'Author', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 1, 'details' => '', 'order' => 2, ])->save(); } $dataRow = $this->dataRow($postDataType, 'slug'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'slug', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'slugify' => [ 'origin' => 'title', 'forceUpdate' => true, ], ]), 'order' => 3, ])->save(); } $dataRow = $this->dataRow($postDataType, 'status'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'status', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'default' => 'DRAFT', 'options' => [ 'PUBLISHED' => 'published', 'DRAFT' => 'draft', 'PENDING' => 'pending', ], ]), 'order' => 4, ])->save(); } $dataRow = $this->dataRow($postDataType, 'category_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'Category', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 0, 'details' => json_encode([ 'relationship' => [ 'key' => 'id', 'label' => 'name', ] ]), 'order' => 5, ])->save(); } $dataRow = $this->dataRow($postDataType, 'title'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => '', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 6, ])->save(); } $dataRow = $this->dataRow($postDataType, 'excerpt'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text_area', 'display_name' => '', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 7, ])->save(); } $dataRow = $this->dataRow($postDataType, 'body'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'rich_text_box', 'display_name' => '', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'validation' => [ 'rule' => 'required', ] ]), 'order' => 8, ])->save(); } $dataRow = $this->dataRow($postDataType, 'image'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'image', 'display_name' => 'Post Image', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'cropper' => [ [ 'name' => 'avatar', 'size' => [ 'name' => 'max', 'width' => '300', 'height' => '200', ], 'resize' => [ [ 'name' => 'norm', 'width' => '200', 'height' => 'null', ], [ 'name' => 'min', 'width' => '100', 'height' => 'null', ], ], ], ], ]), 'order' => 9, ])->save(); } $dataRow = $this->dataRow($postDataType, 'meta_description'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text_area', 'display_name' => 'meta_description', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 10, ])->save(); } $dataRow = $this->dataRow($postDataType, 'meta_keywords'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text_area', 'display_name' => 'meta_keywords', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 11, ])->save(); } $dataRow = $this->dataRow($postDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 12, ])->save(); } $dataRow = $this->dataRow($postDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 13, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'author_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'author_id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => json_encode([ 'relationship' => [ 'key' => 'id', 'label' => 'name', ] ]), 'order' => 2, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'title'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'title', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 3, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'excerpt'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text_area', 'display_name' => 'excerpt', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 4, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'body'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'rich_text_box', 'display_name' => 'body', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 5, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'slug'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'slug', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'slugify' => [ 'origin' => 'title', ], ]), 'order' => 6, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'meta_description'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'meta_description', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 7, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'meta_keywords'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'meta_keywords', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 8, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'status'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'status', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'default' => 'INACTIVE', 'options' => [ 'INACTIVE' => 'INACTIVE', 'ACTIVE' => 'ACTIVE', ], ]), 'order' => 9, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 10, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 11, ])->save(); } $dataRow = $this->dataRow($pageDataType, 'image'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'image', 'display_name' => 'image', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 12, ])->save(); } $dataRow = $this->dataRow($userDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($userDataType, 'name'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'name', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 2, ])->save(); } $dataRow = $this->dataRow($userDataType, 'email'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'email', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 3, ])->save(); } $dataRow = $this->dataRow($userDataType, 'password'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'password', 'display_name' => 'password', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 1, 'add' => 1, 'delete' => 0, 'details' => '', 'order' => 4, ])->save(); } $dataRow = $this->dataRow($userDataType, 'user_belongsto_role_relationship'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'relationship', 'display_name' => 'Role', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 0, 'details' => '{"model":"LaravelAdminPanel\\\Models\\\Role","table":"roles","type":"belongsTo","column":"role_id","key":"id","label":"name","pivot_table":"roles","pivot":"0"}', 'order' => 10, ])->save(); } $dataRow = $this->dataRow($userDataType, 'remember_token'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'remember_token', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 5, ])->save(); } $dataRow = $this->dataRow($userDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 6, ])->save(); } $dataRow = $this->dataRow($userDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 7, ])->save(); } $dataRow = $this->dataRow($userDataType, 'avatar'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'image', 'display_name' => 'avatar', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 8, ])->save(); } $dataRow = $this->dataRow($menuDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($menuDataType, 'name'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'name', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 2, ])->save(); } $dataRow = $this->dataRow($menuDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 3, ])->save(); } $dataRow = $this->dataRow($menuDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 4, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'parent_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'parent_id', 'required' => 0, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'default' => '', 'null' => '', 'options' => [ '' => '-- None --', ], 'relationship' => [ 'key' => 'id', 'label' => 'name', ], ]), 'order' => 2, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'order'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'order', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'default' => 1, ]), 'order' => 3, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'name'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'name', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 4, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'slug'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'slug', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'slugify' => [ 'origin' => 'name', ], ]), 'order' => 5, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 0, 'browse' => 0, 'read' => 1, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 6, ])->save(); } $dataRow = $this->dataRow($categoryDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 7, ])->save(); } $dataRow = $this->dataRow($roleDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($roleDataType, 'name'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'Name', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 2, ])->save(); } $dataRow = $this->dataRow($roleDataType, 'created_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'created_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 3, ])->save(); } $dataRow = $this->dataRow($roleDataType, 'updated_at'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'timestamp', 'display_name' => 'updated_at', 'required' => 0, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 4, ])->save(); } $dataRow = $this->dataRow($roleDataType, 'display_name'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'Display Name', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 5, ])->save(); } $dataRow = $this->dataRow($postDataType, 'seo_title'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'seo_title', 'required' => 0, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 14, ])->save(); } $dataRow = $this->dataRow($postDataType, 'featured'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'checkbox', 'display_name' => 'featured', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 15, ])->save(); } $dataRow = $this->dataRow($userDataType, 'role_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'text', 'display_name' => 'role_id', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => '', 'order' => 9, ])->save(); } $dataRow = $this->dataRow($formDesignerDataType, 'id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'number', 'display_name' => 'id', 'required' => 1, 'browse' => 0, 'read' => 0, 'edit' => 0, 'add' => 0, 'delete' => 0, 'details' => '', 'order' => 1, ])->save(); } $dataRow = $this->dataRow($formDesignerDataType, 'data_type_id'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'select_dropdown', 'display_name' => 'Data Type', 'required' => 1, 'browse' => 1, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'relationship' => [ 'key' => 'id', 'label' => 'display_name_singular', ], ]), 'order' => 2, ])->save(); } $dataRow = $this->dataRow($formDesignerDataType, 'options'); if (!$dataRow->exists) { $dataRow->fill([ 'type' => 'code_editor', 'display_name' => 'Options', 'required' => 1, 'browse' => 0, 'read' => 1, 'edit' => 1, 'add' => 1, 'delete' => 1, 'details' => json_encode([ 'formfields_custom' => 'json_editor', ]), 'order' => 3, ])->save(); } }
Auto generated seed file.
entailment
public function handle($request, Closure $next) { if (!Auth::guest()) { $user = Admin::model('User')->find(Auth::id()); return $user->hasPermission('browse_admin') ? $next($request) : redirect('/'); } $urlLogin = route('admin.login'); $urlIntended = $request->url(); if ($urlIntended == $urlLogin) { $urlIntended = null; } return redirect($urlLogin)->with('url.intended', $urlIntended); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public function registerAssetFiles($view) { $this->css = [$this->url . $this->version . '/styles/' . $this->style]; $this->js = [$this->url . $this->version . '/highlight.min.js']; parent::registerAssetFiles($view); }
Register CSS and JS file based on version. @param \yii\web\View $view the view that the asset files are to be registered with.
entailment
public function translations() { return $this->hasMany(Translation::class, 'foreign_key', $this->getKeyName()) ->where('table_name', $this->getTable()) ->whereIn('locale', config('admin.multilingual.locales', [])); }
Load translations relation. @return mixed
entailment
public function prepareTranslations(&$request) { $translations = []; // Translatable Fields $transFields = $this->getTranslatableAttributes(); foreach ($transFields as $field) { $trans = json_decode($request->input($field.'_i18n'), true); // Set the default local value $request->merge([$field => $trans[config('admin.multilingual.default', 'en')]]); $translations[$field] = $this->setAttributeTranslations( $field, $trans ); // Remove field hidden input unset($request[$field.'_i18n']); } // Remove language selector input unset($request['i18n_selector']); return $translations; }
Prepare translations and set default locale field value. @param object $request @return array translations
entailment
public function handle($request, Closure $next, $role) { if ($this->auth->check() && $this->auth->user()->isRole($role)) { return $next($request); } throw new RoleDeniedException($role); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param int|string $role @return mixed @throws \HttpOz\Roles\Exceptions\RoleDeniedException
entailment
public function getRoles() { if ( $this->cacheEnabled() ) { if ( is_null( $this->getCachedRoles() ) ) { Cache::remember( 'roles.user_' . $this->id, config( 'roles.cache.expiry' ), function () { return $this->roles()->get(); } ); } return $this->getCachedRoles(); } else { return $this->roles()->get(); } }
Get all roles as collection. @return \Illuminate\Database\Eloquent\Collection
entailment
public function isRole( $role, $all = false ) { if ( $this->isPretendEnabled() ) { return $this->pretend( 'isRole' ); } return $this->{$this->getMethodName( 'is', $all )}( $role ); }
Check if the user has a role or roles. @param int|string|array $role @param bool $all @return bool
entailment
private function executeQuery($query) { $content = (string)$this->getAdapter()->get($query)->getBody(); if (empty($content)) { throw new NoResult(sprintf('Could not execute query %s', $query)); } $data = Xml::build($content); if (empty($data) || empty($data->result)) { throw new NoResult(sprintf('Could not execute query %s', $query)); } $data = (array)$data->result; $adminLevels = []; if (!empty($data['isp']) || !empty($data['isp'])) { $adminLevels[] = [ 'name' => isset($data['isp']) ? $data['isp'] : null, 'code' => null, 'level' => 1 ]; } return $this->returnResults([ array_merge($this->getDefaults(), [ 'latitude' => isset($data['latitude']) ? $data['latitude'] : null, 'longitude' => isset($data['longitude']) ? $data['longitude'] : null, 'locality' => isset($data['city']) ? $data['city'] : null, 'adminLevels' => $adminLevels, 'country' => isset($data['countryname']) ? $data['countryname'] : null, 'countryCode' => isset($data['countrycode']) ? $data['countrycode'] : null, ]) ]); }
@param string $query @return \Geocoder\Model\AddressCollection
entailment
public function boot() { $this->publishes([ __DIR__ . '/../config/roles.php' => config_path('roles.php') ], 'config'); $stub = __DIR__ . '/../database/migrations/'; $target = database_path('migrations').'/'; $this->publishes([ $stub.'create_roles_table.php' => $target . '2016_09_04_000000_create_roles_table.php', $stub.'create_role_user_table.php' => $target . '2016_09_04_100000_create_role_user_table.php' ], 'migrations'); $this->publishes([ __DIR__.'/../resources/views' => base_path('resources/views/vendor'), ], 'views'); $this->registerBladeExtensions(); }
Bootstrap the application services. @return void
entailment
public function retrieve($address) { /** @var \Geo\Model\Entity\GeocodedAddress $entity */ $entity = $this->find()->where(['address' => $address])->first(); if ($entity) { return $entity; } $result = $this->_execute($address); $address = $this->newEntity([ 'address' => $address ]); if ($result) { $address->lat = $result->getLatitude(); $address->lng = $result->getLongitude(); $address->country = $result->getCountry()->getCode(); $formatter = new StringFormatter(); $address->formatted_address = $formatter->format($result, '%S %n, %z %L'); $address->data = $result; } return $this->save($address); }
@param string $address @return bool|\Geo\Model\Entity\GeocodedAddress
entailment
public function validationDefault(Validator $validator) { $validator ->integer('id') ->allowEmpty('id', 'create'); $validator ->requirePresence('address', 'create') ->notEmpty('address') ->add('address', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']); $validator ->allowEmpty('formatted_address'); $validator ->allowEmpty('country'); $validator ->decimal('lat') ->allowEmpty('lat'); $validator ->decimal('lng') ->allowEmpty('lng'); $validator ->allowEmpty('data'); return $validator; }
Default validation rules. @param \Cake\Validation\Validator $validator Validator instance. @return \Cake\Validation\Validator
entailment
protected function _execute($address) { $this->_Geocoder = new Geocoder(); try { $addresses = $this->_Geocoder->geocode($address); } catch (InconclusiveException $e) { return null; } catch (NotAccurateEnoughException $e) { return null; } if (!$addresses || $addresses->count() < 1) { return null; } $address = $addresses->first(); return $address; }
@param string $address @return \Geocoder\Model\Address|null
entailment
public function apiUrl(array $query = []) { $url = $this->_protocol() . static::API; if ($this->_runtimeConfig['map']['api']) { $query['v'] = $this->_runtimeConfig['map']['api']; } if ($this->_runtimeConfig['key']) { $query['key'] = $this->_runtimeConfig['key']; } if ($this->_runtimeConfig['language']) { $query['language'] = $this->_runtimeConfig['language']; } if ($query) { $query = http_build_query($query); $url .= '?' . $query; } return $url; }
JS maps.google API url. Options read via configs - key - api - language (iso2: en, de, ja, ...) You can adds more after the URL like "&key=value&..." via - query string array: additional query strings (e.g. callback for deferred execution - not supported yet by this helper) @param array $query @return string Full URL
entailment
public function reset($full = true) { static::$markerCount = static::$infoWindowCount = 0; $this->markers = $this->infoWindows = []; if ($full) { $this->_runtimeConfig = $this->_config; } }
Make it possible to include multiple maps per page resets markers, infoWindows etc @param bool $full true=optionsAsWell @return void
entailment
public function setControls(array $options = []) { if (isset($options['streetView'])) { $this->_runtimeConfig['map']['streetViewControl'] = $options['streetView']; } if (isset($options['zoom'])) { $this->_runtimeConfig['map']['scaleControl'] = $options['zoom']; } if (isset($options['scrollwheel'])) { $this->_runtimeConfig['map']['scrollwheel'] = $options['scrollwheel']; } if (isset($options['keyboardShortcuts'])) { $this->_runtimeConfig['map']['keyboardShortcuts'] = $options['keyboardShortcuts']; } if (isset($options['type'])) { $this->_runtimeConfig['map']['type'] = $options['type']; } }
Set the controls of current map Control options - zoom, scale, overview: TRUE/FALSE - map: FALSE, small, large - type: FALSE, normal, menu, hierarchical TIP: faster/shorter by using only the first character (e.g. "H" for "hierarchical") @param array $options @return void
entailment
public function map(array $options = []) { $this->reset(); $this->_runtimeConfig = Hash::merge($this->_runtimeConfig, $options); $this->_runtimeConfig['map'] = $options + $this->_runtimeConfig['map']; if (!isset($this->_runtimeConfig['map']['lat']) || !isset($this->_runtimeConfig['map']['lng'])) { $this->_runtimeConfig['map']['lat'] = $this->_runtimeConfig['map']['defaultLat']; $this->_runtimeConfig['map']['lng'] = $this->_runtimeConfig['map']['defaultLng']; } if (!isset($this->_runtimeConfig['map']['zoom'])) { $this->_runtimeConfig['map']['zoom'] = $this->_runtimeConfig['map']['defaultZoom']; } $result = ''; // autoinclude js? if ($this->_runtimeConfig['autoScript'] && !$this->_apiIncluded) { $res = $this->Html->script($this->apiUrl(), ['block' => $this->_runtimeConfig['block']]); $this->_apiIncluded = true; if (!$this->_runtimeConfig['block']) { $result .= $res . PHP_EOL; } // usually already included //http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js } // still not very common: http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/basics.html if (false && !empty($this->_runtimeConfig['autoScript']) && !$this->_gearsIncluded) { $res = $this->Html->script($this->gearsUrl(), ['block' => $this->_runtimeConfig['block']]); if (!$this->_runtimeConfig['block']) { $result .= $res . PHP_EOL; } } $map = " var initialLocation = " . $this->_initialLocation() . "; var browserSupportFlag = new Boolean(); var myOptions = " . $this->_mapOptions() . "; // deprecated gMarkers" . static::$mapCount . " = new Array(); gInfoWindows" . static::$mapCount . " = new Array(); gWindowContents" . static::$mapCount . " = new Array(); "; #rename "map_canvas" to "map_canvas1", ... if multiple maps on one page while (in_array($this->_runtimeConfig['div']['id'], $this->_mapIds)) { $this->_runtimeConfig['div']['id'] .= '-1'; //TODO: improve } $this->_mapIds[] = $this->_runtimeConfig['div']['id']; $map .= " var " . $this->name() . ' = new google.maps.Map(document.getElementById("' . $this->_runtimeConfig['div']['id'] . "\"), myOptions); "; $this->map = $map; $this->_runtimeConfig['div']['style'] = ''; if (is_numeric($this->_runtimeConfig['div']['width'])) { $this->_runtimeConfig['div']['width'] .= 'px'; } if (is_numeric($this->_runtimeConfig['div']['height'])) { $this->_runtimeConfig['div']['height'] .= 'px'; } $this->_runtimeConfig['div']['style'] .= 'width: ' . $this->_runtimeConfig['div']['width'] . ';'; $this->_runtimeConfig['div']['style'] .= 'height: ' . $this->_runtimeConfig['div']['height'] . ';'; unset($this->_runtimeConfig['div']['width']); unset($this->_runtimeConfig['div']['height']); $defaultText = isset($this->_runtimeConfig['content']) ? $this->_runtimeConfig['content'] : __('Map cannot be displayed!'); $result .= $this->Html->tag('div', $defaultText, $this->_runtimeConfig['div']); return $result; }
This the initialization point of the script Returns the div container you can echo on the website @param array $options associative array of settings are passed @return string divContainer
entailment
protected function _initialLocation() { if ($this->_runtimeConfig['map']['lat'] && $this->_runtimeConfig['map']['lng']) { return 'new google.maps.LatLng(' . $this->_runtimeConfig['map']['lat'] . ', ' . $this->_runtimeConfig['map']['lng'] . ')'; } $this->_runtimeConfig['autoCenter'] = true; return 'false'; }
Generate a new LatLng object with the current lat and lng. @return string
entailment
public function addMarker($options) { $defaults = $this->_runtimeConfig['marker']; if (isset($options['icon']) && is_array($options['icon'])) { $defaults = $options['icon'] + $defaults; unset($options['icon']); } $options += $defaults; $params = []; $params['map'] = $this->name(); if (isset($options['title'])) { $params['title'] = json_encode($options['title']); } if (isset($options['icon'])) { $params['icon'] = $options['icon']; if (is_int($params['icon'])) { $params['icon'] = 'gIcons' . static::$mapCount . '[' . $params['icon'] . ']'; } else { $params['icon'] = json_encode($params['icon']); } } if (isset($options['shadow'])) { $params['shadow'] = $options['shadow']; if (is_int($params['shadow'])) { $params['shadow'] = 'gIcons' . static::$mapCount . '[' . $params['shadow'] . ']'; } else { $params['shadow'] = json_encode($params['shadow']); } } if (isset($options['shape'])) { $params['shape'] = $options['shape']; } if (isset($options['zIndex'])) { $params['zIndex'] = $options['zIndex']; } if (isset($options['animation'])) { $params['animation'] = 'google.maps.Animation.' . strtoupper($options['animation']); } // geocode if necessary if (!isset($options['lat']) || !isset($options['lng'])) { $this->map .= " var geocoder = new google.maps.Geocoder(); function geocodeAddress(address) { geocoder.geocode({'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { x" . static::$markerCount . " = new google.maps.Marker({ position: results[0].geometry.location, " . $this->_toObjectParams($params, false, false) . " }); gMarkers" . static::$mapCount . " .push( x" . static::$markerCount . " ); return results[0].geometry.location; } else { //alert('Geocoding was not successful for the following reason: ' + status); return null; } }); }"; if (!isset($options['address'])) { throw new Exception('Either use lat/lng or address to add a marker'); } $position = 'geocodeAddress("' . h($options['address']) . '")'; } else { $position = 'new google.maps.LatLng(' . $options['lat'] . ',' . $options['lng'] . ')'; } $marker = " var x" . static::$markerCount . " = new google.maps.Marker({ position: " . $position . ", " . $this->_toObjectParams($params, false, false) . " }); gMarkers" . static::$mapCount . " .push( x" . static::$markerCount . " ); "; $this->map .= $marker; if (!empty($options['directions'])) { $options['content'] .= $this->_directions($options['directions'], $options); } // Fill popup windows if (!empty($options['content']) && $this->_runtimeConfig['infoWindow']['useMultiple']) { $x = $this->addInfoWindow(['content' => $options['content']]); $this->addEvent(static::$markerCount, $x, $options['open']); } elseif (!empty($options['content'])) { if (!isset($this->_runtimeConfig['marker']['infoWindow'])) { $this->_runtimeConfig['marker']['infoWindow'] = $this->addInfoWindow(); } $x = $this->addInfoContent($options['content']); $event = " gInfoWindows" . static::$mapCount . '[' . $this->_runtimeConfig['marker']['infoWindow'] . ']. setContent(gWindowContents' . static::$mapCount . '[' . $x . "]); gInfoWindows" . static::$mapCount . '[' . $this->_runtimeConfig['marker']['infoWindow'] . '].open(' . $this->name() . ', gMarkers' . static::$mapCount . '[' . $x . "]); "; $this->addCustomEvent(static::$markerCount, $event); if (!empty($options['open'])) { $this->addCustom($event); } } // Custom matching event? if (isset($options['id'])) { $this->matching[$options['id']] = static::$markerCount; } return static::$markerCount++; }
Add a marker to the map. Options: - lat and lng or address (to geocode on demand, not recommended, though) - title, content, icon, directions, maxWidth, open (optional) Note, that you can only set one marker to "open" for single window mode. If you declare multiple ones, the last one will be the one shown as open. @param array $options @return mixed Integer marker count or boolean false on failure @throws \Cake\Core\Exception\Exception
entailment
protected function _directions($directions, array $markerOptions = []) { $options = [ 'from' => null, 'to' => null, 'label' => __('Enter your address'), 'submit' => __('Get directions'), 'escape' => true, 'zoom' => null, // auto ]; if ($directions === true) { $options['to'] = $markerOptions['lat'] . ',' . $markerOptions['lng']; } elseif (is_array($directions)) { $options = $directions + $options; } if (empty($options['to']) && empty($options['from'])) { return ''; } $form = '<form action="https://maps.google.com/maps" method="get" target="_blank">'; $form .= $options['escape'] ? h($options['label']) : $options['label']; if (!empty($options['from'])) { $form .= '<input type="hidden" name="saddr" value="' . $options['from'] . '" />'; } else { $form .= '<input type="text" name="saddr" />'; } if (!empty($options['to'])) { $form .= '<input type="hidden" name="daddr" value="' . $options['to'] . '" />'; } else { $form .= '<input type="text" name="daddr" />'; } if (isset($options['zoom'])) { $form .= '<input type="hidden" name="z" value="' . $options['zoom'] . '" />'; } $form .= '<input type="submit" value="' . $options['submit'] . '" />'; $form .= '</form>'; return '<div class="directions">' . $form . '</div>'; }
Build directions form (type get) for directions inside infoWindows Options for directions (if array) - label - submit - escape: defaults to true @param mixed $directions - bool TRUE for autoDirections (using lat/lng) @param array $markerOptions - options array of marker for autoDirections etc (optional) @return string HTML
entailment
public function iconSet($color, $char = null, $size = 'm') { $colors = ['red', 'green', 'yellow', 'blue', 'purple', 'white', 'black']; if (!in_array($color, $colors)) { $color = 'red'; } if (!empty($this->_runtimeConfig['localImages'])) { $this->setIcons['color'] = $this->_runtimeConfig['localImages'] . 'marker%s.png'; $this->setIcons['alpha'] = $this->_runtimeConfig['localImages'] . 'marker%s%s.png'; $this->setIcons['numeric'] = $this->_runtimeConfig['localImages'] . '%s%s.png'; $this->setIcons['special'] = $this->_runtimeConfig['localImages'] . '%s.png'; } if (!empty($char)) { if ($color === 'red') { $color = ''; } else { $color = '_' . $color; } $url = sprintf($this->setIcons['alpha'], $color, $char); } else { if ($color === 'red') { $color = ''; } else { $color = '_' . $color; } $url = sprintf($this->setIcons['color'], $color); } /* var iconImage = new google.maps.MarkerImage('images/' + images[0] + ' .png', new google.maps.Size(iconData[images[0]].width, iconData[images[0]].height), new google.maps.Point(0,0), new google.maps.Point(0, 32) ); var iconShadow = new google.maps.MarkerImage('images/' + images[1] + ' .png', new google.maps.Size(iconData[images[1]].width, iconData[images[1]].height), new google.maps.Point(0,0), new google.maps.Point(0, 32) ); var iconShape = { coord: [1, 1, 1, 32, 32, 32, 32, 1], type: 'poly' }; */ $shadow = 'https://www.google.com/mapfiles/shadow50.png'; $res = [ 'url' => $url, 'icon' => $this->icon($url, ['size' => ['width' => 20, 'height' => 34]]), 'shadow' => $this->icon($shadow, ['size' => ['width' => 37, 'height' => 34], 'shadow' => ['width' => 10, 'height' => 34]]) ]; return $res; }
Get a custom icon set @param string $color Color: green, red, purple, ... or some special ones like "home", ... @param string|null $char Char: A...Z or 0...20/100 (defaults to none) @param string $size Size: s, m, l (defaults to medium) NOTE: for special ones only first parameter counts! @return array Array(icon, shadow, shape, ...)
entailment
public function addIcon($image, $shadow = null, array $imageOptions = [], array $shadowOptions = []) { $res = ['url' => $image]; $res['icon'] = $this->icon($image, $imageOptions); if ($shadow) { $last = $this->_iconRemember[$res['icon']]; if (!isset($shadowOptions['anchor'])) { $shadowOptions['anchor'] = []; } $shadowOptions['anchor'] = $last['options']['anchor'] + $shadowOptions['anchor']; $res['shadow'] = $this->icon($shadow, $shadowOptions); } return $res; }
Generate icon array. custom icon: http://thydzik.com/thydzikGoogleMap/markerlink.php?text=?&color=FFFFFF custom icons: http://code.google.com/p/google-maps-icons/wiki/NumericIcons#Lettered_Balloons_from_A_to_Z,_in_10_Colors custom shadows: http://www.cycloloco.com/shadowmaker/shadowmaker.htm @param string $image Image Url (http://...) @param string|null $shadow ShadowImage Url (http://...) @param array $imageOptions Image options @param array $shadowOptions Shadow image options @return array Resulting array
entailment
public function icon($url, array $options = []) { // The shadow image is larger in the horizontal dimension // while the position and offset are the same as for the main image. if (empty($options['size'])) { // We will deprecate this in the future maybe as this is super slow! //trigger_error('Please specify size manually [width => ..., height => ...] for performance reasons.', E_USER_DEPRECATED); $path = $url; if (!preg_match('#^((https?://)|//)#i', $path)) { // This should also be avoided but is still way faster than the URL lookup. $path = WWW_ROOT . ltrim($url, '/'); } $data = getimagesize($path); if ($data) { $options['size']['width'] = $data[0]; $options['size']['height'] = $data[1]; } else { $options['size']['width'] = $options['size']['height'] = 0; } } if (empty($options['anchor'])) { $options['anchor']['width'] = (int)($options['size']['width'] / 2); $options['anchor']['height'] = $options['size']['height']; } if (empty($options['origin'])) { $options['origin']['width'] = $options['origin']['height'] = 0; } if (isset($options['shadow'])) { $options['anchor'] = $options['shadow']; } $icon = 'new google.maps.MarkerImage("' . $url . '", new google.maps.Size(' . $options['size']['width'] . ', ' . $options['size']['height'] . '), new google.maps.Point(' . $options['origin']['width'] . ', ' . $options['origin']['height'] . '), new google.maps.Point(' . $options['anchor']['width'] . ', ' . $options['anchor']['height'] . ') )'; $this->icons[static::$iconCount] = $icon; $this->_iconRemember[static::$iconCount] = ['url' => $url, 'options' => $options, 'id' => static::$iconCount]; return static::$iconCount++; }
Generate icon object @param string $url (required) @param array $options (optional): - size: array(width=>x, height=>y) - origin: array(width=>x, height=>y) - anchor: array(width=>x, height=>y) @return int Icon count
entailment
public function addInfoWindow(array $options = []) { $defaults = $this->_runtimeConfig['infoWindow']; $options += $defaults; if (!empty($options['lat']) && !empty($options['lng'])) { $position = 'new google.maps.LatLng(' . $options['lat'] . ', ' . $options['lng'] . ')'; } else { $position = ' ' . $this->name() . ' .getCenter()'; } $windows = " gInfoWindows" . static::$mapCount . ".push(new google.maps.InfoWindow({ position: {$position}, content: " . $this->escapeString($options['content']) . ", maxWidth: {$options['maxWidth']}, pixelOffset: {$options['pixelOffset']} /*zIndex: {$options['zIndex']},*/ })); "; $this->map .= $windows; return static::$infoWindowCount++; }
Creates a new InfoWindow. @param array $options - lat, lng, content, maxWidth, pixelOffset, zIndex @return int windowCount
entailment
public function addEvent($marker, $infoWindow, $open = false) { $this->map .= " google.maps.event.addListener(gMarkers" . static::$mapCount . "[{$marker}], 'click', function() { gInfoWindows" . static::$mapCount . "[$infoWindow].open(" . $this->name() . ", this); }); "; if ($open) { $event = 'gInfoWindows' . static::$mapCount . "[$infoWindow].open(" . $this->name() . ', gMarkers' . static::$mapCount . '[' . $marker . ']);'; $this->addCustom($event); } }
Add event to open marker on click. @param int $marker @param int $infoWindow @param bool $open Also open it right away. @return void
entailment
public function addDirections($from, $to, array $options = []) { $id = 'd' . static::$markerCount++; $defaults = $this->_runtimeConfig['directions']; $options += $defaults; $travelMode = $this->travelModes[$options['travelMode']]; $directions = " var {$id}Service = new google.maps.DirectionsService(); var {$id}Display; {$id}Display = new google.maps.DirectionsRenderer(); {$id}Display. setMap(" . $this->name() . "); "; if (!empty($options['directionsDiv'])) { $directions .= "{$id}Display. setPanel(document.getElementById('" . $options['directionsDiv'] . "'));"; } if (is_array($from)) { $from = 'new google.maps.LatLng(' . (float)$from['lat'] . ', ' . (float)$from['lng'] . ')'; } else { $from = '"' . h($from) . '"'; } if (is_array($to)) { $to = 'new google.maps.LatLng(' . (float)$to['lat'] . ', ' . (float)$to['lng'] . ')'; } else { $to = '"' . h($to) . '"'; } $directions .= " var request = { origin: $from, destination: $to, unitSystem: google.maps.UnitSystem." . $options['unitSystem'] . ", travelMode: google.maps.TravelMode. $travelMode }; {$id}Service.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { {$id}Display. setDirections(result); } }); "; $this->map .= $directions; }
Add directions to the map. @param array|string $from Location as array(fixed lat/lng pair) or string (to be geocoded at runtime) @param array|string $to Location as array(fixed lat/lng pair) or string (to be geocoded at runtime) @param array $options - directionsDiv: Div to place directions in text form - travelMode: TravelMode, - transitOptions: TransitOptions, - unitSystem: UnitSystem (IMPERIAL, METRIC, AUTO), - waypoints[]: DirectionsWaypoint, - optimizeWaypoints: Boolean, - provideRouteAlternatives: Boolean, - avoidHighways: Boolean, - avoidTolls: Boolean - region: String @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRequest @return void
entailment
public function addPolyline($from, $to, array $options = []) { if (is_array($from)) { $from = 'new google.maps.LatLng(' . (float)$from['lat'] . ', ' . (float)$from['lng'] . ')'; } else { throw new Exception('not implemented yet, use array of lat/lng'); //$from = '\'' . h($from) . '\''; } if (is_array($to)) { $to = 'new google.maps.LatLng(' . (float)$to['lat'] . ', ' . (float)$to['lng'] . ')'; } else { throw new Exception('not implemented yet, use array of lat/lng'); //$to = '\'' . h($to) . '\''; } $defaults = $this->_runtimeConfig['polyline']; $options += $defaults; $id = 'p' . static::$markerCount++; $polyline = "var start = $from;"; $polyline .= "var end = $to;"; $polyline .= " var poly = [ start, end ]; var {$id}Polyline = new google.maps.Polyline({ path: poly, strokeColor: '" . $options['color'] . "', strokeOpacity: " . $options['opacity'] . ", strokeWeight: " . $options['weight'] . " }); {$id}Polyline.setMap(" . $this->name() . "); "; $this->map .= $polyline; }
Add a polyline This method adds a line between 2 points @param array|string $from Location as array(fixed lat/lng pair) or string (to be geocoded at runtime) @param array|string $to Location as array(fixed lat/lng pair) or string (to be geocoded at runtime) @param array $options - color (#FFFFFF ... #000000) - opacity (0.1 ... 1, defaults to 1) - weight in pixels (defaults to 2) @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline @return void
entailment
public function finalize($return = false) { $script = $this->_arrayToObject('matching', $this->matching, false, true) . PHP_EOL; $script .= $this->_arrayToObject('gIcons' . static::$mapCount, $this->icons, false, false) . ' jQuery(document).ready(function() { '; $script .= $this->map; if ($this->_runtimeConfig['geolocate']) { $script .= $this->_geolocate(); } if ($this->_runtimeConfig['showMarker'] && !empty($this->markers) && is_array($this->markers)) { $script .= implode($this->markers, ' '); } if ($this->_runtimeConfig['autoCenter']) { $script .= $this->_autoCenter(); } $script .= ' });'; static::$mapCount++; if ($return) { return $script; } $this->Html->scriptBlock($script, ['block' => true]); }
Finalize the map and write the javascript to the buffer. Make sure that your view does also output the buffer at some place! @param bool $return If the output should be returned instead @return null|string Javascript if $return is true
entailment
public function geolocateCallback($js) { if ($js === false) { $this->_runtimeConfig['callbacks']['geolocate'] = false; return; } $this->_runtimeConfig['callbacks']['geolocate'] = $js; }
Set a custom geolocate callback @param string|bool $js Custom JS false: no callback at all @return void
entailment
public function mapLink($title, $mapOptions = [], $linkOptions = []) { return $this->Html->link($title, $this->mapUrl($mapOptions + ['escape' => false]), $linkOptions); }
Returns a maps.google link @param string $title Link title @param array $mapOptions @param array $linkOptions @return string HTML link
entailment
public function mapUrl(array $options = []) { $url = $this->_protocol() . 'maps.google.com/maps?'; $urlArray = !empty($options['query']) ? $options['query'] : []; if (!empty($options['from'])) { $urlArray['saddr'] = $options['from']; } if (!empty($options['to']) && is_array($options['to'])) { $to = array_shift($options['to']); foreach ($options['to'] as $key => $value) { $to .= '+to:' . $value; } $urlArray['daddr'] = $to; } elseif (!empty($options['to'])) { $urlArray['daddr'] = $options['to']; } if (isset($options['zoom']) && $options['zoom'] !== false) { $urlArray['z'] = (int)$options['zoom']; } //$urlArray[] = 'f=d'; //$urlArray[] = 'hl=de'; //$urlArray[] = 'ie=UTF8'; $options += [ 'escape' => true, ]; $query = http_build_query($urlArray); if ($options['escape']) { $query = h($query); } return $url . $query; }
Returns a maps.google url Options: - from: necessary (address or lat,lng) - to: 1x necessary (address or lat,lng - can be an array of multiple destinations: array('dest1', 'dest2')) - zoom: optional (defaults to none) - query: Additional query strings as array - escape: defaults to true @param array $options Options @return string link: http://...
entailment
public function staticMap(array $options = [], array $attributes = []) { $defaultAttributes = ['alt' => __d('tools', 'Map')]; $attributes += $defaultAttributes; // This was fixed in 3.5.1 to auto-escape URL query strings for security reasons $escape = version_compare(Configure::version(), '3.5.1') < 0 ? true : false; return $this->Html->image($this->staticMapUrl($options + ['escape' => $escape]), $attributes); }
Creates a plain image map. @link http://code.google.com/intl/de-DE/apis/maps/documentation/staticmaps @param array $options Options - string $size [necessary: VALxVAL, e.g. 500x400 - max 640x640] - string $center: x,y or address [necessary, if no markers are given; else tries to take defaults if available] or TRUE/FALSE - int $zoom [optional; if no markers are given, default value is used; if set to "auto" and ]* - array $markers [optional, @see staticPaths() method] - string $type [optional: roadmap/hybrid, ...; default:roadmap] - string $mobile TRUE/FALSE - string $visible: $area (x|y|...) - array $paths [optional, @see staticPaths() method] - string $language [optional] @param array $attributes HTML attributes for the image - title - alt (defaults to 'Map') - url (tip: you can pass $this->link(...) and it will create a link to maps.google.com) @return string imageTag
entailment
public function staticMapLink($title, array $mapOptions = [], array $linkOptions = []) { return $this->Html->link($title, $this->staticMapUrl($mapOptions + ['escape' => false]), $linkOptions); }
Create a link to a plain image map @param string $title Link title @param array $mapOptions @param array $linkOptions @return string HTML link
entailment