handled home loading if not available in dom (if drupalSettings.path.isFront == false)

This commit is contained in:
2019-06-04 22:38:44 +02:00
parent d8e5f93c14
commit 082e011fbb
22 changed files with 591 additions and 160 deletions

View File

@@ -1,23 +1,7 @@
# materio_home.home:
# path: '/home'
# defaults:
# _controller: '\Drupal\materio_home\Controller\HomeController::home'
# _title: 'Home'
# requirements:
# _permission: 'access content'
# materio_home.home_mobile:
# path: '/home_m'
# defaults:
# _controller: '\Drupal\materio_home\Controller\HomeController::home_mobile'
# _title: 'Home'
# requirements:
# _permission: 'access content'
#
# materio_home.home_mobileajax:
# path: '/home_m/ajax'
# defaults:
# _controller: '\Drupal\materio_home\Controller\HomeController::home_mobilejson'
# _title: 'Home'
# requirements:
# _permission: 'access content'
materio_home.ajax_home:
path: 'materio_home/ajax/gethome'
defaults:
_controller: '\Drupal\materio_home\Controller\AjaxHomeController::getHome'
_title: 'ajaxGetHome'
requirements:
_permission: 'access content'

View File

@@ -0,0 +1,106 @@
<?php
namespace Drupal\materio_home\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Url;
use Drupal\core\render\RenderContext;
/**
* Class AjaxHomeController.
*/
class AjaxHomeController extends ControllerBase {
/**
* Drupal\Core\Entity\EntityManagerInterface definition.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Drupal\language\ConfigurableLanguageManagerInterface definition.
*
* @var \Drupal\language\ConfigurableLanguageManagerInterface
*/
protected $languageManager;
/**
* Drupal\Core\Render\RendererInterface definition.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Drupal\Core\Render\RendererInterface definition.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new AjaxHomeController object.
*/
public function __construct(EntityManagerInterface $entity_manager, ConfigurableLanguageManagerInterface $language_manager, RendererInterface $renderer, EntityTypeManagerInterface $entity_type_manager) {
$this->entityManager = $entity_manager;
$this->languageManager = $language_manager;
$this->renderer = $renderer;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('language_manager'),
$container->get('renderer'),
$container->get('entity_type.manager')
);
}
/**
* Hello.
*
* @return string
* Return Hello string.
*/
public function getHome() {
$path = \Drupal::config('system.site')->get('page.front');
$params = Url::fromUri("internal:" . $path)->getRouteParameters();
$entity_type = key($params);
$entity = $this->entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
$view_builder = $this->entityTypeManager()->getViewBuilder('node');
$renderable = $view_builder->view($entity, 'default');
$rendered = $this->renderer->executeInRenderContext(new RenderContext(), function () use ($renderable) {
return render($renderable);
});
$data['rendered'] = $rendered;
$data['#cache'] = [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => ['edlp-home-cache'],
'contexts' => [
'languages:language_content'
]
];
// $response = new JsonResponse();
// $response->setData($data);
$response = new CacheableJsonResponse($data);
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
return $response;
}
}

View File

@@ -30,9 +30,9 @@ materio_sapi.getresults:
requirements:
_permission: 'access materio search'
# materio_sapi.base:
# path: '/base/{keys}/{autocomplete}'
# defaults:
# _controller: '\Drupal\materio_sapi\Controller\Base::base'
# requirements:
# _permission: 'access materio search'
materio_sapi.base:
path: '/base'
defaults:
_controller: '\Drupal\materio_sapi\Controller\Base::pageHandler'
requirements:
_permission: 'access materio search'

View File

