将模块Drupal7转换为Drupal8

时间:2019-09-07 09:38:50

标签: php drupal-7 drupal-8

我想将drupal7模块转换为drupal8。我知道drupal8是面向对象的,但是我的代码中仍然存在一些问题。

我在oop中编写了代码,但是无法正常运行,并且在运行代码时显示错误,未定义函数。我模块的功能是重定向根目录中的文件夹。 会有所帮助。

<?php

namespace Drupal\afridi\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\Form\FormValidatorInterface;
use \Drupal\Core\Form\FormSubmitterInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultForm.
 */
class DefaultForm extends FormBase {
// public function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL);
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'default_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form = array();

    $form['files_autoredirect']['title'] = array(
      '#markup' => t('<h2>Folder Redirect</h2><p>Before moving the media folder from old location to new location, add the folder path & destination path in order to automatically generate <b>301 redirect</b> for all the files in folder. Once the redirects are generated, move the folder from the old location to the new location & verify by visiting old url if it redirects correctly to the new file location.</p>'),
    );
    $form['afridi']['scan_folder'] = array(
      '#type' => 'textfield',
      '#title' => t('Folder to scan'),
      '#default_value' => !empty(\Drupal::state()->get('afridi_scan_folder')) ?  \Drupal::state()->get('afridi_scan_folder') : '',
      '#size' => 60,
      '#maxlength' => 128,
      '#description' => t('This folder must exsist & accessible under the path so all the files inside can be scanned and a redirect rule is added for each file.<br>Example: For <b>root/content</b> folder add <b>content</b>.'),
      '#required' => TRUE,
    );

    $form['afridi']['check'] = array(
      '#title' => t("Same as folder path"),
      '#type' => 'checkbox',
      '#default_value' => !empty(\Drupal::state()->get('afridi_check')) ? \Drupal::state()->get('afridi_check') : '',
      '#description' => t('Uncheck if the <b>redirect from</b> path is different.'),
      '#ajax' => array(
        'callback' => 'testprb_ajaxtest',
        'wrapper' => 'testprb_replace_field_div',
      ),
    );

    $form['afridi']['path_check'] = array(
      '#type' => 'container',
      '#states' => array(
        "visible" => array(
          "input[name='check']" => array("checked" => FALSE),
        ),
      ),
    );
    $form['afridi']['path_check']['path_from'] = array(
      '#type' => 'textfield',
      '#title' => t('Redirect from path'),
      '#default_value' => !empty(\Drupal::state()->get('afridi_from')) ? \Drupal::state()->get('afridi_from') : '',
      '#size' => 60,
      '#maxlength' => 128,
      '#description' => t('Example: For <b>root/content</b> folder add <b>content</b>. If left blank scanned folder will be chosen as base path.'),
    );
    $form['afridi']['path_to'] = array(
      '#type' => 'textfield',
      '#title' => t('Redirect to path'),
      '#default_value' => !empty(\Drupal::state()->get('afridi_to')) ? \Drupal::state()->get('afridi_to') : '',

      '#size' => 60,
      '#maxlength' => 128,
      '#description' => t('Example: <b>sites/default/files/</b> for <b>root/sites/default/files</b> folder. Trailing slash must be provided.'),
      '#required' => TRUE,
    );

    $form['afridi']['exception'] = array(
      '#title' => t('Exceptions'),
      '#type' => 'textarea',
      '#description' => t('Exception rules, files or directories added in the list will be ignored. Add one entry per row.'),
       '#default_value' => !empty(\Drupal::state()->get('afridi_exceptions')) ? implode(\Drupal::state()->get('afridi_exceptions')) : implode(PHP_EOL, array(
         '. ',
         '.. ',
         '.DS_Store ',
       )),

    );

    $form['submit'][] = array(
      '#type' => 'submit',
      '#value' => t('Generate Redirects'),
    );

    return $form;

  }

  /**
   * {@inheritdoc}
   */

