Можно ли отладить этот PHP - PullRequest
       22

Можно ли отладить этот PHP

0 голосов
/ 26 сентября 2018

Я действительно хватаюсь за соломинку здесь.Я не пишу код, и мое почтовое расширение PHP прекрасно работает, КРОМЕ этих ошибок при редактировании шаблонов.Мой продавец в том, кто знает, какой часовой пояс, и очень не отвечает.Помимо очевидного - смена расширений, смена поставщиков и т. Д. Любой из вас, PHP, может взглянуть на этот блок кода и сказать мне, что не так.Я не знаю, если вырваться из контекста, это будет иметь смысл.Ошибки - это PHP-уведомление. Попытка получить свойство необъекта, начинающегося со строки 1344. Вот блок кода с 1344 по 1370. Это, очевидно, связано с переключением на обычный текст, когда HTML не поддерживается.ОПЯТЬ, хватаясь за соломинку здесь, но stackoverflow довольно солидный, когда дело доходит до знающих людей.

Я заново вставляю код, чтобы включить более полный блок.Я также добавил комментарии в строках, чтобы указать, где появляются четыре предупреждения.Они выглядят так: // СЛЕДУЮЩАЯ ЛИНИЯ - ОШИБКА ОДНА - ЛИНИЯ 1344 Примечание: Попытка получить свойство необъекта

Спасибо

<?php
    public static function isHTML($str) {
    $html = array('A','ABBR','ACRONYM','ADDRESS','APPLET','AREA','B','BASE','BASEFONT','BDO','BIG','BLOCKQUOTE',
        'BODY','BR','BUTTON','CAPTION','CENTER','CITE','CODE','COL','COLGROUP','DD','DEL','DFN','DIR','DIV','DL',
        'DT','EM','FIELDSET','FONT','FORM','FRAME','FRAMESET','H1','H2','H3','H4','H5','H6','HEAD','HR','HTML',
        'I','IFRAME','IMG','INPUT','INS','ISINDEX','KBD','LABEL','LEGEND','LI','LINK','MAP','MENU','META',
        'NOFRAMES','NOSCRIPT','OBJECT','OL','OPTGROUP','OPTION','P','PARAM','PRE','Q','S','SAMP','SCRIPT',
        'SELECT','SMALL','SPAN','STRIKE','STRONG','STYLE','SUB','SUP','TABLE','TBODY','TD','TEXTAREA','TFOOT',
        'TH','THEAD','TITLE','TR','TT','U','UL','VAR');

    return preg_match("~(&lt;\/?)\b(".implode('|', $html).")\b([^>]*&gt;)~i", $str, $c);
}

private function _html_to_plain_text($node) {
    if ($node instanceof DOMText) {
        return preg_replace("/\\s+/im", " ", $node->wholeText);
    }
    if ($node instanceof DOMDocumentType) {
        // ignore
        return "";
    }

    // Next
//NEXT LINE IS ERROR ONE - LINE 1344  Notice: Trying to get property of non-object
    $nextNode = $node->nextSibling;
    while ($nextNode != null) {
        if ($nextNode instanceof DOMElement) {
            break;
        }
        $nextNode = $nextNode->nextSibling;
    }
    $nextName = null;
    if ($nextNode instanceof DOMElement && $nextNode != null) {
        $nextName = strtolower($nextNode->nodeName);
    }

    // Previous
//NEXT LINE IS ERROR TWO - LINE 1357  Notice: Trying to get property of non-object
    $nextNode = $node->previousSibling;
    while ($nextNode != null) {
        if ($nextNode instanceof DOMElement) {
            break;
        }
        $nextNode = $nextNode->previousSibling;
    }
    $prevName = null;
    if ($nextNode instanceof DOMElement && $nextNode != null) {
        $prevName = strtolower($nextNode->nodeName);
    }
//NEXT LINE IS ERROR THREE - LINE 1369  Notice: Trying to get property of non-object
    $name = strtolower($node->nodeName);

    // start whitespace
    switch ($name) {
        case "hr":
            return "------\n";

        case "style":
        case "head":
        case "title":
        case "meta":
        case "script":
            // ignore these tags
            return "";

        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
            // add two newlines
            $output = "\n";
            break;

        case "p":
        case "div":
            // add one line
            $output = "\n";
            break;

        default:
            // print out contents of unknown tags
            $output = "";
            break;
    }

    // debug $output .= "[$name,$nextName]";
//NEXT LINE IS ERROR FOUR - LINE 1408  Notice: Trying to get property of non-object
    if($node->childNodes){
        for ($i = 0; $i < $node->childNodes->length; $i++) {
            $n = $node->childNodes->item($i);

            $text = $this->_html_to_plain_text($n);

            $output .= $text;
        }
    }

    // end whitespace
    switch ($name) {
        case "style":
        case "head":
        case "title":
        case "meta":
        case "script":
            // ignore these tags
            return "";

        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
            $output .= "\n";
            break;

        case "p":
        case "br":
            // add one line
            if ($nextName != "div")
                $output .= "\n";
            break;

        case "div":
        // add one line only if the next child isn't a div
            if (($nextName != "div" && $nextName != null) || ($node->hasAttribute('class') && strstr($node->getAttribute('class'), 'emailtemplateSpacing')))
                $output .= "\n";
            break;

        case "a":
            // links are returned in [text](link) format
            $href = $node->getAttribute("href");
            if ($href == null) {
                // it doesn't link anywhere
                if ($node->getAttribute("name") != null) {
                    $output = "$output";
                }
            } else {
                if ($href == $output || ($node->hasAttribute('class') && strstr($node->getAttribute('class'), 'emailtemplateNoDisplay'))) {
                    // link to the same address: just use link
                    $output;
                } else {
                    // No display
                    $output = $href . "\n" . $output;
                }
            }

            // does the next node require additional whitespace?
            switch ($nextName) {
                case "h1": case "h2": case "h3": case "h4": case "h5": case "h6":
                    $output .= "\n";
                    break;
            }

        default:
            // do nothing
    }

    return $output;
    }
}
?>

1 Ответ

0 голосов
/ 27 сентября 2018

Похоже, переменная $node, поступающая в вашу функцию из private function _html_to_plain_text($node), не является правильным типом переменной.Может быть int, string, array или null вместо любого объекта / класса, каким он должен быть.Вам, вероятно, нужно взглянуть на любой код, вызывающий эту функцию, а не на саму функцию.

Отладка в PHP - это навык сам по себе.

  • Если кодирование выполняется вручную, подумайте о вставкеvar_export($node); операторы до и после областей, где вы подозреваете, что есть проблема, чтобы вы могли ее изучить.
  • Если у вас есть доступ к отладчику (например, Eclipse + XAMPP + XDebug), используйте его и перейдите в строкупострочно, проверяя содержимое переменной $ node, наводя на нее курсор или просматривая список переменных.
...