首页 > 编程语言 >php 根据条件打印输出,方便调试

php 根据条件打印输出,方便调试

时间:2023-07-04 19:11:37浏览次数:43  
标签:function return 打印输出 conditions value php data public 调试

laravel 核心代码调试起来,还是挺麻烦的,循环太多了。当从某个路由进去之后,进入到核心内部,断点打印的可能根据不是你认为的执行过程。为此,我想到了条件打印,跟用 ide debug 设置条件一样的思想。不过还是觉得打印更加直观一些吧。

代码很简单,一看就懂,不过多介绍了。

 

 

<?php

class debuger {

    protected $conditions = [];
    protected $file = '';
    public function __construct($value1 = true, $value2 = true)
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, );
        $this->file = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $trace[1]['file']) .':'. $trace[1]['line'];
        $this->log = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'debug.txt';
        if(!isset($_ENV['debug_next_step'])){
            $_ENV['debug_next_step'] = 0;
        }
        if(func_num_args() == 1){
            $this->if($value1);
        }else{
            $this->eq($value1, $value2);
        }
    }

    public function dump(mixed ...$values)
    {
        ob_start();
        dump(...$values);
        echo preg_replace('/\/\/\s+helpers.php:\d+/', "// $this->file", ob_get_clean());
        return $this;
    }

    public function stop(mixed ...$values)
    {
        $this->dump(...$values);
        exit(1);
    }

    public function dd(mixed ...$values)
    {
        if($this->allIsTrue()){
            dd(...$values);
        }
    }

    public function du(mixed ...$values)
    {
        if(!$this->allIsTrue()) return $this;
        $this->dump(...$values);
        return $this;
    }

    public function if(mixed $value = true)
    {
        $this->conditions[] = boolval($value);
        return $this;
    }

    public function var(mixed ...$values)
    {
        if($this->allIsTrue()){
            var_dump(...$values);
        }
        return $this;
    }

    public function eq($value1 = true, $value2 = true, $strict = false)
    {
        if($strict){
            $this->conditions[] = $value1 === $value2;
        }else{
            $this->conditions[] = $value1 == $value2;
        }
        return $this;
    }

    public function empty($value = false)
    {
        $this->conditions[] =  empty($value);
        return $this;
    }

    public function full($value = true)
    {
        $this->conditions[] = !empty($value);
        return $this;
    }

    public function compare($value1, $symbol, $value2 = null)
    {
        if(func_num_args() == 2){
            $value2 = $symbol;
            $symbol = '=';
        }
        $this->conditions[] = eval("$value1 $symbol $value2");
        return $this;
    }


    public function true($value, $strict = false)
    {
        if($strict){
            $this->conditions[] = $value === true;
        }else{
            $this->conditions[] = $value == true;
        }
        return $this;
    }

    public function false($value, $strict = false)
    {
        if($strict){
            $this->conditions[] = $value === false;
        }else{
            $this->conditions[] = $value == false;
        }
        return $this;
    }

    public function null($value = null)
    {
        $this->conditions[] = is_null($value);
        return $this;
    }

    protected function allIsTrue()
    {
        return count($this->conditions) == count(array_filter($this->conditions));
    }

    public function exec($callback = null, ...$args)
    {
        if($this->allIsTrue()){
            if(is_callable($callback)){
                call_user_func($callback, ...$args);
            }else{
                $this->dd('$callback is not callable');
            }
        }
        return $this;
    }

    public function dir($value)
    {
        $this->conditions[] = is_dir($value);
        return $this;
    }


    public function next(int $value = 0)
    {
        if($this->allIsTrue()){
            $_ENV['debug_next_step'] = $value;
        }
        return $this;
    }


    public function prev(int $value = 0)
    {
        $this->conditions[] = $value == $_ENV['debug_next_step'];
        return $this;
    }

    public function here(string $value = '== debug here ==')
    {
        dd($value);
    }

    public function return($value, $default = null)
    {
        return $this->allIsTrue()? $value : $default;
    }

    public function trace()
    {
        if($this->allIsTrue()){
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            $trace = array_reverse($trace);
            $html = '<table style="border-collapse:collapse;width: 100%;" >';
            foreach($trace as $key => $item){
                !isset($item['class']) && $item['class'] = '';
                !isset($item['type']) && $item['type'] = '';
                !isset($item['function']) && $item['function'] = '';
                $item['file'] = str_replace([__DIR__ . '/', 'vendor/', 'laravel/framework/src/', 'laravel/', '/'], ['', '', '', '', '\\'], $item['file']);
                $html .= "<tr><td style='border:1px solid #DDD;padding:4px;'>$key</td><td style='border:1px solid #DDD;padding:4px;'><td style='border:1px solid #DDD;padding:4px 30px 4px 4px;width:0px;'>{$item['file']}:{$item['line']}</td><td  style='border:1px solid #DDD;padding:4px;'>{$item['class']}{$item['type']}{$item['function']}()</td></tr>";
            }
            $html .= '</table>';
            echo $html;
        }
        return $this;
    }

    public function exit()
    {
        if($this->allIsTrue()) exit(1);
    }


    public static function unicode($string)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function($match) {
            return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
        }, $string);
    }

    public function format(mixed ...$args)
    {
        $cli = PHP_SAPI == 'cli' ? true : false;
        $content = $cli ? $this->file . PHP_EOL : '<pre style="margin-bottom:5px;background:#f3f3f4;padding:5px;border:1px solid #DDD;">文件: ' . $this->file . PHP_EOL . '<hr/>';
        foreach($args as $key => $data) {
            $append = [];
            if(is_bool($data)) {
                $content .= ($data ? '(bool) true' : '(bool) false') . PHP_EOL;
            }else if(is_null($data)) {
                $content .= '(null) null' . PHP_EOL;
            }else if($data === '') {
                $content .= '""' . PHP_EOL;
            }else if(is_array($data)){
                $content .= print_r($data, true);
            }else if(is_scalar($data) && !function_exists($data) && !class_exists($data, false)){
                $content .= self::unicode($data) . PHP_EOL;
            }
            if(is_string($data) && function_exists($data)){
                $object = new \ReflectionFunction($data);
                $content .= print_r(['Type' => 'Function', 'Name' => $data, 'Namespace' => $object->getNamespaceName(), 'File' => $object->getFilename()], true);
            }
            if(is_object($data) || (is_string($data) && class_exists($data, false))) {
                $message = '';
                if(is_object($data)) {
                    if($data instanceof \Exception) {
                        $file = $data->getFile() . ':' . $data->getLine();
                        $message = $data->getMessage() . ' (' . $data->getCode() . ')';
                    }else if($data instanceof \think\Model || (is_array($data) && current($data) instanceof \think\Model)){
                        $append['Collect'] = collection($data)->toArray();
                    }else if(method_exists($data, 'toArray')) {
                        $append['ToArray'] = $data->toArray();
                    }else if(method_exists($data, '__toString')) {
                        $append['ToString'] = $data->__toString();
                    }
                    $name = get_class($data);
                    $fields = get_object_vars($data);
                }else {
                    $name = $data;
                    $fields = get_class_vars($data);
                }
                $methods = get_class_methods($data);
                $object = new \ReflectionClass($data);
                if(!isset($file)) {
                    $file = $object->getFilename();
                }
                $content .= print_r(array('Type' => (is_object($data)? 'Object' : 'Class'),  (is_object($data)? 'Class' : 'Name') => $name, 'Namespace' => $object->getNamespaceName(), 'Exception' => $message, 'File' => $file, 'Attribute ' => $fields, 'Data' => $append,  'Method' => $methods), true);
            }
            if(array_key_exists($key + 1, $args)) {
                $content .= $cli ? PHP_EOL . '----------------------------------------------------------------------------------' . PHP_EOL : '<hr/>';
            }
        }
        $content .= $cli ? PHP_EOL : '</pre>';
        return $content;
    }


}