@@ -1,5 +1,4 @@
<?php
// https://www.qed42.com/blog/autocomplete-drupal-8
// https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code
namespace Drupal\materio_sapi\Controller;
@@ -14,73 +13,88 @@ use Drupal\search_api\Entity\Index;
// https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
/**
* Defines a route controller for entity autocomplete form elements.
* Defines a route controller for materio sapi search (regular and ajax).
*/
class Base extends ControllerBase {
private $limit = 15;
private $offset = 0;
private function sapiQuery(){
$this->index = Index::load('database');
$this->query = $this->index->query();
// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
->createInstance('direct');
$parse_mode->setConjunction('OR');
$this->query->setParseMode($parse_mode);
// Set fulltext search keywords and fields.
$this->query->keys($this->keys);
// $this->query->setFulltextFields(['name']);
// Set additional conditions.
// $this->query->addCondition('status', 1)
// ->addCondition('author', 1, '<>');
// Restrict the search to specific languages.
// $this->query->setLanguages(['de', 'it']);
// Do paging.
$this->query->range($this->offset, $this->limit);
// Add sorting.
$this->query->sort('search_api_relevance', 'DESC');
// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$this->query->addTag('materio_sapi_search');
$this->results = $this->query->execute();
}
/**
* Handler for autocomplete request.
* get params from request
*/
private function parseRequest(Request $request){
// Get the typed string from the URL, if it exists.
$this->keys = $request->query->get('keys');
if($this->keys){
$this->keys = Unicode::strtolower($this->keys);
// $this->keys = Tags::explode($this->keys);
\Drupal::logger('materio_sapi')->notice($this->keys);
}
$this->term = $request->query->get('term');
$this->offset = $request->query->get('offset') ?? $this->offset;
$this->limit = $request->query->get('limit') ?? $this->limit;
}
/**
* Handler for ajax search.
*/
public function getResults(Request $request) {
$this->parseRequest($request);
$resp = [
'tes' => 'ok',
'autocomplete' => $request->query->get('autocomplete'),
'keys' => $request->query->get('keys'),
'keys' => $this->keys,
'term' => $this->term,
'range' => array(
'offset' => $request->query->get('offset'),
'limit' => $request->query->get('limit'),
'offset' => $this->offset,
'limit' => $this->limit
),
];
// Get the typed string from the URL, if it exists.
if ($keys = $resp['keys']) {
$typed_string = Tags::explode($keys);
$typed_string = Unicode::strtolower($keys);
\Drupal::logger('materio_sapi')->notice($typed_string);
$index = Index::load('database');
$query = $index->query();
// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);
// Set fulltext search keywords and fields.
$query->keys($typed_string);
// $query->setFulltextFields(['name']);
// Set additional conditions.
// $query->addCondition('status', 1)
// ->addCondition('author', 1, '<>');
// Restrict the search to specific languages.
// $query->setLanguages(['de', 'it']);
// Do paging.
$query->range($resp['range']['offset'], $resp['range']['limit']);
// Add sorting.
$query->sort('search_api_relevance', 'DESC');
// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('materio_sapi_search');
$results = $query->execute();
$resultitems = $results->getResultItems();
$resp['count'] = $results->getResultCount();
$resp['resultitems'] = array_keys($resultitems);
$resp['options'] = $query->getOptions();
if ($this->keys) {
$this->sapiQuery();
$resp['count'] = $this->results->getResultCount();
$resp['options'] = $this->query->getOptions();
$items = [];
foreach ($results as $result) {
// \Drupal::logger('materio_sapi')->notice(print_r($result->getField('tid')->getValues(),true));
// \Drupal::logger('materio_sapi')->notice(print_r($result->getField('name')->getValues(),true));
foreach ($this->results as $result) {
$nid = $result->getField('nid')->getValues()[0];
$title = $result->getField('title')->getValues()[0]->getText();
$items[] = [
@@ -94,4 +108,50 @@ class Base extends ControllerBase {
return new JsonResponse($resp);
}
/**
* Handler for regular page search.
*/
function pageHandler(Request $request){
// \Drupal::logger('materio_sapi')->notice(print_r($request, true));
$this->parseRequest($request);
$resp = [
"#title" => 'Base'
];
if ($this->keys) {
$resp['#title'] = $this->keys;
$this->sapiQuery();
$node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$items = $this->results->getResultItems();
$this->items = [];
foreach ($items as $item) {
try {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $item->getOriginalObject()->getValue();
}
catch (SearchApiException $e) {
continue;
}
if (!$entity) {
continue;
}
// TODO: define dynamicly viewmode
$this->items[] = $node_view_builder->view($entity, 'teaser');
}
$resp['items'] = $this->items;
}else{
$resp['#markup'] = "no keys to search for";
}
return $resp;
}
}

View File

@@ -32,7 +32,7 @@ class MaterioSapiSearchForm extends FormBase {
"placeholder" => $this->t('Search'),
// "@keyup" => "keyup",
"@keyup.enter" => "submit",
"v-model" => "keys",
"v-model" => "typed",
// "v-on:select" => "typed",
],
'#autocomplete_route_name' => 'materio_sapi.search_autocomplete',

View File

@@ -0,0 +1,7 @@
name: 'REST Config'
type: module
description: 'Get site configiration through rest api'
core: 8.x
package: 'Custom'
dependencies:
- rest

View File

@@ -0,0 +1,24 @@
<?php
/**
* @file
* Contains rest_config.module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function rest_config_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the rest_config module.
case 'help.page.rest_config':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Get site configiration through rest api') . '</p>';
return $output;
default:
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Drupal\rest_config\Plugin\rest\resource;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* Provides a resource to get configurations values.
*
* @RestResource(
* id = "config_rest_resource",
* label = @Translation("Config rest resource"),
* uri_paths = {
* "canonical" = "/config/{file}/{key}"
* }
* )
*/
class ConfigRestResource extends ResourceBase {
/**
* A current user instance.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* Constructs a new ConfigRestResource object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* A current user instance.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
AccountProxyInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('rest_config'),
$container->get('current_user')
);
}
/**
* Responds to GET requests.
*
* @return \Drupal\rest\ResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* Throws exception expected.
*/
public function get($file = null, $key = null) {
// You must to implement the logic of your REST Resource here.
// Use current user after pass authentication to validate access.
if (!$this->currentUser->hasPermission('access content')) {
throw new AccessDeniedHttpException();
}
$data = [];
if($file && $key){
$config = \Drupal::config($file);
if($config){
$value = $config->get($key);
$data[$key] = $value;
}
}
$response = new ResourceResponse($data, 200);
$response->addCacheableDependency($data);
return $response;
}
}