function submitForm(array &$form, FormStateInterface $form_state) {
         if ($form_state->hasValue(array('exception'))) {
         $exceptions = explode(PHP_EOL, trim($form_state->getValues('exception')));
         \Drupal::state()->set('folder_redirect_exceptions', $exceptions);
       }
       \Drupal::state()->set('folder_redirect_check', $form_state->getValues('check'));
       \Drupal::state()->set('folder_redirect_scan_folder', $form_state->getValues('scan_folder'));
       \Drupal::state()->set('folder_redirect_from', $form_state->getValues('path_from'));
       \Drupal::state()->set('folder_redirect_to', $form_state->getValues('path_to'));

      if (!empty(\Drupal::state()->get('folder_redirect_scan_folder', '')) && !empty(\Drupal::state()->get('folder_redirect_to'))) {
        if (\Drupal::state()->get('folder_redirect_check','')) {
          \Drupal::state()->delete('folder_redirect_from');
          if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {

            drupal_set_message(t('Url redirects generated, <a href=" @base-url ">Redirects List</a>', array('@base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
          }
          else {
            drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => \Drupal::state()->get('folder_redirect_scan_folder') )), 'error', TRUE);

          }
        }
        else {

          if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_from', ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''), \Drupal::state()->get('folder_redirect_scan_folder','')))
          {
            drupal_set_message(t('Url redirects generated, <a href=" @base-url ">Redirects List</a>', array('@base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
          }
          else {
            drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => variable_get('folder_redirect_scan_folder'))), 'error', TRUE);
          }
        }
      }

      else {
        drupal_set_message(t('Invalid configurations, please try again'), 'error', TRUE);
      }
    }


    /**
     * Helper function to set important variables.
     */

     function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL) {
        $root = DRUPAL_ROOT . "/";
        $root_preg = preg_replace("/([\/]+)/", "\\/", $root);
        $path_from_preg = preg_replace("/([\/]+)/", "\\/", $path);
        if ($folder_scan) {
          $scan_folder = $root . $folder_scan;
          if (is_dir($scan_folder)) {
            afridi_list_all_files($scan_folder, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $path);
            return TRUE;
          }
          else {
            return FALSE;
          }
        }
        else {
          $path = $root . $path;
          if (is_dir($path)) {
            afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions);
            return TRUE;
          }
          else {
            return FALSE;
          }
        }
      }
          /**
           * Helper function to scan the dir and its sub-dir.
           */
           function afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from = '') {
            if (!isset($redirects)) {
              $redirects = array();
            }
            $files = array_diff(scandir($path), array_map('trim', $exceptions));
            foreach ($files as $file) {
              if (is_dir($path . "/{$file}")) {
                if (!empty($different_path_from)) {
                  afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from);
                }
                else {
                  afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions);
                }
              }
              else {
                if (!empty($different_path_from)) {
                  preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
                  preg_match("/([a-zA-Z0-9-_]+)([\/])([.a-zA-Z0-9-_\/]+)/", $out[1], $out1);
                  $redirect_from = $different_path_from . '/' . $out1[3];
                  $redirect_to = $path_to . $out1[3];;
                }
                else {
                  preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
                  $redirect_from = $out[1];
                  preg_match("/" . $path_from_preg . "\/(...+)/", $redirect_from, $out1);
                  $redirect_to = $path_to . $out1[1];
                }
                $redirects[$redirect_from] = $redirect_to;
              }
            }
              afridi_import_redirects($redirects);
          }

          /**
           * Helper function to import redirects.
           */
        function afridi_import_redirect($redirect_from, $redirect_to) {
            $redirect = new stdClass();
            module_invoke(
              'redirect',
              'object_prepare',
              $redirect,
              array(
                'source' => $redirect_from,
                'source_options' => array(),
                'redirect' => $redirect_to,
                'redirect_options' => array(),
                'language' => LANGUAGE_NONE,
              )
            );
            module_invoke('redirect', 'save', $redirect);
          }

          /**
           * Helper function to import bulk redirects.
           */
       function afridi_import_redirects($redirects) {
            foreach ($redirects as $from_url => $to_url) {
              if (!redirect_load_by_source($from_url)) {
                $redirect = new stdClass();
                redirect_object_prepare(
                  $redirect,
                  array(
                    'source' => $from_url,
                    'source_options' => array(),
                    'redirect' => $to_url,
                    'redirect_options' => array(),
                    'language' => LANGUAGE_NONE,
                  )
                );
                redirect_save($redirect);
              }
              else {
                drupal_set_message(t('Redirect already exsists for path<i> "@path" </i>', array('@path' => $from_url)), 'warning', TRUE);
              }
            }
          }

    }

我想在本节中重定向文件夹路径,但是存在一些问题。显示功能未定义的错误。

1 个答案:

答案 0 :(得分:1)

在PHP中,方法调用始终需要提供对象实例($this)或类名(如果它是static method call)。因此,对于您的情况,您不能直接调用afridi_trigger_import_redirectsafridi_list_all_files,因为它们是普通函数。

快速解决方案是使用$this实例调用它们。例如,这:

          if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {

            drupal_set_message(t('Url redirects generated, <a href=" @base-url ">Redirects List</a>', array('@base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
          }

应重写为:

          if ($this->afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {

            drupal_set_message(t('Url redirects generated, <a href=" @base-url ">Redirects List</a>', array('@base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
          }

一种更优雅的方法是将所有不引用实例属性的方法重写为静态方法。例如,这:

          function ($path, $path_to, $exceptions, $folder_scan = NULL) {

应这样重写:

          public static function ($path, $path_to, $exceptions, $folder_scan = NULL) {

所有afridi_trigger_import_redirects调用都应以DefaultForm::afridi_trigger_import_redirects格式重写。