如果WP_ERROR抛出错误,我如何创建“不给变量赋值”的状态?

时间:2018-01-08 作者:Jonathan Guerin

我有以下代码可以从给定帐户中抓取Instagram图片:

<?php

class Scrape_Instagram {

    private $images = array();

    public function __construct( $username ) {
        $this->username = $username;
    }

    private function build_endpoint() {
        /**
        * Builds the endpoint for the Instagram API, provided the username from constructor.
        * @param $end_cursor    Used in case the user wants more pictures to be scrapped.
        */
        return \'https://www.instagram.com/\' . trim( strtolower( $this->username ) ) . \'/?__a=1\';
    }

    private function get_json() {
        /**
        * GET\'s the data from Instagram, provided the endpoint.
        */
        $request = wp_remote_get( $this->build_endpoint() );

        if( is_wp_error( $request ) ) {
            return new WP_Error( \'site-down\', esc_html__( \'Instagram may be down. Unable to communicate.\', \'_s\') );
        }

        elseif( wp_remote_retrieve_response_code( $request ) !== 200 ) {
            return new WP_Error( \'invalid-response\', esc_html__( \'Got an invalid response.\', \'_s\') );
        }

        else {
            return wp_remote_retrieve_body( $request );
        }
    }

    private function get_data() {
        /**
        * Ingests the data from get_json() then converts / decodes into an array.
        */
        $data = json_decode( $this->get_json(), true);

        if ( is_wp_error( $data ) ) {
            return new WP_Error( \'invalid-data\', esc_html__( \'Something is wrong. Did you enter the right username?\', \'_s\' ) );
        } else {
            return $data;
        }
    }

    protected function get_links() {
        /**
        * Based on the array generated from get_data(), some nodes have resulted that contain information about
        * each photo the user has, as such, we\'ll loop through each photo and access any data.
        * @see [\'user\'][\'media\'][\'nodes\'] - individual node / image.
        */
        $response = $this->get_data();

        foreach( $response[\'user\'][\'media\'][\'nodes\'] as $node ) {
            // Check if type is video, if not, set default image
            array_push( $this->images, $node[\'thumbnail_src\'] );
        }
        return $this->images;
    }

    public function get_instagram_photos_links() {
        return $this->get_links();
    }
}
有几个WP_Error 处理它检查的变量可能产生的错误。

因此,在方法中get_json(), 我有:

private function get_json() {
    /**
    * GET\'s the data from Instagram, provided the endpoint.
    */
    $request = wp_remote_get( $this->build_endpoint() );

    if( is_wp_error( $request ) ) {
        return new WP_Error( \'site-down\', esc_html__( \'Instagram may be down. Unable to communicate.\', \'_s\') );
    }

    elseif( wp_remote_retrieve_response_code( $request ) !== 200 ) {
        return new WP_Error( \'invalid-response\', esc_html__( \'Got an invalid response.\', \'_s\') );
    }

    else {
        return wp_remote_retrieve_body( $request );
    }
}
哪个应该停止$data 如果失败,就无法获得任何价值。我想要/认为它会做的是(尽管我知道我第一次声明$data):

Hey, WordPress, see this $data? Yea, don\'t assign anything to it if these WP_Errors say it\'s bad. Just drop it and break loop..

不幸的是,这并没有发生,我已经为此构建了一个小部件,使用:

<?php
/**
* Plugin Name: Instagram Widget
*/

add_action( \'widget_init\', \'custom_widget_instagram_pictures\');
register_widget( \'custom_widget_instagram_pictures\' );

class custom_widget_instagram_pictures extends Wp_Widget {

    /**
    * Setup the Widget
    */
    public function __construct() {
        $widget_ops = array(\'classname\'     => \'custom_widget_instagram_pictures\',
                            \'description\'   => esc_html__(\'A widget to display instagram photos.\', \'_s\') 
                            );

        $control_ops = array(\'id_base\'      => \'custom_widget_instagram_pictures\');

        parent::__construct( \'custom_widget_instagram_pictures\', __(\'_s: Instagram Widget\', \'_s_simple_image_widget\'), $widget_ops, $control_ops );
    }

    public function widget( $args, $instance ) {
        extract( $args );
        $title              = isset( $instance[\'title\'] ) ? apply_filters(\'widget_title\', $instance[\'title\'] ) : \'\';
        $username           = isset( $instance[\'username\'] ) ? $instance[\'username\'] : \'\';
        $profile_link       = isset( $instance[\'profile_link\'] ) ? $instance[\'profile_link\'] : \'\';

        echo ent2ncr( $before_widget );

        if ( $title ) {
            echo ent2ncr( $before_title . $title . $after_title );
        }
        ?>
        <div class="instagram-widget">
            <ul class="instagram-widget-list">
                <?php if( $username ) {
                    $instagram_object = new Scrape_Instagram($username);
                    $instagram_links = $instagram_object->get_instagram_photos_links();
                    foreach( $instagram_links as $link ) { ?>
                        <li class="instagram-thumb">
                            <a href="<?php echo $link ?>"><img src="<?php echo $link ?>"/></a>
                        </li>
                    <?php }

                } ?>
            </ul>
            <?php if( \'on\' == $profile_link ) : ?>
            <button class="instagram-widget-profile-link"><a href="<?php echo \'https://www.instagram.com/\' . $username; ?>"><?php echo $username ?></a></button>
            <?php endif; ?>
        </div>
        <?php
        echo ent2ncr( $after_widget );
    }

    function update( $new_instance, $old_instance ) {
        $instance[\'title\']          = ( isset( $new_instance[\'title\'] ) ) ? strip_tags($new_instance[\'title\'] ) : \'\';
        $instance[\'username\']       = ( isset( $new_instance[\'username\'] ) ) ? strip_tags( $new_instance[\'username\'] ) : \'\';
        $instance[\'profile_link\']   = ( isset( $new_instance[\'profile_link\'] ) ) ? strip_tags( $new_instance[\'profile_link\'] ) : \'\';

        return $instance;
    }

    function form( $instance ) {
        $defaults = array(  \'title\'         => \'\',
                            \'username\'      => \'\',
                            \'profile_link\'  => \'\',
                        );

        $instance = wp_parse_args( (array) $instance, $defaults ); ?>
        <!-- Form for Title -->
        <p>
            <label for="<?php echo $this->get_field_id( \'title\' ); ?>">Widget Title:<strong>(Leave Blank to Hide)</strong></label>
            <br>
            <input class="widefat" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" value="<?php echo $instance[\'title\'];?>" />
        </p>

        <!-- Form for Link -->
        <p>
            <label for="<?php echo $this->get_field_id( \'username\' ); ?>">Username:</label>
            <br>
            <input class="widefat" id="<?php echo $this->get_field_id( \'username\' ); ?>" name="<?php echo $this->get_field_name( \'username\' ); ?>" value="<?php echo $instance[\'username\'];?>" />
        </p>

        <!-- The checkbox -->
        <p>
            <input class="checkbox" type="checkbox" <?php checked( $instance[ \'profile_link\' ], \'on\' ); ?> id="<?php echo $this->get_field_id( \'profile_link\' ); ?>" name="<?php echo $this->get_field_name( \'profile_link\' ); ?>" /> 
            <label for="<?php echo $this->get_field_id( \'profile_link\' ); ?>">Show Instagram Button?</label>
        </p>
    <?php

    }
}

?>
如果我输入了错误的用户名,请说:“kinfolk53252395932”,它只会抛出以下内容:

The error

我怎样才能做到这一点?

1 个回复
SO网友:kero

看起来给出错误的那条线是这条

$data = json_decode( $this->get_json(), true);
这样(未经测试)应该可以:

private function get_data() {
    /**
    * Ingests the data from get_json() then converts / decodes into an array.
    */
    $json = $this->get_json();
    if (is_wp_error($json)) {
        return new WP_Error( \'invalid-data\', esc_html__( \'Something is wrong. Did you enter the right username?\', \'_s\' ) );
    }

    $data = json_decode( $json, true);

    if ( is_wp_error( $data ) ) {
        return new WP_Error( \'invalid-data\', esc_html__( \'Something is wrong. Did you enter the right username?\', \'_s\' ) );
    } else {
        return $data;
    }
}
我其实不太熟悉WP_Error, 但是错误不应该被抛出而不是返回吗?

为什么它是这样工作的?PHP错误消息告诉您出了什么问题

json\\u decode()要求参数1为字符串,对象为给定的

json_decode( $this->get_json(),
             ^ should be a string but is an object
从您的代码中我们知道,它是WP_Error, 因为这就是你回来的原因get_json().

我想最重要的一点是:在使用变量/返回之前,检查变量/返回中的错误。

结束

相关推荐

PLUGINS_LOADED操作工作不正常

我试图在表单提交后向用户发送电子邮件,但出现错误Call to undefined function wp_mail() in C:\\xampp\\htdocs\\wordpress\\wp-content\\plugins\\contact form\\contact-form-plugin.php on line 46<我在谷歌上搜索了一下,发现它与add_action( \'plugins_loaded\', \'functionShowForm\' );.我在代码中添加了这一行,但它在主窗