Untitled

 avatar
unknown
plain_text
a year ago
6.4 kB
5
Indexable
Please check and fix the below warning in drupal 9.

Warning: Undefined array key "theme_id" in Drupal\hearsay_preview\Plugin\rest\resource\PostPreview->post() (line 138 of /code/web/modules/custom/hearsay_preview/src/Plugin/rest/resource/PostPreview.php)

<?php

namespace Drupal\hearsay_preview\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Psr\Log\LoggerInterface;
use Drupal\hearsay_automation_process\HSUtilityService;
use Drupal\hearsay_client_customization\Controller\HearsayClientCustomization;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\rest\ModifiedResourceResponse;

/**
 * Annotation for post method.
 *
 * @RestResource(
 *   id = "hs_preview_data_post",
 *   label = @Translation("HS Site changes preview"),
 *   serialization_class = "",
 *   uri_paths = {
 *     "create" = "/api/preview"
 *   }
 * )
 */
class PostPreview extends ResourceBase
{
    /**
     * Responds to POST requests.
     *
     * @return \Drupal\rest\ModifiedResourceResponse
     *   The response will be token verification status.
     */

    /**
     * A Service Instance.
     *
     * @var \Drupal\hearsay_automation_process\HSUtilityService
     */
    protected $HSUtilityService;

    /**
     * A Client Customization Instance.
     *
     * @var Drupal\hearsay_client_customization\Controller\HearsayClientCustomization
     */
    protected $HSClientCustomization;

    /**
     * Constructs a Drupal\rest\Plugin\ResourceBase 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\hearsay_automation_process\HSUtilityService $utilityObject
     *   A HS utility service instance.
     */
    public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        array $serializer_formats,
        LoggerInterface $logger,
        HSUtilityService $utilityObject
    ) {
        parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger, $utilityObject);
        $this->HSUtilityService = $utilityObject;
        $this->HSClientCustomization = new HearsayClientCustomization();
    }

    /**
     * {@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('custom_rest'),
            $container->get('hearsay_automation_process_service.utility')

        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getEditableConfigNames()
    {
        return ['hearsay_preview.slug'];
    }

    /**
     * Responds to POST requests.
     *
     * @return \Drupal\
     *   Saves the preview configuration
     *   Returns a list of bundles for specified entity.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post($data)
    {
        $previewToken = PREVIEW_TOKEN;
        if (!isset($data)) {
            $responseStatus['status'] = false;
        } else {
            $headers = getallheaders();
            $xPreviewToken = $headers['X-Preview-Token'];
            $baseSlug = $data['slug'];
            $slug = $this->HSUtilityService->getBaseSlugByUrl($baseSlug);

            // Verify token.
            if ($xPreviewToken != $previewToken) {
                \Drupal::logger('sites_preview')->notice('Received bad token for new preview request for "' . $slug);
                $responseStatus['status'] = 401;
                $responseStatus['error_message'] = 'Received bad token for new preview request for "' . $slug;
                return new ModifiedResourceResponse(401);
            }

            // Log start of job.
            \Drupal::logger('sites_preview')->notice('Receiving new preview request for: " ' . $slug . '". <br> Returned new path successfully');

            // Set created and expiration values.
            $data['config_created'] = time();
            $data['config_expiration'] = time() + 600;

            try {
                $config = \Drupal::configFactory()->getEditable('sites_preview.api');
                $language = $this->HSClientCustomization->getLanguageByThemeID($data['theme_id']);
                $langCode = $this->HSClientCustomization->getLanguageAbbreviation($language);
                // Final slug to save config data with language suffix.
                $finalSlug = $slug . '_' . $langCode;
                $config->set($finalSlug, $data)->save();
                $previewPath = $this->HSClientCustomization->getPostPreviewPath($slug, $langCode);
                $responseStatus['preview_path'] = $previewPath;
            } catch (\Exception $e) {
                \Drupal::logger('Sites Preview post error')->error($e->getMessage() . ' <br> — Slug ' . $slug);
            }
        }
        return new ModifiedResourceResponse($responseStatus);
    }

    /**
     * Open access (using auth token check).
     *
     * @return void
     *   Return Null.
     */
    public function permissions()
    {
        return [];
    }
}


/**
     * Get Language by Theme ID.
     *
     * @param int $themeId
     *   Theme Id.
     *
     * @return string
     *   Return theme language.
     */
    public function getLanguageByThemeID($themeId)
    {
        $config = \Drupal::config(HS_PLATFORM_SETTINGS);
        $languages = HS_LANGUAGES;
        $themeLanguage = '';
        foreach ($languages as $key => $language) {
            $getThemeIds = $config->get('theme_id_' . strtolower($key));
            $arrThemeIds = explode(",", $getThemeIds);
            if (in_array($themeId, $arrThemeIds)) {
                $themeLanguage = $language;
                return $themeLanguage;
            }
        }
        return $themeLanguage;
    }
Editor is loading...
Leave a Comment