// ================================================================================================
// 为了方便,定义一个函数,之所以叫 ifif 是为了搜索时好找

function ifif($value1 = true, $value2 = true)
{
    if(func_num_args() == 0){
        return new \debuger();
    }else if(func_num_args() == 1){
        return new \debuger($value1);
    }else{
        return new \debuger($value1, $value2);
    }
}

 

标签:function,return,打印输出,conditions,value,php,data,public,调试
From: https://www.cnblogs.com/zbseoag/p/17526758.html

相关文章

  • Mac 下的 MxSrvs 安装 PHPzip 的扩展(感觉各种扩展都是这个样子)
    https://my.oschina.net/wgw888/blog/8563131https://blog.csdn.net/unhejing/article/details/107176891 从PHP官网下载一个zip的扩展,wgethttp://pecl.php.net/get/zip然后在下载好的目录下使用:sudo/Applications/MxSrvs/bin/php/bin/peclinstallzip来安装......
  • 基于thinkphp开发的Telegram电报机器人系统,支持关键词回复
    系统支持多个添加机器人、支持关键词回复、支持设置按钮回复、支持个人、群、频道等的消息处理,另外支持消息定时推送。基于thinkphp开发的TG电报机器人系统,支持关键词回复后台登录地址:/admin后台账号密码:admin/123456下载地址:https://pan.saipancloud.com/s/7NRbiilGZV ......
  • CakePHP教程_编程入门自学教程_菜鸟教程-免费教程分享
    教程简介CakePHP是一个运用了诸如ActiveRecord、AssociationDataMapping、FrontController和MVC等著名设计模式的快速开发框架。该项目主要目标是提供一个可以让各种层次的PHP开发人员快速地开发出健壮的Web应用,而又不失灵活性。CakePHP是一个基于PHP,免费且开源的迅速发展框......
  • 2023最新php goto完全解密系统程序
    PHPGOTO加密代码一度被认为是程序员的一大难题,但随着技术的不断进步,现在有了一款神奇的工具来解决这个问题。这款PHPGOTO解密工具拥有强大的功能,能够轻松解密和还原GOTO语句,让你的程序恢复到最初的状态。完整有效解密还原源码goto解密,基本做到免修复直接可用。Windows电脑版:https......
  • 修复雅黑php探针流量显示不出来的问题
    前言雅黑PHP探针算是一个历史悠久的简单的PHP探针。特性、功能、用途什么的就不在此过多赘述了,毕竟随便搜索下很容易就能找到。至于官网,并非“永久性”的不可用。下方为域名的whois信息,通过whois信息可知,域名并没有到期,站点其实有时候能访问,有时候不行。今年2023年,也是有一些时间......
  • GraphPad Prism 9-科研医学数据绘图分析mac/win版
    GraphPadPrism9是一款功能强大、易于使用的科研和医学数据处理软件。它可以帮助研究人员进行数据可视化、统计分析和实验结果解读,提供了广泛的功能和工具,使得数据呈现更直观且易于理解。→→↓↓载GraphPadPrism9mac/win版 Prism9的主要特点之一是其直观的用户界面。软......
  • Idea远程debug调试本地代码 Remote JVM Debug
    如果项目太大本地启动不了,或者假设你项目是微服务项目依赖太多,你写了个功能后,想本地启动debug调试又不方便,此时可以用一个idea远程debug神奇。实现访问测试环境,回调到你本地启动的代码。1,准备一个springboot项目什么都不用配置2,idea设置RemoteJVMDebug端口随便设置就行......
  • lnmp下一键切换php7与8脚本
    先去/usr/local目录下,新建php7bak,php8bak两个目录,假设当下默认安装的是php7,则将php8的目录复制到php8bak目录下备用。 shell脚本如下:#!/bin/bashpath7=/usr/local/php7bakpath8=/usr/local/php8bakpid=emptyif[!-d$path7/php];thenecho'Startconvertingph......
  • 【PHP语言】医院安全(不良)事件报告系统
    技术架构:前后端分离,仓储模式,开发语言:PHP开发工具:vscode前端框架:vue2+element后端框架:laravel8数据库:mysql5.7系统概述:医院安全(不良)事件报告系统是一种用于医院管理和监管的工具,旨在帮助医疗机构识别、跟踪、分析和解决各种医疗安全事件,提高医疗质量和患者安全。医院安全(......
  • 08_调试与使用虚拟的GPIO控制器
    目录资料下载视频观看调试与使用虚拟的GPIO控制器1.硬件功能2.编写设备树文件3.上机实验3.2编译、替换设备树3.3编译、安装驱动程序4.STM32MP157上的bug资料下载coding无法使用浏览器打开,必须用git工具下载:gitclonehttps://e.coding.net/weidongshan/linux/doc_and_sourc......