From fe905f10ba8a8eec74e9a42cef73f74352df0a63 Mon Sep 17 00:00:00 2001 From: zxin <14545600+NHZEX@users.noreply.github.com> Date: Fri, 20 Oct 2023 11:37:54 +0800 Subject: [PATCH] =?UTF-8?q?[3.0]=20=E6=9B=B4=E6=96=B0=E5=BC=80=E5=8F=91?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E9=9B=86=20(#594)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update: phpstan 1.10.39 * Update: core 规则更新 * Update: 组件规则更新 * Update: 重构 phpstan 启动代码 * Fix * Update: .gitattributes * Update: 调整目录结构 * Fix * Update: 修复一些错误报告 * Update: 重新生成 core 基线 * Update: 应用 php-cs-fixer 修复 * Update: rector 0.18.5 * Update: 更新代码风格规范 * Update: 应用 rector 的更改到核心 * Update: 格式化代码 * Update: 修复代码分析 * Update: 修复代码风格 * Update: 应用 rector 的更改到组件 * Update: 修复代码风格 * Update: 更新工具脚本 * Update: 修复代码风格 * Update: 使工作流能在推送新提交时自动取消前一个 * Update: 选择更合适的唯一组合 --- .gitattributes | 2 +- .github/workflows/ci.yml | 4 + .github/workflows/codecov.yml | 4 + .github/workflows/phpcs.yml | 4 + .github/workflows/phpstan.yml | 50 +++---- .github/workflows/rector.yml | 4 + .php-cs-fixer.php | 7 +- composer.json | 4 +- dev/Plugin.php | 4 +- dev/bootstrap.php | 12 +- dev/phpstan.sh | 90 +++++++++++++ dev/rector.sh | 91 +++++++++++++ dev/try-include-swoole.php | 2 +- phpstan-baseline/baseline-access-control.neon | 2 + phpstan-baseline/baseline-amqp.neon | 2 + phpstan-baseline/baseline-apidoc.neon | 2 + phpstan-baseline/baseline-core.neon | 51 +++++++ phpstan-baseline/baseline-fpm.neon | 2 + phpstan-baseline/baseline-grpc.neon | 2 + phpstan-baseline/baseline-jwt.neon | 126 ++++++++++++++++++ phpstan-baseline/baseline-kafka.neon | 2 + phpstan-baseline/baseline-macro.neon | 2 + phpstan-baseline/baseline-mqtt.neon | 2 + phpstan-baseline/baseline-pgsql.neon | 2 + phpstan-baseline/baseline-queue.neon | 2 + phpstan-baseline/baseline-rate-limit.neon | 2 + phpstan-baseline/baseline-roadrunner.neon | 2 + phpstan-baseline/baseline-rpc.neon | 2 + phpstan-baseline/baseline-shared-memory.neon | 2 + phpstan-baseline/baseline-smarty.neon | 2 + phpstan-baseline/baseline-snowflake.neon | 2 + phpstan-baseline/baseline-swoole-tracker.neon | 2 + phpstan-baseline/baseline-swoole.neon | 21 +++ .../baseline-workerman-gateway.neon | 2 + phpstan-baseline/baseline-workerman.neon | 6 + phpstan-baseline/component-baseline.php | 26 ++++ phpstan-components.neon | 37 ++--- phpstan.neon | 45 ++++--- phpstan.sh | 48 ------- rector.sh | 26 ---- split-repository/split.php | 2 +- src/Aop/AfterThrowingJoinPoint.php | 12 +- src/Aop/AopAnnotationLoader.php | 2 +- src/Aop/JoinPoint.php | 32 ++--- src/Aop/Listener/ImiInit.php | 4 +- src/Aop/Model/AopItem.php | 14 +- src/Async/AsyncResult.php | 11 +- src/Bean/Annotation.php | 6 +- .../Annotation/Model/AnnotationRelation.php | 8 +- src/Bean/Annotation/Model/ClassAnnotation.php | 14 +- .../Model/ClassAnnotationRelation.php | 24 ++-- .../Model/ConstantAnnotationRelation.php | 34 ++--- .../Model/MethodAnnotationRelation.php | 34 ++--- .../Model/PropertyAnnotationRelation.php | 34 ++--- src/Bean/AnnotationLoader.php | 2 +- src/Bean/AnnotationParser.php | 16 +-- src/Bean/BeanFactory.php | 2 +- src/Bean/BeanProxy.php | 39 ++---- src/Bean/Container.php | 18 ++- src/Bean/Parser/BeanParser.php | 2 +- src/Bean/ReflectionUtil.php | 6 +- src/Bean/Scanner.php | 2 +- src/Cache/Aop/CacheableAop.php | 2 +- src/Cache/Handler/File.php | 2 +- src/Cache/Handler/RedisHash.php | 6 +- src/Cli/Contract/BaseCommand.php | 11 +- src/Cli/ImiArgvInput.php | 22 ++- src/Cli/ImiCommand.php | 67 ++++------ src/Cli/Parser/ToolParser.php | 6 +- src/Cli/bootstrap.php | 6 +- .../src/AccessControl/Member.php | 12 +- .../access-control/test/Tool/TestTool.php | 4 +- .../AMQP/QueueTest/QueueTestConsumer.php | 2 +- .../amqp/example/AMQP/Test/TestConsumer.php | 2 +- .../example/Process/SwooleTestProcess.php | 4 +- src/Components/amqp/src/Base/BaseConsumer.php | 2 +- .../amqp/src/Base/BasePublisher.php | 4 +- src/Components/amqp/src/Contract/IMessage.php | 4 +- src/Components/amqp/src/Pool/AMQPResource.php | 20 ++- .../amqp/src/Queue/AMQPQueueDriver.php | 12 +- .../amqp/src/Queue/AMQPQueueDriverHandler.php | 28 ++-- .../amqp/src/Queue/QueueConsumer.php | 19 ++- .../amqp/src/Queue/SwooleQueueConsumer.php | 19 ++- src/Components/amqp/tests/PHPUnitHook.php | 8 +- .../amqp/tests/Queue/BaseQueueTest.php | 4 +- src/Components/amqp/tests/bootstrap.php | 12 +- .../ApiServer/Controller/IndexController.php | 24 +--- src/Components/apidoc/src/Tool/DocTool.php | 8 +- .../fpm/src/Http/Message/FpmRequest.php | 2 +- .../fpm/src/Http/Message/FpmResponse.php | 2 +- src/Components/fpm/src/Server/Cli/Server.php | 2 +- src/Components/fpm/tests/bootstrap.php | 4 +- .../grpc/src/Client/GrpcService.php | 32 ++--- .../grpc/src/Client/ServiceAgent.php | 34 ++--- .../grpc/src/Listener/WorkerExit.php | 2 +- .../grpc/src/Proxy/Http/GrpcHttpClient.php | 8 +- .../grpc/src/Proxy/Http/GrpcHttpProxy.php | 2 +- .../Server/Error/DefaultGrpcErrorHandler.php | 2 +- src/Components/grpc/src/Util/ProtobufUtil.php | 17 +-- .../grpc/tests/Grpc/PHPUnitHook.php | 2 +- src/Components/grpc/tests/bootstrap.php | 10 +- src/Components/jwt/src/Model/JWTConfig.php | 4 +- src/Components/jwt/tests/PHPUnitHook.php | 2 +- src/Components/jwt/tests/Unit/JWTTest.php | 17 +-- .../example/Process/SwooleTestProcess.php | 4 +- .../kafka/src/Base/BaseConsumer.php | 2 +- src/Components/kafka/src/Pool/KafkaPool.php | 4 +- .../kafka/src/Pool/KafkaResource.php | 12 +- .../kafka/src/Queue/KafkaQueueDriver.php | 12 +- src/Components/kafka/tests/PHPUnitHook.php | 2 +- src/Components/kafka/tests/bootstrap.php | 12 +- src/Components/macro/src/AutoLoader.php | 5 +- src/Components/macro/src/bootstrap.php | 2 +- src/Components/mqtt/src/Client/Connection.php | 44 +++--- src/Components/mqtt/src/Client/MQTTClient.php | 18 ++- .../imi/Server/MQTT/Message/ReceiveData.php | 34 ++--- src/Components/mqtt/tests/MQTT/MQTTTest.php | 2 +- src/Components/mqtt/tests/PHPUnitHook.php | 2 +- src/Components/mqtt/tests/bootstrap.php | 10 +- .../pgsql/src/Db/Drivers/PdoPgsql/Driver.php | 6 +- .../pgsql/src/Db/Drivers/Swoole/Statement.php | 48 +++---- .../src/Db/Drivers/SwooleNew/Statement.php | 35 ++--- .../src/Model/Cli/Model/ModelGenerate.php | 46 ++----- src/Components/pgsql/tests/PHPUnitHook.php | 6 +- .../pgsql/tests/Unit/Db/DbBaseTest.php | 8 +- src/Components/phar/config/imi-phar-cfg.php | 4 +- src/Components/phar/phar_init.php | 2 +- src/Components/phar/src/PharHandler.php | 2 +- src/Components/phar/src/PharService.php | 4 +- src/Components/phar/tests/run-tests.php | 8 +- .../example/Listener/WorkerStartListener.php | 4 +- .../queue/src/Driver/RedisQueueDriver.php | 31 ++--- .../src/Driver/RedisStreamQueueDriver.php | 16 +-- .../queue/src/Model/QueueConfig.php | 12 +- .../SwooleBaseQueueConsumerPartial.php | 6 +- .../Process/SwooleQueueConsumerProcess.php | 10 +- .../queue/src/Service/BaseQueueConsumer.php | 14 +- .../queue/src/Service/QueueService.php | 6 +- src/Components/queue/src/Tool/QueueTool.php | 12 +- src/Components/queue/tests/PHPUnitHook.php | 2 +- .../queue/tests/Queue/BaseQueueTest.php | 4 +- src/Components/rate-limit/src/RateLimiter.php | 10 +- .../src/Storage/ImiRedisStorage.php | 38 ++---- .../rate-limit/src/WorkerLimiter.php | 8 +- src/Components/roadrunner/bootstrap.php | 4 +- .../src/HotUpdate/HotUpdateProcess.php | 2 +- .../src/Http/Message/RoadRunnerRequest.php | 2 +- .../src/Http/Message/RoadRunnerResponse.php | 7 +- .../roadrunner/src/RoadRunnerApp.php | 2 +- .../roadrunner/src/Server/Http/Server.php | 2 +- src/Components/roadrunner/tests/bootstrap.php | 2 +- .../rpc/src/Client/Pool/RpcClientResource.php | 12 +- .../Annotation/Parser/RpcControllerParser.php | 6 +- .../shared-memory/src/Pool/ClientResource.php | 12 +- ...ernal_compile_private_special_variable.php | 2 +- src/Components/smarty/tests/bootstrap.php | 4 +- .../snowflake/src/ImiRedisResolver.php | 18 ++- .../snowflake/tests/PHPUnitHook.php | 2 +- .../ApiServer/Controller/IndexController.php | 4 +- .../TCPServer/test-client/eof-client.php | 2 +- .../TCPServer/test-client/fixed-client.php | 2 +- .../example/UDPServer/test-client/client.php | 2 +- .../MainServer/Controller/Http/HandShake.php | 4 +- .../Controller/Http/IndexController.php | 4 +- .../MainServer/Controller/TestController.php | 4 +- src/Components/swoole/bootstrap.php | 6 +- .../swoole/src/Async/SwooleHandler.php | 6 +- .../swoole/src/Async/SwooleResult.php | 5 +- .../src/Context/CoroutineContextManager.php | 4 +- .../swoole/src/Cron/CronManager.php | 12 +- .../swoole/src/Cron/Process/CronProcess.php | 4 +- .../src/Cron/Process/CronWorkerProcess.php | 2 +- src/Components/swoole/src/Cron/Scheduler.php | 4 +- .../swoole/src/Cron/Task/CronTask.php | 2 +- .../swoole/src/Db/Driver/Swoole/Statement.php | 44 +++--- .../swoole/src/HotUpdate/HotUpdateProcess.php | 6 +- .../src/Http/Message/SwooleEmitHandler.php | 5 +- .../swoole/src/Http/Message/SwooleRequest.php | 30 ++--- .../src/Http/Message/SwooleResponse.php | 22 ++- .../swoole/src/Lock/Handler/Atomic.php | 2 +- .../swoole/src/Log/SwooleLogger.php | 4 +- .../swoole/src/Pool/BaseAsyncPool.php | 10 +- .../swoole/src/Process/BasePoolProcess.php | 12 +- .../swoole/src/Process/BaseProcess.php | 12 +- .../swoole/src/Process/Cli/Process.php | 8 +- src/Components/swoole/src/Process/Pool.php | 43 ++---- src/Components/swoole/src/Process/Process.php | 12 +- .../swoole/src/Process/ProcessManager.php | 10 +- .../swoole/src/Process/ProcessPoolManager.php | 6 +- src/Components/swoole/src/Process/Signal.php | 4 +- src/Components/swoole/src/Server/Base.php | 36 +++-- .../swoole/src/Server/Cli/Server.php | 4 +- .../StoreHandler/MemoryTable.php | 14 +- .../Server/Http/Listener/BeforeRequest.php | 8 +- .../Middleware/ExecuteTimeoutMiddleware.php | 4 +- .../swoole/src/Server/Http/Server.php | 10 +- .../src/Server/Listener/OnPipeMessage.php | 2 +- .../Server/TcpServer/Message/ReceiveData.php | 12 +- .../swoole/src/Server/TcpServer/Server.php | 12 +- .../Server/UdpServer/Message/PacketData.php | 12 +- .../swoole/src/Server/UdpServer/Server.php | 4 +- .../Server/Util/Amqp/AmqpServerConsumer.php | 26 ++-- .../Server/Util/Amqp/AmqpServerPublisher.php | 5 +- .../swoole/src/Server/Util/AmqpServerUtil.php | 10 +- .../src/Server/Util/LocalServerUtil.php | 2 +- .../src/Server/Util/RedisServerUtil.php | 8 +- .../src/Server/WebSocket/Message/Frame.php | 12 +- .../Middleware/HandShakeMiddleware.php | 2 +- .../swoole/src/Server/WebSocket/Server.php | 22 +-- src/Components/swoole/src/SwooleApp.php | 8 +- src/Components/swoole/src/SwooleTimer.php | 4 +- .../src/Task/Handler/BeanTaskHandler.php | 14 +- src/Components/swoole/src/Task/TaskInfo.php | 24 ++-- src/Components/swoole/src/Task/TaskParam.php | 8 +- src/Components/swoole/src/Util/Imi.php | 2 +- .../swoole/src/Worker/SwooleWorkerHandler.php | 2 +- src/Components/swoole/src/functions.php | 2 +- src/Components/swoole/tests/bootstrap.php | 6 +- src/Components/swoole/tests/unit/BaseTest.php | 2 +- .../tests/unit/Component/PHPUnitHook.php | 4 +- .../Component/Tests/CacheAnnotationTest.php | 6 +- .../Component/Tests/LockAnnotationTest.php | 2 +- .../tests/unit/Component/Tests/PoolTest.php | 2 +- .../unit/Component/Tests/RedisManagerTest.php | 2 +- .../swoole/tests/unit/Component/test.php | 4 +- .../Controller/MemoryTableController.php | 2 +- .../unit/HttpServer/Listener/WorkerStart.php | 2 +- .../HttpServer/Tests/CustomSessionIdTest.php | 4 +- .../tests/unit/HttpServer/Tests/Http2Test.php | 2 +- .../tests/unit/HttpServer/Tests/HttpsTest.php | 4 +- .../tests/unit/TCPServer/Tests/TCPTest.php | 4 +- .../tests/unit/UDPServer/Tests/UDPTest.php | 4 +- .../WebSocketServer/Tests/ServerUtilTest.php | 14 +- .../unit/WebSocketServer/Tests/WSTest.php | 10 +- .../Tests/ServerUtilTest.php | 12 +- .../Tests/ServerUtilTest.php | 12 +- .../Tests/ServerUtilTest.php | 12 +- .../Tests/WSTest.php | 8 +- .../StoreHandler/ConnectionContextGateway.php | 2 +- .../Message/WorkermanGatewaySwooleRequest.php | 28 ++-- .../Server/Business/Task/WorkerTask.php | 4 +- .../Server/Business/TcpBusinessServer.php | 10 +- .../Business/WebSocketBusinessServer.php | 10 +- .../Http/Message/WorkermanRequest.php | 28 ++-- .../Server/Business/TcpBusinessServer.php | 8 +- .../Business/WebSocketBusinessServer.php | 10 +- .../Server/Gateway/GatewayServer.php | 2 +- .../workerman-gateway/tests/bootstrap.php | 6 +- .../WebSocket/Workerman/ServerUtilTest.php | 10 +- .../Tests/WebSocket/Workerman/WSTest.php | 6 +- src/Components/workerman/bootstrap.php | 4 +- .../src/Cron/Process/CronProcess.php | 4 +- .../src/HotUpdate/HotUpdateProcess.php | 2 +- .../src/Http/Message/WorkermanEmitHandler.php | 5 +- .../src/Http/Message/WorkermanRequest.php | 38 +++--- .../src/Http/Message/WorkermanResponse.php | 42 +++--- .../workerman/src/Process/BaseProcess.php | 12 +- .../workerman/src/Process/ProcessManager.php | 4 +- src/Components/workerman/src/Server/Base.php | 18 +-- .../workerman/src/Server/Cli/Server.php | 2 +- .../workerman/src/Server/Http/Server.php | 2 +- .../workerman/src/Server/Tcp/Server.php | 2 +- .../workerman/src/Server/Udp/Server.php | 2 +- .../workerman/src/Server/WebSocket/Server.php | 2 +- .../src/Server/WorkermanServerWorker.php | 4 +- src/Components/workerman/src/Util/Imi.php | 2 +- src/Components/workerman/src/WorkermanApp.php | 4 +- src/Components/workerman/tests/bootstrap.php | 4 +- .../unit/AppServer/Tests/Tcp/TCPTest.php | 4 +- .../unit/AppServer/Tests/Udp/UDPTest.php | 4 +- .../Tests/WebSocket/ServerUtilTest.php | 10 +- .../unit/AppServer/Tests/WebSocket/WSTest.php | 6 +- .../Tests/WebSocket/ServerUtilTest.php | 12 +- src/Config/DotEnv/Parser.php | 2 +- src/ConnectionContext.php | 6 +- src/Core/App/Contract/BaseApp.php | 16 +-- src/Core/Context/DefaultContextManager.php | 2 +- src/Cron/Client.php | 12 +- src/Cron/CronManager.php | 2 +- src/Cron/CronTask.php | 104 ++++++--------- src/Cron/Message/CommonMsg.php | 16 +-- src/Cron/Message/Result.php | 58 +++----- src/Db/Db.php | 2 +- src/Db/Drivers/Base.php | 14 +- src/Db/Mysql/Drivers/Mysqli/Statement.php | 55 +++----- src/Db/Mysql/Drivers/PdoMysql/Driver.php | 6 +- .../Query/FullText/MysqlFullTextOptions.php | 14 +- .../Query/Pagination/BigTablePagination.php | 11 +- src/Db/Pool/DbResource.php | 12 +- src/Db/Query/Builder/BaseBuilder.php | 14 +- src/Db/Query/Database.php | 24 ++-- src/Db/Query/Field.php | 12 +- src/Db/Query/Interfaces/IQuery.php | 4 +- src/Db/Query/Join.php | 52 +++----- src/Db/Query/Order.php | 24 ++-- src/Db/Query/PaginateResult.php | 64 ++++----- src/Db/Query/Query.php | 42 +++--- src/Db/Query/Result.php | 12 +- src/Db/Query/Result/ChunkByOffsetResult.php | 8 +- src/Db/Query/Result/ChunkResult.php | 14 +- src/Db/Query/Result/CursorResult.php | 12 +- src/Db/Query/Table.php | 44 +++--- src/Db/Query/Where/Where.php | 34 ++--- src/Db/Query/Where/WhereFullText.php | 5 +- src/Db/Query/WhereCollector.php | 5 +- src/Db/Query/WrapField.php | 11 +- src/Env.php | 22 +-- src/Event/EventItem.php | 24 ++-- src/Event/EventParam.php | 36 +++-- src/Event/TEvent.php | 4 +- src/HotUpdate/Monitor/BaseMonitor.php | 14 +- src/HotUpdate/Monitor/FileMTime.php | 6 +- src/HotUpdate/Monitor/Inotify.php | 4 +- src/Lock/Aop/TLockableParser.php | 2 +- src/Lock/Handler/BaseLock.php | 12 +- src/Log/ErrorLog.php | 36 ++--- src/Log/Formatter/ConsoleLineFormatter.php | 4 +- src/Main/BaseMain.php | 12 +- src/Model/Cli/Model/ModelGenerate.php | 14 +- src/Model/Key/KeyRule.php | 28 ++-- src/Model/Meta.php | 12 +- src/Model/Model.php | 26 ++-- src/Model/RedisModel.php | 17 +-- src/Model/Relation/Delete.php | 8 +- src/Model/Relation/Query.php | 4 +- src/Model/Relation/TRelation.php | 13 +- src/Model/Relation/Update.php | 8 +- src/Model/SoftDelete/Traits/TSoftDelete.php | 2 +- src/Pool/BasePool.php | 12 +- src/Pool/BasePoolResource.php | 14 +- src/Pool/PoolItem.php | 12 +- src/Pool/TUriResourceConfig.php | 2 +- src/Redis/RedisHandler.php | 14 +- src/Redis/RedisManager.php | 6 +- src/Redis/RedisResource.php | 13 +- src/Redis/Traits/TRedisPool.php | 2 +- .../ConnectionContext/StoreHandler/Local.php | 4 +- .../ConnectionContext/StoreHandler/Redis.php | 26 ++-- src/Server/Contract/BaseServer.php | 22 ++- src/Server/Group/Group.php | 34 ++--- src/Server/Group/Handler/Redis.php | 14 +- .../Http/Error/ExecuteTimeoutHandler.php | 2 +- .../Http/Message/Emitter/SseMessageEvent.php | 24 +--- src/Server/Http/Message/UploadedFile.php | 42 +++--- src/Server/Http/RequestHandler.php | 16 +-- src/Server/Http/Route/Annotation/Route.php | 2 +- src/Server/Http/Route/HttpRoute.php | 12 +- src/Server/Http/Route/RouteItem.php | 42 +++--- src/Server/Http/Route/RouteResult.php | 32 ++--- src/Server/Http/Route/Router.php | 2 +- src/Server/Http/Struct/ActionMethodItem.php | 44 +++--- src/Server/Http/SuperGlobals/Server.php | 14 +- src/Server/Session/Handler/Redis.php | 4 +- src/Server/Session/SessionConfig.php | 44 +++--- src/Server/Session/SessionCookie.php | 54 +++----- src/Server/TcpServer/Message/ReceiveData.php | 24 ++-- src/Server/TcpServer/ReceiveHandler.php | 18 +-- .../TcpServer/Route/Annotation/TcpRoute.php | 2 +- src/Server/TcpServer/Route/RouteItem.php | 22 ++- src/Server/TcpServer/Route/RouteResult.php | 22 ++- src/Server/UdpServer/Message/PacketData.php | 12 +- src/Server/UdpServer/PacketHandler.php | 18 +-- .../UdpServer/Route/Annotation/UdpRoute.php | 2 +- src/Server/UdpServer/Route/RouteItem.php | 22 ++- src/Server/UdpServer/Route/RouteResult.php | 22 ++- src/Server/View/Engine/Php.php | 2 +- src/Server/WebSocket/Message/Frame.php | 48 +++---- src/Server/WebSocket/MessageHandler.php | 18 +-- .../WebSocket/Route/Annotation/WSRoute.php | 2 +- src/Server/WebSocket/Route/RouteItem.php | 22 ++- src/Server/WebSocket/Route/RouteResult.php | 22 ++- src/Util/ArrayData.php | 16 +-- src/Util/ArrayList.php | 14 +- src/Util/ClassObject.php | 2 +- src/Util/DelayBeanCallable.php | 11 +- src/Util/DelayClassCallable.php | 11 +- src/Util/DelayServerBeanCallable.php | 11 +- src/Util/File.php | 8 +- src/Util/File/FileEnumItem.php | 22 ++- src/Util/FilterableList.php | 34 +++-- src/Util/Imi.php | 29 ++-- src/Util/Pagination.php | 22 ++- src/Util/Random.php | 10 +- src/Util/Socket/IPEndPoint.php | 24 ++-- src/Util/Stream/FileStream.php | 16 +-- src/Util/Stream/MemoryStream.php | 12 +- src/Util/Traits/TServerAnnotationParser.php | 2 +- src/Validate/ValidatorHelper.php | 31 ++--- src/functions.php | 2 +- .../Component/Bean/ReferenceBeanAspect.php | 8 +- .../Component/Db/Classes/TestTransaction.php | 4 +- tests/unit/Component/PHPUnitHook.php | 6 +- tests/unit/Component/Tests/BaseCacheTest.php | 4 +- tests/unit/Component/Tests/BaseLockTest.php | 6 +- tests/unit/Component/Tests/Db/DbBaseTest.php | 8 +- .../Component/Tests/Db/QueryCurdBaseTest.php | 4 +- .../Component/Tests/Db/TransactionTest.php | 88 ++++++------ tests/unit/Component/Tests/EventTest.php | 12 +- .../Tests/HotUpdate/BaseMonitorTest.php | 2 +- .../Component/Tests/ModelRelationTest.php | 2 +- tests/unit/Component/Tests/ModelTest.php | 4 +- .../unit/Component/Tests/RedisManagerTest.php | 2 +- .../Component/Tests/Util/DateTimeTest.php | 2 +- tests/unit/Component/test.php | 2 +- 404 files changed, 2388 insertions(+), 2902 deletions(-) create mode 100755 dev/phpstan.sh create mode 100644 dev/rector.sh create mode 100644 phpstan-baseline/baseline-access-control.neon create mode 100644 phpstan-baseline/baseline-amqp.neon create mode 100644 phpstan-baseline/baseline-apidoc.neon create mode 100644 phpstan-baseline/baseline-core.neon create mode 100644 phpstan-baseline/baseline-fpm.neon create mode 100644 phpstan-baseline/baseline-grpc.neon create mode 100644 phpstan-baseline/baseline-jwt.neon create mode 100644 phpstan-baseline/baseline-kafka.neon create mode 100644 phpstan-baseline/baseline-macro.neon create mode 100644 phpstan-baseline/baseline-mqtt.neon create mode 100644 phpstan-baseline/baseline-pgsql.neon create mode 100644 phpstan-baseline/baseline-queue.neon create mode 100644 phpstan-baseline/baseline-rate-limit.neon create mode 100644 phpstan-baseline/baseline-roadrunner.neon create mode 100644 phpstan-baseline/baseline-rpc.neon create mode 100644 phpstan-baseline/baseline-shared-memory.neon create mode 100644 phpstan-baseline/baseline-smarty.neon create mode 100644 phpstan-baseline/baseline-snowflake.neon create mode 100644 phpstan-baseline/baseline-swoole-tracker.neon create mode 100644 phpstan-baseline/baseline-swoole.neon create mode 100644 phpstan-baseline/baseline-workerman-gateway.neon create mode 100644 phpstan-baseline/baseline-workerman.neon create mode 100644 phpstan-baseline/component-baseline.php delete mode 100755 phpstan.sh delete mode 100755 rector.sh diff --git a/.gitattributes b/.gitattributes index 42de66a4a1..7a732cd04a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,8 +15,8 @@ /.markdownlint.json export-ignore /.php-cs-fixer.php export-ignore /package.json export-ignore +/phpstan-baseline export-ignore /phpstan-components.neon export-ignore /phpstan.neon export-ignore -/phpstan.sh export-ignore /rector.php export-ignore /rector.sh export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8cc776642e..520f626e2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,6 +12,10 @@ on: - "README.md" pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + jobs: ci: name: Linux Swoole-${{ matrix.swoole.version }} RoadRunner-${{ matrix.roadrunner }} diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index 59d1cd2f1d..692c502cb7 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -12,6 +12,10 @@ on: - "README.md" pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + jobs: test: runs-on: ubuntu-latest diff --git a/.github/workflows/phpcs.yml b/.github/workflows/phpcs.yml index 4616bea86c..6a712ec9ec 100644 --- a/.github/workflows/phpcs.yml +++ b/.github/workflows/phpcs.yml @@ -11,6 +11,10 @@ on: - "README.md" pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + jobs: tests: runs-on: ubuntu-20.04 diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index 614bb5e116..24b89c5d15 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -11,6 +11,10 @@ on: - "README.md" pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + jobs: tests: runs-on: ubuntu-20.04 @@ -40,114 +44,114 @@ jobs: - name: Analyse core if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G + docker exec ${ENV_SERVICE} ./dev/phpstan.sh core - name: Analyse access-control if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/access-control/vendor/autoload.php src/Components/access-control + docker exec ${ENV_SERVICE} ./dev/phpstan.sh access-control - name: Analyse amqp if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/amqp/vendor/autoload.php src/Components/amqp + docker exec ${ENV_SERVICE} ./dev/phpstan.sh amqp - name: Analyse apidoc if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/apidoc/vendor/autoload.php src/Components/apidoc + docker exec ${ENV_SERVICE} ./dev/phpstan.sh apidoc - name: Analyse fpm if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/fpm/vendor/autoload.php src/Components/fpm + docker exec ${ENV_SERVICE} ./dev/phpstan.sh fpm - name: Analyse grpc if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/grpc/vendor/autoload.php src/Components/grpc + docker exec ${ENV_SERVICE} ./dev/phpstan.sh grpc - name: Analyse jwt if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/jwt/vendor/autoload.php src/Components/jwt + docker exec ${ENV_SERVICE} ./dev/phpstan.sh jwt - name: Analyse kafka if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/kafka/vendor/autoload.php src/Components/kafka + docker exec ${ENV_SERVICE} ./dev/phpstan.sh kafka - name: Analyse mqtt if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/mqtt/vendor/autoload.php src/Components/mqtt + docker exec ${ENV_SERVICE} ./dev/phpstan.sh mqtt - name: Analyse pgsql if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/pgsql/vendor/autoload.php src/Components/pgsql + docker exec ${ENV_SERVICE} ./dev/phpstan.sh pgsql - name: Analyse queue if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/queue/vendor/autoload.php src/Components/queue + docker exec ${ENV_SERVICE} ./dev/phpstan.sh queue - name: Analyse rate-limit if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/rate-limit/vendor/autoload.php src/Components/rate-limit + docker exec ${ENV_SERVICE} ./dev/phpstan.sh rate-limit - name: Analyse roadrunner if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/roadrunner/vendor/autoload.php src/Components/roadrunner + docker exec ${ENV_SERVICE} ./dev/phpstan.sh roadrunner - name: Analyse rpc if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/rpc/vendor/autoload.php src/Components/rpc + docker exec ${ENV_SERVICE} ./dev/phpstan.sh rpc - name: Analyse shared-memory if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/shared-memory/vendor/autoload.php src/Components/shared-memory + docker exec ${ENV_SERVICE} ./dev/phpstan.sh shared-memory - name: Analyse smarty if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/smarty/vendor/autoload.php src/Components/smarty + docker exec ${ENV_SERVICE} ./dev/phpstan.sh smarty - name: Analyse snowflake if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/snowflake/vendor/autoload.php src/Components/snowflake + docker exec ${ENV_SERVICE} ./dev/phpstan.sh snowflake - name: Analyse swoole if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/swoole/vendor/autoload.php src/Components/swoole + docker exec ${ENV_SERVICE} ./dev/phpstan.sh swoole - name: Analyse swoole-tracker if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/swoole-tracker/vendor/autoload.php src/Components/swoole-tracker + docker exec ${ENV_SERVICE} ./dev/phpstan.sh swoole-tracker - name: Analyse workerman if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/workerman/vendor/autoload.php src/Components/workerman + docker exec ${ENV_SERVICE} ./dev/phpstan.sh workerman - name: Analyse workerman-gateway if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/workerman-gateway/vendor/autoload.php src/Components/workerman-gateway + docker exec ${ENV_SERVICE} ./dev/phpstan.sh workerman-gateway - name: Analyse macro if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/macro/vendor/autoload.php src/Components/macro + docker exec ${ENV_SERVICE} ./dev/phpstan.sh macro - name: Analyse phar if: ${{ env.test_prepared && always() }} run: | - docker exec ${ENV_SERVICE} ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/phar/vendor/autoload.php src/Components/phar + docker exec ${ENV_SERVICE} ./dev/phpstan.sh phar diff --git a/.github/workflows/rector.yml b/.github/workflows/rector.yml index 1a397f2415..9e15802734 100644 --- a/.github/workflows/rector.yml +++ b/.github/workflows/rector.yml @@ -11,6 +11,10 @@ on: - "README.md" pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.ref || github.run_id }} + cancel-in-progress: true + jobs: tests: runs-on: ubuntu-20.04 diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index ab6697acfd..9fe2ee3e6b 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -9,8 +9,8 @@ return (new PhpCsFixer\Config()) ->setRules([ - '@PHP74Migration' => true, - '@PHP74Migration:risky' => true, + '@PHP81Migration' => true, + '@PHP80Migration:risky' => true, '@Symfony' => true, '@Symfony:risky' => true, '@DoctrineAnnotation' => true, @@ -116,7 +116,6 @@ 'return_assignment' => true, 'explicit_string_variable' => true, 'heredoc_to_nowdoc' => true, - 'void_return' => false, // BUG:https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/6690 // Symfony 冲突 'braces_position' => [ 'control_structures_opening_brace' => 'next_line_unless_newline_at_signature_end', @@ -128,8 +127,6 @@ 'remove_inheritdoc' => false, ], 'no_null_property_initialization' => false, - // 当支持 php>=8.0 后改配置可以移除 - 'get_class_to_class_keyword' => false, ]) ->setRiskyAllowed(true) ->setFinder( diff --git a/composer.json b/composer.json index 4b2824ed6a..4f66a17531 100644 --- a/composer.json +++ b/composer.json @@ -25,9 +25,9 @@ "require-dev": { "composer/semver": "^3.3.2", "php-cs-fixer/shim": "~3.35.1", - "phpstan/phpstan": "~1.8.0", + "phpstan/phpstan": "~1.10.39", "phpunit/phpunit": "~9.6", - "rector/rector": "~0.13", + "rector/rector": "~0.18.5", "symfony/polyfill-uuid": "^1.27", "yurunsoft/ide-helper": "~1.0", "yurunsoft/yurun-http": "^5.0.0" diff --git a/dev/Plugin.php b/dev/Plugin.php index bb2746466b..8d76444f53 100644 --- a/dev/Plugin.php +++ b/dev/Plugin.php @@ -63,7 +63,7 @@ public static function IDEHelper(): void '--app-namespace=Imi\\\\Dev', ]; $process = self::createProcess($cmd); - $process->run(static function ($type, $buffer) { + $process->run(static function ($type, $buffer): void { echo $buffer; }); @@ -105,7 +105,7 @@ protected static function parallel(array $processes, int $max, string $titleTemp { ++$running; $output->writeln("[{$title}]"); - $process->start(static function ($type, $buffer) { + $process->start(static function ($type, $buffer): void { echo $buffer; }); } diff --git a/dev/bootstrap.php b/dev/bootstrap.php index 7bd58d1db1..b065eb66c0 100644 --- a/dev/bootstrap.php +++ b/dev/bootstrap.php @@ -52,7 +52,11 @@ function getRectorConfigCallback(string $path): callable \Rector\Php71\Rector\FuncCall\CountOnNullRector::class, \Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector::class, \Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector::class, - \Rector\Php70\Rector\FuncCall\RandomFunctionRector::class, + + // 存在兼容问题 + \Rector\Php80\Rector\FunctionLike\MixedTypeRector::class, // todo 给接口参数加了`mixed`但没给实现加类型,导致静态分析报错 + \Rector\CodeQuality\Rector\ClassMethod\OptionalParametersAfterRequiredRector::class, // todo 调整包含默认参的参数顺序,会导致代码被破坏 + \Rector\Php81\Rector\ClassConst\FinalizePublicClassConstantRector::class, // 无法正确处理继承覆盖的情况 ]); $rectorConfig->bootstrapFiles([ @@ -63,7 +67,7 @@ function getRectorConfigCallback(string $path): callable $path . '/src', ]); - $rectorConfig->sets([LevelSetList::UP_TO_PHP_74]); + $rectorConfig->sets([LevelSetList::UP_TO_PHP_81]); }; } @@ -167,7 +171,7 @@ function checkPorts(array $ports, string $host = '127.0.0.1', int $tryCount = 30 if (isCodeCoverage()) { putenv('IMI_CODE_COVERAGE_NAME=' . getCodeCoverageName()); - (static function () { + (static function (): void { $filter = new Filter(); $filter->includeDirectory(\dirname(__DIR__) . '/src'); $componentsDir = \dirname(__DIR__) . '/src/Components'; @@ -185,7 +189,7 @@ function checkPorts(array $ports, string $host = '127.0.0.1', int $tryCount = 30 $codeCoverage->start('imi'); $stoped = false; - $shutdownCallback = static function () use ($codeCoverage, &$stoped) { + $shutdownCallback = static function () use ($codeCoverage, &$stoped): void { if (!$stoped) { $stoped = true; diff --git a/dev/phpstan.sh b/dev/phpstan.sh new file mode 100755 index 0000000000..079234356b --- /dev/null +++ b/dev/phpstan.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +__DIR__=$(cd `dirname $0`; pwd) +cd "$__DIR__/.." +__DIR__=$(pwd) + +components=( +# "core" 默认不处理 + "access-control" + "amqp" + "apidoc" + "fpm" + "grpc" + "jwt" + "kafka" + "mqtt" + "pgsql" + "queue" + "rate-limit" + "roadrunner" + "rpc" + "shared-memory" + "smarty" + "snowflake" + "swoole" + "swoole-tracker" + "workerman" + "workerman-gateway" + "macro" +) + +analyze_component() { + component="$1" + gen_baseline="$2" + echo "Analyzing: $component, Generate Baseline: $gen_baseline" + + analyse_configuration="" + + args=() + args+=("--memory-limit" "1G") + + if [ "$component" != "core" ]; then + args+=("--configuration=phpstan-components.neon" "--autoload-file=src/Components/$component/vendor/autoload.php" "src/Components/$component") + fi + + if [ "$gen_baseline" == "true" ]; then + args+=("--generate-baseline=./phpstan-baseline/baseline-$component.neon" "--allow-empty-baseline") + fi + + echo ./vendor/bin/phpstan analyse "${args[@]}" + + PHPSTAN_ANALYSE_COMPONENT_NAME="$component" PHPSTAN_GENERATE_BASELINE="$gen_baseline" ./vendor/bin/phpstan analyse "${args[@]}" +} + +use_baseline="false" +input_components=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --baseline) + use_baseline="true" + shift + ;; + -b) + use_baseline="true" + shift + ;; + *) + # 如果不是 --baseline 标志,将参数添加到 components 数组中 + input_components+=("$1") + shift + ;; + esac +done + +if [ ${#input_components[@]} -eq 0 ]; then + # If no arguments are provided, analyze all components + for component in "${components[@]}"; do + analyze_component "$component" "$use_baseline" + done +else + # Analyze the specified components provided as arguments + for component in "${input_components[@]}"; do + if [[ " ${components[@]} " =~ " $component " || "core" == "$component" ]]; then + analyze_component "$component" "$use_baseline" + else + echo "Invalid component name: $component" + fi + done +fi \ No newline at end of file diff --git a/dev/rector.sh b/dev/rector.sh new file mode 100644 index 0000000000..c0ef54c3df --- /dev/null +++ b/dev/rector.sh @@ -0,0 +1,91 @@ +#!/bin/bash + +__DIR__=$(cd `dirname $0`; pwd) +cd "$__DIR__/.." +__DIR__=$(pwd) + +components=( +# "core" 默认不处理 + "access-control" + "amqp" + "apidoc" + "fpm" + "grpc" + "jwt" + "kafka" + "mqtt" + "pgsql" + "queue" + "rate-limit" + "roadrunner" + "rpc" + "shared-memory" + "smarty" + "snowflake" + "swoole" + "swoole-tracker" + "workerman" + "workerman-gateway" + "macro" +) + +analyze_component() { + component="$1" + use_dry_run="$2" + original_dir=$(pwd) + echo "process: $component, dry-run: $use_dry_run" + + analyse_configuration="" + + args=() + + if [ "$component" != "core" ]; then + cd "$__DIR__/src/Components/$component" + fi + + if [ "$use_dry_run" == "true" ]; then + args+=("--dry-run") + fi + + "$__DIR__/vendor/bin/rector" process "${args[@]}" + + cd "$original_dir" + sleep 1 +} + +use_dry_run="false" +input_components=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --dry-run) + use_dry_run="true" + shift + ;; + -n) + use_dry_run="true" + shift + ;; + *) + # 如果不是 --dry-run 标志,将参数添加到 components 数组中 + input_components+=("$1") + shift + ;; + esac +done + +if [ ${#input_components[@]} -eq 0 ]; then + # If no arguments are provided, analyze all components + for component in "${components[@]}"; do + analyze_component "$component" "$use_dry_run" + done +else + # Analyze the specified components provided as arguments + for component in "${input_components[@]}"; do + if [[ " ${components[@]} " =~ " $component " || "core" == "$component" ]]; then + analyze_component "$component" "$use_dry_run" + else + echo "Invalid component name: $component" + fi + done +fi \ No newline at end of file diff --git a/dev/try-include-swoole.php b/dev/try-include-swoole.php index 5192cbdb0e..e7b65d2e62 100644 --- a/dev/try-include-swoole.php +++ b/dev/try-include-swoole.php @@ -2,7 +2,7 @@ declare(strict_types=1); -(static function () { +(static function (): void { $file = \dirname(__DIR__) . '/src/Components/swoole/vendor/autoload.php'; if (is_file($file)) { diff --git a/phpstan-baseline/baseline-access-control.neon b/phpstan-baseline/baseline-access-control.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-access-control.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-amqp.neon b/phpstan-baseline/baseline-amqp.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-amqp.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-apidoc.neon b/phpstan-baseline/baseline-apidoc.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-apidoc.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-core.neon b/phpstan-baseline/baseline-core.neon new file mode 100644 index 0000000000..d68cd7d262 --- /dev/null +++ b/phpstan-baseline/baseline-core.neon @@ -0,0 +1,51 @@ +parameters: + ignoreErrors: + - + message: "#^Cannot access constant class on array\\\\|Imi\\\\Bean\\\\Annotation\\\\Base\\.$#" + count: 1 + path: ../src/Bean/AnnotationParser.php + + - + message: "#^Creating callable from a non\\-native method Imi\\\\Redis\\\\RedisHandler\\:\\:_serialize\\(\\)\\.$#" + count: 4 + path: ../src/Cache/Handler/RedisHash.php + + - + message: "#^If condition is always false\\.$#" + count: 3 + path: ../src/Db/Query/Query.php + + - + message: "#^Argument of an invalid type ArrayAccess supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: ../src/Model/Model.php + + - + message: "#^Left side of && is always true\\.$#" + count: 1 + path: ../src/Model/Model.php + + - + message: "#^PHPDoc tag @return with type T\\|null is not subtype of native type Imi\\\\Bean\\\\Annotation\\\\Base\\|null\\.$#" + count: 1 + path: ../src/Model/ModelManager.php + + - + message: "#^Parameter \\#2 \\$class of static method Imi\\\\Server\\\\ServerManager\\:\\:getServer\\(\\) expects class\\-string\\\\|null, string given\\.$#" + count: 1 + path: ../src/Server/Group/Listener/GroupRestore.php + + - + message: "#^Method Imi\\\\Test\\\\Component\\\\Model\\\\Article\\:\\:getQueryRelationsList\\(\\) should return Imi\\\\Test\\\\Component\\\\Model\\\\Article\\|null but returns Imi\\\\Test\\\\Component\\\\Model\\\\ArticleEx\\|null\\.$#" + count: 1 + path: ../tests/unit/Component/Model/Article.php + + - + message: "#^Property Imi\\\\Test\\\\Component\\\\Model\\\\Article\\:\\:\\$queryRelationsList \\(Imi\\\\Test\\\\Component\\\\Model\\\\ArticleEx\\|null\\) does not accept Imi\\\\Test\\\\Component\\\\Model\\\\Article\\|null\\.$#" + count: 1 + path: ../tests/unit/Component/Model/Article.php + + - + message: "#^Argument of an invalid type Imi\\\\Util\\\\ArrayData supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: ../tests/unit/Component/Tests/Util/ArrayDataTest.php diff --git a/phpstan-baseline/baseline-fpm.neon b/phpstan-baseline/baseline-fpm.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-fpm.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-grpc.neon b/phpstan-baseline/baseline-grpc.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-grpc.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-jwt.neon b/phpstan-baseline/baseline-jwt.neon new file mode 100644 index 0000000000..3505a844e0 --- /dev/null +++ b/phpstan-baseline/baseline-jwt.neon @@ -0,0 +1,126 @@ +parameters: + ignoreErrors: + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:claims\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Aop/JWTValidationAop.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:getClaim\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Aop/JWTValidationAop.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Builder\\:\\:sign\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:validate\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:verify\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to method setAudience\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to method setId\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to method setIssuer\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to method setSubject\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Cannot instantiate interface Lcobucci\\\\JWT\\\\Builder\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Cannot instantiate interface Lcobucci\\\\JWT\\\\Parser\\.$#" + count: 2 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Instantiated class Lcobucci\\\\JWT\\\\ValidationData not found\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Builder\\:\\:sign\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:validate\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:verify\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to method setAudience\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to method setId\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to method setIssuer\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to method setSubject\\(\\) on an unknown class Lcobucci\\\\JWT\\\\ValidationData\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Cannot instantiate interface Lcobucci\\\\JWT\\\\Builder\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Cannot instantiate interface Lcobucci\\\\JWT\\\\Parser\\.$#" + count: 2 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Instantiated class Lcobucci\\\\JWT\\\\ValidationData not found\\.$#" + count: 1 + path: ../src/Components/jwt/src/Bean/JWT.php.macro.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:claims\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/tests/Unit/JWTTest.php + + - + message: "#^Call to an undefined method Lcobucci\\\\JWT\\\\Token\\:\\:getClaim\\(\\)\\.$#" + count: 1 + path: ../src/Components/jwt/tests/Unit/JWTTest.php + + - + message: "#^Parameter \\#1 \\$expiration of method Lcobucci\\\\JWT\\\\Builder\\:\\:expiresAt\\(\\) expects DateTimeImmutable, int given\\.$#" + count: 1 + path: ../src/Components/jwt/tests/Unit/JWTTest.php diff --git a/phpstan-baseline/baseline-kafka.neon b/phpstan-baseline/baseline-kafka.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-kafka.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-macro.neon b/phpstan-baseline/baseline-macro.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-macro.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-mqtt.neon b/phpstan-baseline/baseline-mqtt.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-mqtt.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-pgsql.neon b/phpstan-baseline/baseline-pgsql.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-pgsql.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-queue.neon b/phpstan-baseline/baseline-queue.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-queue.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-rate-limit.neon b/phpstan-baseline/baseline-rate-limit.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-rate-limit.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-roadrunner.neon b/phpstan-baseline/baseline-roadrunner.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-roadrunner.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-rpc.neon b/phpstan-baseline/baseline-rpc.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-rpc.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-shared-memory.neon b/phpstan-baseline/baseline-shared-memory.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-shared-memory.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-smarty.neon b/phpstan-baseline/baseline-smarty.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-smarty.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-snowflake.neon b/phpstan-baseline/baseline-snowflake.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-snowflake.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-swoole-tracker.neon b/phpstan-baseline/baseline-swoole-tracker.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-swoole-tracker.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-swoole.neon b/phpstan-baseline/baseline-swoole.neon new file mode 100644 index 0000000000..660107fac8 --- /dev/null +++ b/phpstan-baseline/baseline-swoole.neon @@ -0,0 +1,21 @@ +parameters: + ignoreErrors: + - + message: "#^Method Imi\\\\Swoole\\\\Util\\\\Coroutine\\:\\:__create\\(\\) never returns bool so it can be removed from the return type\\.$#" + count: 1 + path: ../src/Components/swoole/src/Util/Coroutine.typed.php + + - + message: "#^Offset 'class' on array\\{class\\: \\*NEVER\\*\\} in isset\\(\\) always exists and is always null\\.$#" + count: 1 + path: ../src/Components/swoole/src/Util/MemoryTableManager.php + + - + message: "#^Offset 'conflictProportion' on array\\{class\\: \\*NEVER\\*\\} on left side of \\?\\? does not exist\\.$#" + count: 1 + path: ../src/Components/swoole/src/Util/MemoryTableManager.php + + - + message: "#^Offset 'size' on array\\{class\\: \\*NEVER\\*\\} on left side of \\?\\? does not exist\\.$#" + count: 1 + path: ../src/Components/swoole/src/Util/MemoryTableManager.php diff --git a/phpstan-baseline/baseline-workerman-gateway.neon b/phpstan-baseline/baseline-workerman-gateway.neon new file mode 100644 index 0000000000..aab4991158 --- /dev/null +++ b/phpstan-baseline/baseline-workerman-gateway.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/phpstan-baseline/baseline-workerman.neon b/phpstan-baseline/baseline-workerman.neon new file mode 100644 index 0000000000..f80ba54656 --- /dev/null +++ b/phpstan-baseline/baseline-workerman.neon @@ -0,0 +1,6 @@ +parameters: + ignoreErrors: + - + message: "#^Binary operation \"\\+\\=\" between int\\<4, max\\> and string results in an error\\.$#" + count: 1 + path: ../src/Components/workerman/src/Server/Protocol/WorkermanHttp.php diff --git a/phpstan-baseline/component-baseline.php b/phpstan-baseline/component-baseline.php new file mode 100644 index 0000000000..4275fd701b --- /dev/null +++ b/phpstan-baseline/component-baseline.php @@ -0,0 +1,26 @@ +load($file); diff --git a/phpstan-components.neon b/phpstan-components.neon index 094c06c0a6..f3e06e0265 100644 --- a/phpstan-components.neon +++ b/phpstan-components.neon @@ -23,31 +23,22 @@ parameters: reportUnmatchedIgnoredErrors: false ignoreErrors: - - '#is never read, only written#' - - '#expects class-string<\S+>, string given#' - - '#Unable to resolve the template type T in call to method#' - - '#Access to an undefined property Imi\\Util\\LazyArrayObject::\$[^.]+.#' - - '#Access to an undefined property Imi\\Util\\ArrayData::\$[^.]+.#' - - '#Unsafe usage of new static\(\).+#' - - '#Argument of an invalid type Imi\\Util\\ArrayData supplied for foreach, only iterables are supported.#' - - '#Argument of an invalid type ArrayAccess supplied for foreach, only iterables are supported.#' - - '#Property GPBMetadata\\Grpc::\$\S+ has no typehint specified.#' - - '#Property Grpc\\[^:]+::\$\S+ has no typehint specified.#' - - '#Method GPBMetadata\\Grpc::initOnce\(\) has no return typehint specified.#' - - '#PHPDoc tag @throws with type \S+ is not subtype of Throwable#' - - '#Constant IMI_PATH not found.#' - - '#Swoole\\Coroutine\\\S+ not found#' - - message: '#Method \S+ has no return typehint specified.#' - paths: - - tests/unit/**Test.php + message: '#expects class-string<\S+>, string given#' + reportUnmatched: false - - message: '#class .+ not found#' - paths: - - src/Components/jwt/* + message: '#Unable to resolve the template type T in call to method#' + reportUnmatched: false - - message: '#Lcobucci#' - paths: - - src/Components/jwt/* + message: "#^Unsafe usage of new static\\(\\)\\.$#" + reportUnmatched: false + - + message: '#Swoole\\Coroutine\\\S+ not found#' + reportUnmatched: false + - + message: '#^Call to an undefined method Swoole\\Coroutine\\#' + reportUnmatched: false services: +includes: + - phpstan-baseline/component-baseline.php \ No newline at end of file diff --git a/phpstan.neon b/phpstan.neon index d1d94bed6e..717f845163 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -21,32 +21,35 @@ parameters: - vendor/autoload.php - split-repository/vendor/autoload.php - treatPhpDocTypesAsCertain: false +# treatPhpDocTypesAsCertain: false checkGenericClassInNonGenericObjectType: false checkMissingIterableValueType: false reportUnmatchedIgnoredErrors: false ignoreErrors: - - '#is never read, only written#' - - '#expects class-string<\S+>, string given#' - - '#Unable to resolve the template type T in call to method#' - - '#PHPDoc tag @return with type T\|null is not subtype of native type#' - - '#expects class-string<.+>|null, string given#' - - '#Access to an undefined property Imi\\Util\\LazyArrayObject::\$[^.]+.#' - - '#Access to an undefined property Imi\\Util\\ArrayData::\$[^.]+.#' - - '#Unsafe usage of new static\(\).+#' - - '#Argument of an invalid type Imi\\Util\\ArrayData supplied for foreach, only iterables are supported.#' - - '#Argument of an invalid type ArrayAccess supplied for foreach, only iterables are supported.#' - - '#PHPDoc tag @throws with type \S+ is not subtype of Throwable#' - - '#Imi\\Swoole\\Util\\Coroutine#' - - '#Imi\\Swoole\\Process\\Process#' - - '#IMI_PATH#' - - message: '#Method \S+ has no return typehint specified.#' - paths: - - tests/unit/**Test.php + message: '#expects class-string<\S+>, string given#' + reportUnmatched: true - - message: '#(Extending|Creating new|Calling) \S+ is not covered by backward compatibility promise\. The (class|method) might change in a minor PHPStan version\.#' - paths: - - dev/PHPStan/FileFinder.php + message: '#Unable to resolve the template type T in call to method#' + reportUnmatched: true + - + message: '#Access to an undefined property Imi\\Util\\LazyArrayObject::\$[^.]+.#' + path: 'tests/unit/Component/Tests/*' + reportUnmatched: true + - + message: '#Access to an undefined property Imi\\Util\\ArrayData::\$[^.]+.#' + path: 'tests/unit/Component/Tests/*' + reportUnmatched: true + - + message: '#Unsafe usage of new static\(\).+#' + reportUnmatched: true + - + message: '#unknown class Imi\\Swoole\\Util\\Coroutine#' + reportUnmatched: true + - + message: '#Constant IMI_PATH not found#' + reportUnmatched: true services: +includes: + - phpstan-baseline/baseline-core.neon \ No newline at end of file diff --git a/phpstan.sh b/phpstan.sh deleted file mode 100755 index 4b104d8031..0000000000 --- a/phpstan.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -__DIR__=$(cd `dirname $0`; pwd) -cd $__DIR__ - -echo "core" && ./vendor/bin/phpstan analyse --memory-limit 1G - -echo "access-control" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/access-control/vendor/autoload.php src/Components/access-control - -echo "amqp" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/amqp/vendor/autoload.php src/Components/amqp - -echo "apidoc" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/apidoc/vendor/autoload.php src/Components/apidoc - -echo "fpm" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/fpm/vendor/autoload.php src/Components/fpm - -echo "grpc" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/grpc/vendor/autoload.php src/Components/grpc - -echo "jwt" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/jwt/vendor/autoload.php src/Components/jwt - -echo "kafka" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/kafka/vendor/autoload.php src/Components/kafka - -echo "mqtt" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/mqtt/vendor/autoload.php src/Components/mqtt - -echo "pgsql" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/pgsql/vendor/autoload.php src/Components/pgsql - -echo "queue" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/queue/vendor/autoload.php src/Components/queue - -echo "rate-limit" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/rate-limit/vendor/autoload.php src/Components/rate-limit - -echo "roadrunner" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/roadrunner/vendor/autoload.php src/Components/roadrunner - -echo "rpc" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/rpc/vendor/autoload.php src/Components/rpc - -echo "shared-memory" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/shared-memory/vendor/autoload.php src/Components/shared-memory - -echo "smarty" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/smarty/vendor/autoload.php src/Components/smarty - -echo "snowflake" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/snowflake/vendor/autoload.php src/Components/snowflake - -echo "swoole" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/swoole/vendor/autoload.php src/Components/swoole - -echo "swoole-tracker" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/swoole-tracker/vendor/autoload.php src/Components/swoole-tracker - -echo "workerman" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/workerman/vendor/autoload.php src/Components/workerman - -echo "workerman-gateway" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/workerman-gateway/vendor/autoload.php src/Components/workerman-gateway - -echo "macro" && ./vendor/bin/phpstan analyse --memory-limit 1G --configuration=phpstan-components.neon --autoload-file=src/Components/macro/vendor/autoload.php src/Components/macro diff --git a/rector.sh b/rector.sh deleted file mode 100755 index c6473da6f4..0000000000 --- a/rector.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -__DIR__=$(cd `dirname $0`; pwd) - -cd $__DIR__ && echo "core" && ./vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/access-control && echo "access-control" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/amqp && echo "amqp" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/apidoc && echo "apidoc" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/fpm && echo "fpm" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/grpc && echo "grpc" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/jwt && echo "jwt" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/kafka && echo "kafka" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/mqtt && echo "mqtt" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/pgsql && echo "pgsql" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/queue && echo "queue" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/rate-limit && echo "rate-limit" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/roadrunner && echo "roadrunner" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/rpc && echo "rpc" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/shared-memory && echo "shared-memory" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/smarty && echo "smarty" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/snowflake && echo "snowflake" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/swoole && echo "swoole" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/swoole-tracker && echo "swoole-tracker" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/workerman && echo "workerman" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/workerman-gateway && echo "workerman-gateway" && ../../../vendor/bin/rector process --dry-run -cd $__DIR__/src/Components/macro && echo "macro" && ../../../vendor/bin/rector process --dry-run \ No newline at end of file diff --git a/split-repository/split.php b/split-repository/split.php index 2850b70beb..6b2c929a1c 100644 --- a/split-repository/split.php +++ b/split-repository/split.php @@ -283,7 +283,7 @@ function saveConfig(): void $dir = \dirname($repoFilePath); if (!is_dir($dir)) { - mkdir($dir, 0777, true); + mkdir($dir, 0o777, true); } file_put_contents($repoFilePath, file_get_contents($originFileName)); chdir($repoPath); diff --git a/src/Aop/AfterThrowingJoinPoint.php b/src/Aop/AfterThrowingJoinPoint.php index 4b7bf898e2..77932ebf2f 100644 --- a/src/Aop/AfterThrowingJoinPoint.php +++ b/src/Aop/AfterThrowingJoinPoint.php @@ -6,20 +6,18 @@ class AfterThrowingJoinPoint extends JoinPoint { - /** - * 异常. - */ - private ?\Throwable $throwable = null; - /** * 是否取消抛出异常. */ private bool $isCancelThrow = false; - public function __construct(string $type, string $method, array &$args, object $target, \Throwable $throwable) + public function __construct(string $type, string $method, array &$args, object $target, + /** + * 异常. + */ + private readonly ?\Throwable $throwable) { parent::__construct($type, $method, $args, $target); - $this->throwable = $throwable; } /** diff --git a/src/Aop/AopAnnotationLoader.php b/src/Aop/AopAnnotationLoader.php index 58fb3e808e..f775b75912 100644 --- a/src/Aop/AopAnnotationLoader.php +++ b/src/Aop/AopAnnotationLoader.php @@ -69,7 +69,7 @@ public static function load(bool $force = true): void } else { - [$class, $method] = explode('::', $allowItem); + [$class, $method] = explode('::', (string) $allowItem); } if ($beforeAnnotation) { diff --git a/src/Aop/JoinPoint.php b/src/Aop/JoinPoint.php index 42cc30ace1..2ba584a1f2 100644 --- a/src/Aop/JoinPoint.php +++ b/src/Aop/JoinPoint.php @@ -6,32 +6,26 @@ class JoinPoint { - /** - * 切入点类型. - */ - protected string $type = ''; - - /** - * 获取切入的方法名. - */ - protected string $method = ''; - /** * 方法调用参数. */ protected array $args = []; - /** - * 连接点所在的目标对象 - */ - protected ?object $target = null; - - public function __construct(string $type, string $method, array &$args, object $target) + public function __construct( + /** + * 切入点类型. + */ + protected string $type, + /** + * 获取切入的方法名. + */ + protected string $method, array &$args, + /** + * 连接点所在的目标对象 + */ + protected ?object $target) { - $this->type = $type; - $this->method = $method; $this->args = &$args; - $this->target = $target; } /** diff --git a/src/Aop/Listener/ImiInit.php b/src/Aop/Listener/ImiInit.php index 1c45ecfe81..18d8d50545 100644 --- a/src/Aop/Listener/ImiInit.php +++ b/src/Aop/Listener/ImiInit.php @@ -53,7 +53,7 @@ private function parseConfigs(array $configs): void } else { - $annotationClassName = '\Imi\Aop\Annotation\\' . ucfirst($annotationName); + $annotationClassName = '\Imi\Aop\Annotation\\' . ucfirst((string) $annotationName); } $annotations[] = new $annotationClassName($annotationArgs); } @@ -72,7 +72,7 @@ private function parseConfigs(array $configs): void } else { - $annotationClassName = '\Imi\Aop\Annotation\\' . ucfirst($annotationName); + $annotationClassName = '\Imi\Aop\Annotation\\' . ucfirst((string) $annotationName); } $annotations[] = new $annotationClassName($annotationArgs); } diff --git a/src/Aop/Model/AopItem.php b/src/Aop/Model/AopItem.php index 46959a0023..9064089b22 100644 --- a/src/Aop/Model/AopItem.php +++ b/src/Aop/Model/AopItem.php @@ -6,26 +6,14 @@ class AopItem { - private string $class = ''; - - private string $methodRule = ''; - /** * @var callable */ private $callback; - private int $priority = 0; - - private array $options = []; - - public function __construct(string $class, string $methodRule, callable $callback, int $priority = 0, array $options = []) + public function __construct(private readonly string $class, private readonly string $methodRule, callable $callback, private readonly int $priority = 0, private readonly array $options = []) { - $this->class = $class; - $this->methodRule = $methodRule; $this->callback = $callback; - $this->priority = $priority; - $this->options = $options; } public function getClass(): string diff --git a/src/Async/AsyncResult.php b/src/Async/AsyncResult.php index 4f3d2a58ac..4edfbe3b6a 100644 --- a/src/Async/AsyncResult.php +++ b/src/Async/AsyncResult.php @@ -9,22 +9,13 @@ class AsyncResult implements IAsyncResult { - /** - * @var mixed - */ - private $result; - - private bool $isException = false; - private bool $isGeted = false; /** * @param mixed $result */ - public function __construct($result = null, bool $isException = false) + public function __construct(private $result = null, private readonly bool $isException = false) { - $this->result = $result; - $this->isException = $isException; } public function __destruct() diff --git a/src/Bean/Annotation.php b/src/Bean/Annotation.php index 11a370f884..bc0dc2d176 100644 --- a/src/Bean/Annotation.php +++ b/src/Bean/Annotation.php @@ -112,7 +112,7 @@ private function loadModuleAnnotations(string $namespace, bool $isApp = false): } $ignoredPaths = array_merge($ignoredPaths, $config['appIgnorePaths'] ?? []); } - $ignoredPaths = array_map([Imi::class, 'parseRule'], $ignoredPaths); + $ignoredPaths = array_map(Imi::parseRule(...), $ignoredPaths); $pathPattern = '/^(?!((' . implode(')|(', $ignoredPaths) . ')))/'; if ($ignoredNamespaces) { @@ -128,7 +128,7 @@ private function loadModuleAnnotations(string $namespace, bool $isApp = false): $pattern = null; } $parser = $this->parser; - $this->loader->loadModuleAnnotations($namespace, static function (string $fileNamespace, string $fileName) use ($pattern, $parser) { + $this->loader->loadModuleAnnotations($namespace, static function (string $fileNamespace, string $fileName) use ($pattern, $parser): void { if ($pattern && 1 === preg_match($pattern, $fileNamespace)) { return; @@ -147,7 +147,7 @@ private function loadModuleAnnotations(string $namespace, bool $isApp = false): */ public static function toComments(Annotation\Base $annotation, bool $skipDefaultValue = true): string { - $result = '@' . Imi::getClassShortName(\get_class($annotation)); + $result = '@' . Imi::getClassShortName($annotation::class); $properties = []; if ($skipDefaultValue) { diff --git a/src/Bean/Annotation/Model/AnnotationRelation.php b/src/Bean/Annotation/Model/AnnotationRelation.php index 716b37f76f..0fe1b84782 100644 --- a/src/Bean/Annotation/Model/AnnotationRelation.php +++ b/src/Bean/Annotation/Model/AnnotationRelation.php @@ -105,7 +105,7 @@ public function getClassRelations(): array public function addClassRelation(ClassAnnotationRelation $relation): void { $annotation = $relation->getAnnotation(); - $class = \get_class($annotation); + $class = $annotation::class; if (!isset($this->classRelations[$class]) && isset($this->cache['classRelations'][$class])) { $this->classRelations[$class] = unserialize($this->cache['classRelations'][$class]); @@ -137,7 +137,7 @@ public function getMethodRelations(): array public function addMethodRelation(MethodAnnotationRelation $relation): void { $annotation = $relation->getAnnotation(); - $class = \get_class($annotation); + $class = $annotation::class; if (!isset($this->methodRelations[$class]) && isset($this->cache['methodRelations'][$class])) { $this->methodRelations[$class] = unserialize($this->cache['methodRelations'][$class]); @@ -169,7 +169,7 @@ public function getpropertyRelations(): array public function addPropertyRelation(PropertyAnnotationRelation $relation): void { $annotation = $relation->getAnnotation(); - $class = \get_class($annotation); + $class = $annotation::class; if (!isset($this->propertyRelations[$class]) && isset($this->cache['propertyRelations'][$class])) { $this->propertyRelations[$class] = unserialize($this->cache['propertyRelations'][$class]); @@ -201,7 +201,7 @@ public function getConstantRelations(): array public function addConstantRelation(ConstantAnnotationRelation $relation): void { $annotation = $relation->getAnnotation(); - $class = \get_class($annotation); + $class = $annotation::class; if (!isset($this->constantRelations[$class]) && isset($this->cache['constantRelations'][$class])) { $this->constantRelations[$class] = unserialize($this->cache['constantRelations'][$class]); diff --git a/src/Bean/Annotation/Model/ClassAnnotation.php b/src/Bean/Annotation/Model/ClassAnnotation.php index 8040eb6499..295077ec5e 100644 --- a/src/Bean/Annotation/Model/ClassAnnotation.php +++ b/src/Bean/Annotation/Model/ClassAnnotation.php @@ -6,11 +6,6 @@ class ClassAnnotation { - /** - * 类名. - */ - private string $className = ''; - /** * 类注解列表. * @@ -46,9 +41,12 @@ class ClassAnnotation */ private array $methodParameterAnnotations = []; - public function __construct(string $className) - { - $this->className = $className; + public function __construct( + /** + * 类名. + */ + private readonly string $className + ) { } /** diff --git a/src/Bean/Annotation/Model/ClassAnnotationRelation.php b/src/Bean/Annotation/Model/ClassAnnotationRelation.php index a7126f7dbe..d053c3bb77 100644 --- a/src/Bean/Annotation/Model/ClassAnnotationRelation.php +++ b/src/Bean/Annotation/Model/ClassAnnotationRelation.php @@ -8,20 +8,16 @@ class ClassAnnotationRelation implements IAnnotationRelation { - /** - * 类名. - */ - private string $class = ''; - - /** - * 注解. - */ - private ?Base $annotation = null; - - public function __construct(string $class, Base $annotation) - { - $this->class = $class; - $this->annotation = $annotation; + public function __construct( + /** + * 类名. + */ + private readonly string $class, + /** + * 注解. + */ + private readonly ?Base $annotation + ) { } /** diff --git a/src/Bean/Annotation/Model/ConstantAnnotationRelation.php b/src/Bean/Annotation/Model/ConstantAnnotationRelation.php index 347e56ff2b..41ef0e2dd3 100644 --- a/src/Bean/Annotation/Model/ConstantAnnotationRelation.php +++ b/src/Bean/Annotation/Model/ConstantAnnotationRelation.php @@ -8,26 +8,20 @@ class ConstantAnnotationRelation implements IAnnotationRelation { - /** - * 类名. - */ - private string $class = ''; - - /** - * 常量名. - */ - private string $constant = ''; - - /** - * 注解. - */ - private ?Base $annotation = null; - - public function __construct(string $class, string $constant, Base $annotation) - { - $this->class = $class; - $this->constant = $constant; - $this->annotation = $annotation; + public function __construct( + /** + * 类名. + */ + private readonly string $class, + /** + * 常量名. + */ + private readonly string $constant, + /** + * 注解. + */ + private readonly ?Base $annotation + ) { } /** diff --git a/src/Bean/Annotation/Model/MethodAnnotationRelation.php b/src/Bean/Annotation/Model/MethodAnnotationRelation.php index 0265918dc5..f176788d9e 100644 --- a/src/Bean/Annotation/Model/MethodAnnotationRelation.php +++ b/src/Bean/Annotation/Model/MethodAnnotationRelation.php @@ -8,26 +8,20 @@ class MethodAnnotationRelation implements IAnnotationRelation { - /** - * 类名. - */ - private string $class = ''; - - /** - * 方法名. - */ - private string $method = ''; - - /** - * 注解. - */ - private ?Base $annotation = null; - - public function __construct(string $class, string $method, Base $annotation) - { - $this->class = $class; - $this->method = $method; - $this->annotation = $annotation; + public function __construct( + /** + * 类名. + */ + private readonly string $class, + /** + * 方法名. + */ + private readonly string $method, + /** + * 注解. + */ + private readonly ?Base $annotation + ) { } /** diff --git a/src/Bean/Annotation/Model/PropertyAnnotationRelation.php b/src/Bean/Annotation/Model/PropertyAnnotationRelation.php index a9b54a2ffb..325f313c2a 100644 --- a/src/Bean/Annotation/Model/PropertyAnnotationRelation.php +++ b/src/Bean/Annotation/Model/PropertyAnnotationRelation.php @@ -8,26 +8,20 @@ class PropertyAnnotationRelation implements IAnnotationRelation { - /** - * 类名. - */ - private string $class = ''; - - /** - * 属性名. - */ - private string $property = ''; - - /** - * 注解. - */ - private ?Base $annotation = null; - - public function __construct(string $class, string $property, Base $annotation) - { - $this->class = $class; - $this->property = $property; - $this->annotation = $annotation; + public function __construct( + /** + * 类名. + */ + private readonly string $class, + /** + * 属性名. + */ + private readonly string $property, + /** + * 注解. + */ + private readonly ?Base $annotation + ) { } /** diff --git a/src/Bean/AnnotationLoader.php b/src/Bean/AnnotationLoader.php index b74885bd2b..dd18c777a8 100644 --- a/src/Bean/AnnotationLoader.php +++ b/src/Bean/AnnotationLoader.php @@ -74,7 +74,7 @@ public function loadModuleAnnotations(string $namespace, callable $callback, str foreach (File::enumFile($path, $pattern, ['php']) as $file) { $path = $file->getFullPath(); - $diffPath = substr($path, $pathLength); + $diffPath = substr((string) $path, $pathLength); if (isset($diffPath[0]) && \DIRECTORY_SEPARATOR === $diffPath[0]) { $diffPath = substr($diffPath, 1); diff --git a/src/Bean/AnnotationParser.php b/src/Bean/AnnotationParser.php index be42ed4c61..05c812e309 100644 --- a/src/Bean/AnnotationParser.php +++ b/src/Bean/AnnotationParser.php @@ -646,14 +646,14 @@ public function doParser(string $className): void // 类 foreach ($classAnnotations as $annotation) { - $annotationClassName = \get_class($annotation); + $annotationClassName = $annotation::class; if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_CLASS, $className); } else { - $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className) { + $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className): void { if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_CLASS, $className); @@ -667,14 +667,14 @@ public function doParser(string $className): void { foreach ($annotations as $annotation) { - $annotationClassName = \get_class($annotation); + $annotationClassName = $annotation::class; if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_PROPERTY, $propName); } else { - $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $propName) { + $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $propName): void { if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_PROPERTY, $propName); @@ -689,14 +689,14 @@ public function doParser(string $className): void { foreach ($annotations as $annotation) { - $annotationClassName = \get_class($annotation); + $annotationClassName = $annotation::class; if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_METHOD, $methodName); } else { - $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $methodName) { + $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $methodName): void { if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_METHOD, $methodName); @@ -711,14 +711,14 @@ public function doParser(string $className): void { foreach ($annotations as $annotation) { - $annotationClassName = \get_class($annotation); + $annotationClassName = $annotation::class; if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_CONST, $constName); } else { - $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $constName) { + $this->one('parseComplete.' . $annotationClassName, function () use ($annotationClassName, $annotation, $className, $constName): void { if ($this->hasParser($annotationClassName)) { $this->getParser($annotationClassName)->parse($annotation, $className, BaseParser::TARGET_CONST, $constName); diff --git a/src/Bean/BeanFactory.php b/src/Bean/BeanFactory.php index 23c316ed12..7002257ce3 100644 --- a/src/Bean/BeanFactory.php +++ b/src/Bean/BeanFactory.php @@ -466,7 +466,7 @@ public static function getObjectClass($object): string } } - return \get_class($object); + return $object::class; } elseif (is_subclass_of($object, IBean::class)) { diff --git a/src/Bean/BeanProxy.php b/src/Bean/BeanProxy.php index 7643244b6e..f48d0b9a9d 100644 --- a/src/Bean/BeanProxy.php +++ b/src/Bean/BeanProxy.php @@ -32,7 +32,7 @@ public static function &call(object $object, string $className, string $method, { // 先尝试环绕 $aroundAspectDoList = []; - self::doAspect($className, $method, 'Around', static function (AopItem $aopItem, Around $annotation) use (&$aroundAspectDoList) { + self::doAspect($className, $method, 'Around', static function (AopItem $aopItem, Around $annotation) use (&$aroundAspectDoList): void { $aroundAspectDoList[] = $aopItem->getCallback(); }); if (!$aroundAspectDoList) @@ -80,11 +80,11 @@ public static function &call(object $object, string $className, string $method, { // 异常 $isCancelThrow = false; - self::doAspect($className, $method, 'AfterThrowing', static function (AopItem $aopItem, AfterThrowing $annotation) use ($object, $method, &$args, $throwable, &$isCancelThrow) { + self::doAspect($className, $method, 'AfterThrowing', static function (AopItem $aopItem, AfterThrowing $annotation) use ($object, $method, &$args, $throwable, &$isCancelThrow): void { // 验证异常是否捕获 if ($annotation->allow || $annotation->deny) { - $throwableClassName = \get_class($throwable); + $throwableClassName = $throwable::class; if ($annotation->allow) { $allowResult = false; @@ -247,7 +247,7 @@ public static function getInjects(string $className): array private static function &callOrigin(object $object, string $className, string $method, array &$args, callable $callback, bool $returnsReference) { // before - self::doAspect($className, $method, 'Before', static function (AopItem $aopItem, Before $annotation) use ($object, $method, &$args) { + self::doAspect($className, $method, 'Before', static function (AopItem $aopItem, Before $annotation) use ($object, $method, &$args): void { ($aopItem->getCallback())(new JoinPoint('before', $method, $args, $object)); }); // 原始方法调用 @@ -260,11 +260,11 @@ private static function &callOrigin(object $object, string $className, string $m $result = $callback(...$args); } // after - self::doAspect($className, $method, 'After', static function (AopItem $aopItem, After $annotation) use ($object, $method, &$args) { + self::doAspect($className, $method, 'After', static function (AopItem $aopItem, After $annotation) use ($object, $method, &$args): void { ($aopItem->getCallback())(new JoinPoint('after', $method, $args, $object)); }); // afterReturning - self::doAspect($className, $method, 'AfterReturning', static function (AopItem $aopItem, AfterReturning $annotation) use ($object, $method, &$args, &$result) { + self::doAspect($className, $method, 'AfterReturning', static function (AopItem $aopItem, AfterReturning $annotation) use ($object, $method, &$args, &$result): void { $joinPoint = new AfterReturningJoinPoint('afterReturning', $method, $args, $object); $joinPoint->setReturnValue($result); ($aopItem->getCallback())($joinPoint); @@ -283,26 +283,15 @@ private static function &callOrigin(object $object, string $className, string $m */ private static function doAspect(string $className, string $method, string $pointType, callable $callback): void { - switch ($pointType) + $items = match ($pointType) { - case 'Before': - $items = AopManager::getBeforeItems($className, $method); - break; - case 'After': - $items = AopManager::getAfterItems($className, $method); - break; - case 'Around': - $items = AopManager::getAroundItems($className, $method); - break; - case 'AfterReturning': - $items = AopManager::getAfterReturningItems($className, $method); - break; - case 'AfterThrowing': - $items = AopManager::getAfterThrowingItems($className, $method); - break; - default: - throw new \RuntimeException(sprintf('Unknown pointType %s', $pointType)); - } + 'Before' => AopManager::getBeforeItems($className, $method), + 'After' => AopManager::getAfterItems($className, $method), + 'Around' => AopManager::getAroundItems($className, $method), + 'AfterReturning' => AopManager::getAfterReturningItems($className, $method), + 'AfterThrowing' => AopManager::getAfterThrowingItems($className, $method), + default => throw new \RuntimeException(sprintf('Unknown pointType %s', $pointType)), + }; if ($items) { $class = 'Imi\Aop\Annotation\\' . $pointType; diff --git a/src/Bean/Container.php b/src/Bean/Container.php index b9fbf03005..8ef5ca11c2 100644 --- a/src/Bean/Container.php +++ b/src/Bean/Container.php @@ -20,16 +20,14 @@ class Container implements ContainerInterface */ private array $singletonObjects = []; - /** - * 绑定列表. - * - * @var array[]|callable[] - */ - private array $binds = []; - - public function __construct(array $binds = []) - { - $this->binds = $binds; + public function __construct( + /** + * 绑定列表. + * + * @var array[]|callable[] + */ + private array $binds = [] + ) { } /** diff --git a/src/Bean/Parser/BeanParser.php b/src/Bean/Parser/BeanParser.php index 51b1fdc853..ff9141f0b8 100644 --- a/src/Bean/Parser/BeanParser.php +++ b/src/Bean/Parser/BeanParser.php @@ -40,7 +40,7 @@ public function parse(\Imi\Bean\Annotation\Base $annotation, string $className, } elseif ($annotation instanceof BaseInjectValue) { - $annotationClass = \get_class($annotation); + $annotationClass = $annotation::class; switch ($annotationClass) { case Inject::class: diff --git a/src/Bean/ReflectionUtil.php b/src/Bean/ReflectionUtil.php index 57712d2339..c8a9634275 100644 --- a/src/Bean/ReflectionUtil.php +++ b/src/Bean/ReflectionUtil.php @@ -74,7 +74,7 @@ public static function getTypeComments(?\ReflectionType $type, ?string $classNam } else { - throw new \InvalidArgumentException(sprintf('Unknown type %s', \get_class($type))); + throw new \InvalidArgumentException(sprintf('Unknown type %s', $type::class)); } } @@ -144,7 +144,7 @@ public static function getTypeCode(?\ReflectionType $type, ?string $className = } else { - throw new \InvalidArgumentException(sprintf('Unknown type %s', \get_class($type))); + throw new \InvalidArgumentException(sprintf('Unknown type %s', $type::class)); } } @@ -208,7 +208,7 @@ public static function allowsType(\ReflectionType $type, string $checkType, ?str return true; } - throw new \InvalidArgumentException(sprintf('Unknown type %s', \get_class($type))); + throw new \InvalidArgumentException(sprintf('Unknown type %s', $type::class)); } public static function isAllowReturnedType(\ReflectionType $type): bool diff --git a/src/Bean/Scanner.php b/src/Bean/Scanner.php index d3d112f932..68b7094711 100644 --- a/src/Bean/Scanner.php +++ b/src/Bean/Scanner.php @@ -103,7 +103,7 @@ public static function scanVendor(?bool $statistics = null): void if (class_exists($mainClassName) && is_subclass_of($mainClassName, IMain::class)) { // 此目录为 imi 组件目录 - $realNamespace = rtrim($namespace, '\\'); + $realNamespace = rtrim((string) $namespace, '\\'); $componentName = basename($pathName); $components[$componentName] = $realNamespace; break; diff --git a/src/Cache/Aop/CacheableAop.php b/src/Cache/Aop/CacheableAop.php index e7a8d50897..fee2ddd862 100644 --- a/src/Cache/Aop/CacheableAop.php +++ b/src/Cache/Aop/CacheableAop.php @@ -82,7 +82,7 @@ public function parseCacheable(AroundJoinPoint $joinPoint) { // 加锁 $nextProceedExeced = false; - $this->parseLockable($target, $method, $joinPointArgs, $cacheable->lockable, static function () use (&$cacheValue, $joinPoint, &$nextProceedExeced) { + $this->parseLockable($target, $method, $joinPointArgs, $cacheable->lockable, static function () use (&$cacheValue, $joinPoint, &$nextProceedExeced): void { $nextProceedExeced = true; $cacheValue = $joinPoint->proceed(); }, static function () use ($cacheInstance, $key, &$cacheValue) { diff --git a/src/Cache/Handler/File.php b/src/Cache/Handler/File.php index 4624802c47..dbe44199fc 100644 --- a/src/Cache/Handler/File.php +++ b/src/Cache/Handler/File.php @@ -94,7 +94,7 @@ public function set(string $key, mixed $value, null|int|\DateInterval $ttl = nul $dir = \dirname($fileName); if (!is_dir($dir)) { - mkdir($dir, 0755, true); + mkdir($dir, 0o755, true); } // 打开文件 $fp = fopen($fileName, StreamMode::WRITE_CLEAN); diff --git a/src/Cache/Handler/RedisHash.php b/src/Cache/Handler/RedisHash.php index 15f80fce64..a3cd33fb37 100644 --- a/src/Cache/Handler/RedisHash.php +++ b/src/Cache/Handler/RedisHash.php @@ -129,7 +129,7 @@ public function getMultiple(iterable $keys, mixed $default = null): iterable { $evalResult = $redis->evalEx(self::GET_MULTIPLE_SCRIPT, array_merge( [$key], - array_map([$redis, '_serialize'], $members), + array_map($redis->_serialize(...), $members), ), 1); foreach ($evalResult as $v) { @@ -177,7 +177,7 @@ public function setMultiple(iterable $values, null|int|\DateInterval $ttl = null $result = Redis::use(static function (\Imi\Redis\RedisHandler $redis) use ($setValues) { foreach ($setValues as $key => $item) { - $result = false !== $redis->evalEx(self::SET_MULTIPLE_SCRIPT, array_merge([$key], array_map([$redis, '_serialize'], $item['member']), array_map([$redis, '_serialize'], $item['value'])), 1); + $result = false !== $redis->evalEx(self::SET_MULTIPLE_SCRIPT, array_merge([$key], array_map($redis->_serialize(...), $item['member']), array_map($redis->_serialize(...), $item['value'])), 1); if (!$result) { return $result; @@ -209,7 +209,7 @@ public function deleteMultiple(iterable $keys): bool { $result = $redis->evalEx(self::DELETE_MULTIPLE_SCRIPT, array_merge( [$key], - array_map([$redis, '_serialize'], $members), + array_map($redis->_serialize(...), $members), ), 1); if (!$result) { diff --git a/src/Cli/Contract/BaseCommand.php b/src/Cli/Contract/BaseCommand.php index 73f38c8bdd..579fe7d718 100644 --- a/src/Cli/Contract/BaseCommand.php +++ b/src/Cli/Contract/BaseCommand.php @@ -10,16 +10,7 @@ abstract class BaseCommand { - protected ImiCommand $command; - - protected InputInterface $input; - - protected OutputInterface $output; - - public function __construct(ImiCommand $command, InputInterface $input, OutputInterface $output) + public function __construct(protected ImiCommand $command, protected InputInterface $input, protected OutputInterface $output) { - $this->command = $command; - $this->input = $input; - $this->output = $output; } } diff --git a/src/Cli/ImiArgvInput.php b/src/Cli/ImiArgvInput.php index da197eb70e..77aaec9f25 100644 --- a/src/Cli/ImiArgvInput.php +++ b/src/Cli/ImiArgvInput.php @@ -8,7 +8,7 @@ use Symfony\Component\Console\Input\Input; use Symfony\Component\Console\Input\InputDefinition; -class ImiArgvInput extends Input +class ImiArgvInput extends Input implements \Stringable { private array $tokens = []; private array $parsed = []; @@ -71,7 +71,7 @@ protected function parse(): void { $parseOptions = false; } - elseif ($parseOptions && str_starts_with($token, '--')) + elseif ($parseOptions && str_starts_with((string) $token, '--')) { $this->parseLongOption($token); } @@ -335,14 +335,14 @@ public function getFirstArgument(): ?string { if ($token && '-' === $token[0]) { - if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) + if (str_contains((string) $token, '=') || !isset($this->tokens[$i + 1])) { continue; } // If it's a long option, consider that everything after "--" is the option name. // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator) - $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1); + $name = '-' === $token[1] ? substr((string) $token, 2) : substr((string) $token, -1); if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) { // noop @@ -385,8 +385,8 @@ public function hasParameterOption($values, bool $onlyParams = false): bool // Options with values: // For long options, test for '--option=' at beginning // For short options, test for '-o' at beginning - $leading = str_starts_with($value, '--') ? $value . '=' : $value; - if ($token === $value || '' !== $leading && str_starts_with($token, (string) $leading)) + $leading = str_starts_with((string) $value, '--') ? $value . '=' : $value; + if ($token === $value || '' !== $leading && str_starts_with((string) $token, (string) $leading)) { return true; } @@ -421,10 +421,10 @@ public function getParameterOption($values, $default = false, bool $onlyParams = // Options with values: // For long options, test for '--option=' at beginning // For short options, test for '-o' at beginning - $leading = str_starts_with($value, '--') ? $value . '=' : $value; - if ('' !== $leading && str_starts_with($token, $leading)) + $leading = str_starts_with((string) $value, '--') ? $value . '=' : $value; + if ('' !== $leading && str_starts_with((string) $token, (string) $leading)) { - return substr($token, \strlen($leading)); + return substr((string) $token, \strlen((string) $leading)); } } } @@ -434,10 +434,8 @@ public function getParameterOption($values, $default = false, bool $onlyParams = /** * Returns a stringified representation of the args passed to the command. - * - * @return string */ - public function __toString() + public function __toString(): string { $tokens = array_map(function (string $token): string { if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) diff --git a/src/Cli/ImiCommand.php b/src/Cli/ImiCommand.php index d843987a17..e01600f77f 100644 --- a/src/Cli/ImiCommand.php +++ b/src/Cli/ImiCommand.php @@ -20,36 +20,6 @@ class ImiCommand extends Command { - /** - * 命令名称分割符. - */ - protected string $separator = '/'; - - /** - * 命令名称. - */ - protected ?string $commandName = null; - - /** - * 命令动作名称. - */ - protected string $actionName = ''; - - /** - * 类名. - */ - protected string $className = ''; - - /** - * 方法名. - */ - protected string $methodName = ''; - - /** - * 是否启用动态参数支持. - */ - protected bool $dynamicOptions = false; - protected InputInterface $input; protected OutputInterface $output; @@ -88,15 +58,32 @@ public function getMethodName(): string return $this->methodName; } - public function __construct(?string $commandName, string $actionName, string $className, string $methodName, bool $dynamicOptions = false, string $separator = '/') + public function __construct( + /** + * 命令名称. + */ + protected ?string $commandName, + /** + * 命令动作名称. + */ + protected string $actionName, + /** + * 类名. + */ + protected string $className, + /** + * 方法名. + */ + protected string $methodName, + /** + * 是否启用动态参数支持. + */ + protected bool $dynamicOptions = false, + /** + * 命令名称分割符. + */ + protected string $separator = '/') { - $this->separator = $separator; - $this->commandName = $commandName; - $this->actionName = $actionName; - $this->className = $className; - $this->methodName = $methodName; - $this->dynamicOptions = $dynamicOptions; - $actionName = '' === $actionName ? $methodName : $actionName; if (null === $commandName) @@ -344,13 +331,13 @@ private function parseArgValue($value, $option) case ArgType::ARRAY: if (!\is_array($value)) { - $value = explode(',', $value); + $value = explode(',', (string) $value); } break; case ArgType::ARRAY_EX: if (\is_array($value) && !isset($value[1]) && isset($value[0])) { - $value = explode(',', $value[0]); + $value = explode(',', (string) $value[0]); } break; } diff --git a/src/Cli/Parser/ToolParser.php b/src/Cli/Parser/ToolParser.php index 4b125748db..62e2ccaddb 100644 --- a/src/Cli/Parser/ToolParser.php +++ b/src/Cli/Parser/ToolParser.php @@ -29,7 +29,7 @@ public function parse(\Imi\Bean\Annotation\Base $annotation, string $className, } elseif ($annotation instanceof CommandAction) { - $func = static function () use (&$data, $annotation, $className, $targetName) { + $func = static function () use (&$data, $annotation, $className, $targetName): void { /** @var Command $commandAnnotation */ $commandAnnotation = $data[$className]['Command']; CliManager::addCommand($commandAnnotation->name, $annotation->name, $className, $targetName, $annotation->dynamicOptions, $commandAnnotation->separator); @@ -47,7 +47,7 @@ public function parse(\Imi\Bean\Annotation\Base $annotation, string $className, } elseif ($annotation instanceof Argument) { - $func = static function () use (&$data, $annotation, $className, $targetName) { + $func = static function () use (&$data, $annotation, $className, $targetName): void { /** @var Command $commandAnnotation */ $commandAnnotation = $data[$className]['Command']; /** @var CommandAction $commandActionAnnotation */ @@ -65,7 +65,7 @@ public function parse(\Imi\Bean\Annotation\Base $annotation, string $className, } elseif ($annotation instanceof Option) { - $func = static function () use (&$data, $annotation, $className, $targetName) { + $func = static function () use (&$data, $annotation, $className, $targetName): void { /** @var Command $commandAnnotation */ $commandAnnotation = $data[$className]['Command']; /** @var CommandAction $commandActionAnnotation */ diff --git a/src/Cli/bootstrap.php b/src/Cli/bootstrap.php index 28051f1368..c12395a47c 100644 --- a/src/Cli/bootstrap.php +++ b/src/Cli/bootstrap.php @@ -6,7 +6,7 @@ use Imi\App; -return static function () { +return static function (): void { $path = null; if (\defined('IMI_IN_PHAR') && IMI_IN_PHAR) @@ -15,7 +15,7 @@ } elseif (!class_exists(\Imi\App::class)) { - (static function () use (&$path) { + (static function () use (&$path): void { foreach ([ $_SERVER['PWD'] ?? null, getcwd(), @@ -40,5 +40,5 @@ })(); } - App::runApp($path ?? realpath(\dirname($_SERVER['SCRIPT_NAME'], 2)), \Imi\Cli\CliApp::class); + App::runApp($path ?? realpath(\dirname((string) $_SERVER['SCRIPT_NAME'], 2)), \Imi\Cli\CliApp::class); }; diff --git a/src/Components/access-control/src/AccessControl/Member.php b/src/Components/access-control/src/AccessControl/Member.php index 2f92b16576..a1a4163313 100644 --- a/src/Components/access-control/src/AccessControl/Member.php +++ b/src/Components/access-control/src/AccessControl/Member.php @@ -13,11 +13,6 @@ class Member { use TAutoInject; - /** - * 用户 ID. - */ - private int $memberId; - /** * 角色列表. * @@ -46,12 +41,15 @@ class Member protected OperationService $operationService; - public function __construct(int $memberId) + public function __construct( + /** + * 用户 ID. + */ + private readonly int $memberId) { $this->__autoInject(); $this->memberService = App::getBean($this->memberServiceBean); $this->operationService = App::getBean($this->operationServiceBean); - $this->memberId = $memberId; $this->updateRoles(); $this->updateOperations(); } diff --git a/src/Components/access-control/test/Tool/TestTool.php b/src/Components/access-control/test/Tool/TestTool.php index a9a811dc79..71f258dbbd 100644 --- a/src/Components/access-control/test/Tool/TestTool.php +++ b/src/Components/access-control/test/Tool/TestTool.php @@ -21,10 +21,8 @@ public function __construct() /** * @Operation("test") - * - * @return void */ - public function test() + public function test(): void { // ACOperation::create('文章新增'); // ACOperation::create('文章更新'); diff --git a/src/Components/amqp/example/AMQP/QueueTest/QueueTestConsumer.php b/src/Components/amqp/example/AMQP/QueueTest/QueueTestConsumer.php index d40dce1518..0e4aaf321d 100644 --- a/src/Components/amqp/example/AMQP/QueueTest/QueueTestConsumer.php +++ b/src/Components/amqp/example/AMQP/QueueTest/QueueTestConsumer.php @@ -20,7 +20,7 @@ class QueueTestConsumer extends BaseQueueConsumer */ protected function consume(IMessage $message, IQueueDriver $queue): void { - var_dump(__CLASS__, $message->getMessage(), \get_class($message)); + var_dump(__CLASS__, $message->getMessage(), $message::class); $queueTestMessage = QueueTestMessage::fromMessage($message->getMessage()); Redis::set('imi-amqp:consume:QueueTest:' . $queueTestMessage->getMemberId(), $message->getMessage()); diff --git a/src/Components/amqp/example/AMQP/Test/TestConsumer.php b/src/Components/amqp/example/AMQP/Test/TestConsumer.php index 6331d84919..be23a6cb06 100644 --- a/src/Components/amqp/example/AMQP/Test/TestConsumer.php +++ b/src/Components/amqp/example/AMQP/Test/TestConsumer.php @@ -29,7 +29,7 @@ class TestConsumer extends BaseConsumer */ protected function consume(IMessage $message) { - var_dump(__CLASS__, $message->getBody(), \get_class($message)); + var_dump(__CLASS__, $message->getBody(), $message::class); Redis::set('imi-amqp:consume:1:' . $message->getMemberId(), $message->getBody()); return ConsumerResult::ACK; diff --git a/src/Components/amqp/example/Process/SwooleTestProcess.php b/src/Components/amqp/example/Process/SwooleTestProcess.php index 95b995f71c..f8ea1b5448 100644 --- a/src/Components/amqp/example/Process/SwooleTestProcess.php +++ b/src/Components/amqp/example/Process/SwooleTestProcess.php @@ -31,7 +31,7 @@ public function run(\Swoole\Process $process): void $this->running = true; $this->runConsumer($this->testConsumer); $channel = new \Swoole\Coroutine\Channel(); - Event::on('IMI.PROCESS.END', function () use ($channel) { + Event::on('IMI.PROCESS.END', function () use ($channel): void { $this->running = false; $this->testConsumer->close(); $channel->push(1); @@ -41,7 +41,7 @@ public function run(\Swoole\Process $process): void private function runConsumer(IConsumer $consumer): void { - Coroutine::create(function () use ($consumer) { + Coroutine::create(function () use ($consumer): void { try { $consumer->run(); diff --git a/src/Components/amqp/src/Base/BaseConsumer.php b/src/Components/amqp/src/Base/BaseConsumer.php index 03d046e36b..4dc76bbae2 100644 --- a/src/Components/amqp/src/Base/BaseConsumer.php +++ b/src/Components/amqp/src/Base/BaseConsumer.php @@ -94,7 +94,7 @@ protected function bindConsumer(): void foreach ((array) $consumer->queue as $queueName) { $messageClass = $consumer->message ?? \Imi\AMQP\Message::class; - $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass, $isSwoole) { + $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass, $isSwoole): void { if (!$this->running) { return; diff --git a/src/Components/amqp/src/Base/BasePublisher.php b/src/Components/amqp/src/Base/BasePublisher.php index ece8e0c8dd..4345a40b92 100644 --- a/src/Components/amqp/src/Base/BasePublisher.php +++ b/src/Components/amqp/src/Base/BasePublisher.php @@ -59,7 +59,7 @@ protected function preparePublish(bool $force = false): void $this->declarePublisher(); } $this->ackSuccess = false; - $this->channel->set_ack_handler(function () { + $this->channel->set_ack_handler(function (): void { $this->ackSuccess = true; }); } @@ -104,7 +104,7 @@ public function publish(IMessage $message): bool } while ($continue); } - $this->channel->set_ack_handler(static function () { + $this->channel->set_ack_handler(static function (): void { }); return $this->ackSuccess; diff --git a/src/Components/amqp/src/Contract/IMessage.php b/src/Components/amqp/src/Contract/IMessage.php index f71e2e7d2f..534b931a36 100644 --- a/src/Components/amqp/src/Contract/IMessage.php +++ b/src/Components/amqp/src/Contract/IMessage.php @@ -107,10 +107,8 @@ public function setTicket(?int $ticket); /** * 设置 AMQP 消息. - * - * @return void */ - public function setAMQPMessage(AMQPMessage $amqpMessage); + public function setAMQPMessage(AMQPMessage $amqpMessage): void; /** * 获取 AMQP 消息. diff --git a/src/Components/amqp/src/Pool/AMQPResource.php b/src/Components/amqp/src/Pool/AMQPResource.php index 83353ad36b..c27331c7c0 100644 --- a/src/Components/amqp/src/Pool/AMQPResource.php +++ b/src/Components/amqp/src/Pool/AMQPResource.php @@ -17,28 +17,24 @@ */ class AMQPResource extends BasePoolResource { - /** - * AMQP 客户端. - */ - private AbstractConnection $connection; - /** * 重置状态的 Channel,重置中不为 null. * * 为兼容无 Swoole 的环境,所以声明为非强类型 * * @noRector - * - * @var \Swoole\Coroutine\Channel|null */ - private $resetingChannel = null; + private ?\Swoole\Coroutine\Channel $resetingChannel = null; private bool $closed = false; - public function __construct(\Imi\Pool\Interfaces\IPool $pool, AbstractConnection $connection) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * AMQP 客户端. + */ + private AbstractConnection $connection) { parent::__construct($pool); - $this->connection = $connection; $this->closed = !$connection->isConnected(); } @@ -75,7 +71,7 @@ public function close(): void $this->connection->close(); } } - catch (\Exception $e) + catch (\Exception) { return; } @@ -118,7 +114,7 @@ public function reset(): void { $channel->close(); } - catch (\Throwable $e) + catch (\Throwable) { /* Ignore closing errors */ } diff --git a/src/Components/amqp/src/Queue/AMQPQueueDriver.php b/src/Components/amqp/src/Queue/AMQPQueueDriver.php index d135007b91..8acdda1bd2 100644 --- a/src/Components/amqp/src/Queue/AMQPQueueDriver.php +++ b/src/Components/amqp/src/Queue/AMQPQueueDriver.php @@ -36,11 +36,6 @@ class AMQPQueueDriver implements IQueueDriver */ protected ?string $poolName = null; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 支持消息删除功能. * @@ -92,9 +87,12 @@ class AMQPQueueDriver implements IQueueDriver */ private array $args = []; - public function __construct(string $name, array $config = []) + public function __construct( + /** + * 队列名称. + */ + protected string $name, array $config = []) { - $this->name = $name; $this->traitConstruct($config); $this->args = \func_get_args(); } diff --git a/src/Components/amqp/src/Queue/AMQPQueueDriverHandler.php b/src/Components/amqp/src/Queue/AMQPQueueDriverHandler.php index 223b9e3d5c..6b3b57a132 100644 --- a/src/Components/amqp/src/Queue/AMQPQueueDriverHandler.php +++ b/src/Components/amqp/src/Queue/AMQPQueueDriverHandler.php @@ -29,11 +29,6 @@ class AMQPQueueDriverHandler implements IQueueDriver */ protected ?string $poolName = null; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 支持消息删除功能. * @@ -135,9 +130,12 @@ class AMQPQueueDriverHandler implements IQueueDriver */ private string $timeoutQueueName = ''; - public function __construct(string $name, array $config = []) + public function __construct( + /** + * 队列名称. + */ + protected string $name, array $config = []) { - $this->name = $name; $this->traitConstruct($config); $exchangeName = 'imi-' . $name; @@ -334,7 +332,7 @@ public function pop(float $timeout = 0): ?IMessage $score = -1; } - Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($score, $message) { + Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($score, $message): void { $redis->zAdd($this->getRedisQueueKey(QueueType::WORKING), $score, json_encode($message->toArray(), \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE)); }, $this->redisPoolName, true); @@ -363,7 +361,7 @@ public function delete(IMessage $message): bool */ public function clear($queueType = null): void { - Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($queueType) { + Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($queueType): void { if (null === $queueType) { $queueTypes = QueueType::getValues(); @@ -405,7 +403,7 @@ public function clear($queueType = null): void break; } } - catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException $e) + catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException) { } } @@ -470,7 +468,7 @@ public function status(): QueueStatus } $ready = (int) $result[1]; } - catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException $e) + catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException) { $ready = 0; } @@ -494,7 +492,7 @@ public function status(): QueueStatus $fail += $failReady; } } - catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException $e) + catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException) { } $status['fail'] = $fail; @@ -511,7 +509,7 @@ public function status(): QueueStatus [, $timeoutReady] = $result; $status['timeout'] = $timeoutReady; } - catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException $e) + catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException) { $status['timeout'] = 0; } @@ -531,7 +529,7 @@ public function status(): QueueStatus } [, $delayReady] = $result; } - catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException $e) + catch (\PhpAmqpLib\Exception\AMQPProtocolChannelException) { $delayReady = 0; } @@ -606,7 +604,7 @@ public function getRedisQueueKey($queueType): string */ protected function parseTimeoutMessages(int $count = 100): void { - Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($count) { + Redis::use(function (\Imi\Redis\RedisHandler $redis) use ($count): void { $result = $redis->evalEx(<<<'LUA' -- 查询消息ID local messages = redis.call('zrevrangebyscore', KEYS[1], ARGV[1], 0, 'limit', 0, ARGV[2]) diff --git a/src/Components/amqp/src/Queue/QueueConsumer.php b/src/Components/amqp/src/Queue/QueueConsumer.php index e708598be2..fc0c5d8f29 100644 --- a/src/Components/amqp/src/Queue/QueueConsumer.php +++ b/src/Components/amqp/src/Queue/QueueConsumer.php @@ -19,16 +19,13 @@ class QueueConsumer extends BaseConsumer implements IQueueConsumer */ private ?\SplQueue $queue = null; - /** - * 本地缓存的队列长度. - */ - protected int $queueLength = 0; - - public function __construct(int $queueLength, array $exchanges, array $queues, array $consumers, ?string $poolName = null) + public function __construct( + /** + * 本地缓存的队列长度. + */ + protected int $queueLength, array $exchanges, array $queues, array $consumers, ?string $poolName = null) { parent::__construct(); - - $this->queueLength = $queueLength; $this->poolName = $poolName; $list = []; @@ -100,7 +97,7 @@ public function pop(float $timeout): ?Message return $this->queue->pop() ?: null; } - catch (\PhpAmqpLib\Exception\AMQPTimeoutException $te) + catch (\PhpAmqpLib\Exception\AMQPTimeoutException) { } @@ -117,7 +114,7 @@ protected function bindConsumer(): void foreach ((array) $consumer->queue as $queueName) { $messageClass = $consumer->message ?? \Imi\AMQP\Message::class; - $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass) { + $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass): void { /** @var \Imi\AMQP\Message $messageInstance */ $messageInstance = new $messageClass(); $messageInstance->setAMQPMessage($message); @@ -130,7 +127,7 @@ protected function bindConsumer(): void /** * {@inheritDoc} */ - protected function consume(IMessage $message) + protected function consume(IMessage $message): void { $this->queue->push($message); } diff --git a/src/Components/amqp/src/Queue/SwooleQueueConsumer.php b/src/Components/amqp/src/Queue/SwooleQueueConsumer.php index 1e718b6cf4..c1e86a3682 100644 --- a/src/Components/amqp/src/Queue/SwooleQueueConsumer.php +++ b/src/Components/amqp/src/Queue/SwooleQueueConsumer.php @@ -22,16 +22,13 @@ class SwooleQueueConsumer extends BaseConsumer implements IQueueConsumer */ private ?Channel $resultChannel = null; - /** - * 本地缓存的队列长度. - */ - protected int $queueLength = 0; - - public function __construct(int $queueLength, array $exchanges, array $queues, array $consumers, ?string $poolName = null) + public function __construct( + /** + * 本地缓存的队列长度. + */ + protected int $queueLength, array $exchanges, array $queues, array $consumers, ?string $poolName = null) { parent::__construct(); - - $this->queueLength = $queueLength; $this->poolName = $poolName; $list = []; @@ -104,7 +101,7 @@ public function pop(float $timeout): ?Message return $this->resultChannel->pop(0.001) ?: null; } - catch (\PhpAmqpLib\Exception\AMQPTimeoutException $te) + catch (\PhpAmqpLib\Exception\AMQPTimeoutException) { } @@ -121,7 +118,7 @@ protected function bindConsumer(): void foreach ((array) $consumer->queue as $queueName) { $messageClass = $consumer->message ?? \Imi\AMQP\Message::class; - $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass) { + $this->channel->basic_consume($queueName, $consumer->tag, false, false, false, false, function (\PhpAmqpLib\Message\AMQPMessage $message) use ($messageClass): void { /** @var \Imi\AMQP\Message $messageInstance */ $messageInstance = new $messageClass(); $messageInstance->setAMQPMessage($message); @@ -134,7 +131,7 @@ protected function bindConsumer(): void /** * {@inheritDoc} */ - protected function consume(IMessage $message) + protected function consume(IMessage $message): void { $this->resultChannel->push($message); } diff --git a/src/Components/amqp/tests/PHPUnitHook.php b/src/Components/amqp/tests/PHPUnitHook.php index 5288a29604..d0adf4ae0d 100644 --- a/src/Components/amqp/tests/PHPUnitHook.php +++ b/src/Components/amqp/tests/PHPUnitHook.php @@ -24,12 +24,12 @@ public function executeBeforeFirstTest(): void { case 'swoole': $this->channel = $channel = new Channel(1); - Coroutine::create(static function () use ($channel) { + Coroutine::create(static function () use ($channel): void { // 要保证连接池连接被释放,必须在当前协程执行完时推给 executeAfterLastTest() 的 pop() - Coroutine::defer(static function () use ($channel) { + Coroutine::defer(static function () use ($channel): void { $channel->push(1); }); - App::run('AMQPApp', SwooleApp::class, static function () use ($channel) { + App::run('AMQPApp', SwooleApp::class, static function () use ($channel): void { $channel->push(1); $channel->pop(); }); @@ -37,7 +37,7 @@ public function executeBeforeFirstTest(): void $channel->pop(); break; case 'workerman': - App::run('AMQPApp', CliApp::class, static function () { + App::run('AMQPApp', CliApp::class, static function (): void { }); break; } diff --git a/src/Components/amqp/tests/Queue/BaseQueueTest.php b/src/Components/amqp/tests/Queue/BaseQueueTest.php index 79e4796afc..11a4f0100f 100644 --- a/src/Components/amqp/tests/Queue/BaseQueueTest.php +++ b/src/Components/amqp/tests/Queue/BaseQueueTest.php @@ -78,8 +78,8 @@ public function testPopTimeout(): void { $message = $totalTime = null; $channel = new Channel(1); - Coroutine::create(function () use (&$message, &$totalTime, $channel) { - Coroutine::create(function () use ($channel) { + Coroutine::create(function () use (&$message, &$totalTime, $channel): void { + Coroutine::create(function () use ($channel): void { Coroutine::sleep(1); $message = new Message(); $message->setMessage('testPopTimeout'); diff --git a/src/Components/amqp/tests/bootstrap.php b/src/Components/amqp/tests/bootstrap.php index ceda80e14b..e8de1c32b4 100644 --- a/src/Components/amqp/tests/bootstrap.php +++ b/src/Components/amqp/tests/bootstrap.php @@ -34,10 +34,8 @@ function checkHttpServerStatus() /** * 开启服务器. - * - * @return void */ -function startServer() +function startServer(): void { $dirname = \dirname(__DIR__); $mode = env('AMQP_TEST_MODE'); @@ -56,13 +54,13 @@ function startServer() $callbacks = []; foreach ($servers as $name => $options) { - $callbacks[] = static function () use ($options, $name) { + $callbacks[] = static function () use ($options, $name): void { // start server $cmd = 'nohup ' . $options['start'] . ' > /dev/null 2>&1'; echo "Starting {$name}...", \PHP_EOL; shell_exec($cmd); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { \Swoole\Runtime::enableCoroutine(false); // stop server $cmd = $options['stop']; @@ -84,12 +82,12 @@ function startServer() batch($callbacks, 120, max(swoole_cpu_num() - 1, 1)); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([8080]); }); } -(static function () { +(static function (): void { $redis = new \Redis(); $host = env('REDIS_SERVER_HOST', '127.0.0.1'); $port = env('REDIS_SERVER_PORT', 6379); diff --git a/src/Components/apidoc/example/ApiServer/Controller/IndexController.php b/src/Components/apidoc/example/ApiServer/Controller/IndexController.php index 1009479c1b..25367138d8 100644 --- a/src/Components/apidoc/example/ApiServer/Controller/IndexController.php +++ b/src/Components/apidoc/example/ApiServer/Controller/IndexController.php @@ -20,10 +20,8 @@ class IndexController extends HttpController * @Action * * @Route("/") - * - * @return void */ - public function index() + public function index(): void { } @@ -34,10 +32,8 @@ public function index() * * @param string $username 用户名 * @param int $password 密码 - * - * @return void */ - public function login(string $username, int $password) + public function login(string $username, int $password): void { } @@ -45,10 +41,8 @@ public function login(string $username, int $password) * @Action * * @Route(method={"GET", "POST"}) - * - * @return void */ - public function multiMethod1(int $id, int $type, array $tags) + public function multiMethod1(int $id, int $type, array $tags): void { } @@ -58,10 +52,8 @@ public function multiMethod1(int $id, int $type, array $tags) * @Route(method={"PUT", "POST"}) * * @param int[] $tags 标签 - * - * @return void */ - public function multiMethod2(int $id, int $type, array $tags) + public function multiMethod2(int $id, int $type, array $tags): void { } @@ -79,19 +71,15 @@ public function multiMethod2(int $id, int $type, array $tags) * @param string $username 用户名 * @param int $password 密码 * @param string $birthday 生日 - * - * @return void */ - public function register(string $username, int $password, string $birthday) + public function register(string $username, int $password, string $birthday): void { } /** * @Action - * - * @return void */ - public function get(int $id) + public function get(int $id): void { } } diff --git a/src/Components/apidoc/src/Tool/DocTool.php b/src/Components/apidoc/src/Tool/DocTool.php index 4563834ebf..0a07b29d4a 100644 --- a/src/Components/apidoc/src/Tool/DocTool.php +++ b/src/Components/apidoc/src/Tool/DocTool.php @@ -91,7 +91,7 @@ public function api(string $to, ?string $namespace): void $generator = new Generator($loggerInstance->getLogger()); $processors = $generator->getProcessors(); - array_unshift($processors, function (Analysis $analysis) use ($controllerClasses) { + array_unshift($processors, function (Analysis $analysis) use ($controllerClasses): void { $this->parseRoute($analysis, $controllerClasses); }); @@ -103,10 +103,8 @@ public function api(string $to, ?string $namespace): void /** * 处理路由. - * - * @return void */ - private function parseRoute(Analysis $analysis, array $controllerClasses) + private function parseRoute(Analysis $analysis, array $controllerClasses): void { // OpenApi 扫描 $map = []; @@ -121,7 +119,7 @@ private function parseRoute(Analysis $analysis, array $controllerClasses) $context = $annotation->_context; /** @var \OpenApi\Annotations\AbstractAnnotation $annotation */ $className = $context->namespace . '\\' . $context->class; - $map[$className][$context->method][\get_class($annotation)][] = $annotation; + $map[$className][$context->method][$annotation::class][] = $annotation; if ($annotation instanceof Info) { $info = $annotation; diff --git a/src/Components/fpm/src/Http/Message/FpmRequest.php b/src/Components/fpm/src/Http/Message/FpmRequest.php index 144edb095b..6223e8e79f 100644 --- a/src/Components/fpm/src/Http/Message/FpmRequest.php +++ b/src/Components/fpm/src/Http/Message/FpmRequest.php @@ -34,7 +34,7 @@ public function getClientAddress(): IPEndPoint */ protected function initProtocolVersion(): void { - $this->protocolVersion = substr($_SERVER['SERVER_PROTOCOL'], 5); + $this->protocolVersion = substr((string) $_SERVER['SERVER_PROTOCOL'], 5); } /** diff --git a/src/Components/fpm/src/Http/Message/FpmResponse.php b/src/Components/fpm/src/Http/Message/FpmResponse.php index 10d50659dc..e8b19d1c29 100644 --- a/src/Components/fpm/src/Http/Message/FpmResponse.php +++ b/src/Components/fpm/src/Http/Message/FpmResponse.php @@ -58,7 +58,7 @@ private function sendHeaders(): void { foreach ($cookieParams as $cookie) { - setcookie($cookie['key'], $cookie['value'], ['expires' => $cookie['expire'] ?? 0, 'path' => $cookie['path'] ?? '/', 'domain' => $cookie['domain'] ?? '', 'secure' => $cookie['secure'] ?? false, 'httponly' => $cookie['httponly'] ?? false]); + setcookie($cookie['key'], (string) $cookie['value'], ['expires' => $cookie['expire'] ?? 0, 'path' => $cookie['path'] ?? '/', 'domain' => $cookie['domain'] ?? '', 'secure' => $cookie['secure'] ?? false, 'httponly' => $cookie['httponly'] ?? false]); } } } diff --git a/src/Components/fpm/src/Server/Cli/Server.php b/src/Components/fpm/src/Server/Cli/Server.php index ca82ff4411..ba8d237802 100644 --- a/src/Components/fpm/src/Server/Cli/Server.php +++ b/src/Components/fpm/src/Server/Cli/Server.php @@ -34,7 +34,7 @@ public function start(string $host, int $port): void { /** @var \Symfony\Component\Process\Process|null $process */ $process = null; - pcntl_signal(\SIGTERM, static function () use (&$process) { + pcntl_signal(\SIGTERM, static function () use (&$process): void { if ($process) { $process->signal(\SIGINT); diff --git a/src/Components/fpm/tests/bootstrap.php b/src/Components/fpm/tests/bootstrap.php index 55b7c53258..3b2521f775 100644 --- a/src/Components/fpm/tests/bootstrap.php +++ b/src/Components/fpm/tests/bootstrap.php @@ -64,7 +64,7 @@ function checkHttpServerStatus(): bool echo "Starting {$name}...", \PHP_EOL; shell_exec("{$cmd}"); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { // stop server $cmd = $options['stop']; if ('\\' === \DIRECTORY_SEPARATOR) @@ -85,7 +85,7 @@ function checkHttpServerStatus(): bool throw new \RuntimeException("{$name} start failed"); } } - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([13000]); }); } diff --git a/src/Components/grpc/src/Client/GrpcService.php b/src/Components/grpc/src/Client/GrpcService.php index 38e8c922c6..ede8ac61a2 100644 --- a/src/Components/grpc/src/Client/GrpcService.php +++ b/src/Components/grpc/src/Client/GrpcService.php @@ -11,11 +11,6 @@ class GrpcService implements IGrpcService { - /** - * 客户端. - */ - protected GrpcClient $client; - /** * 包名. */ @@ -26,26 +21,25 @@ class GrpcService implements IGrpcService */ protected string $serviceName = ''; - /** - * 完整服务名称. - */ - protected string $name = ''; - - /** - * 服务接口. - */ - protected ?string $interface = null; - /** * @Inject("GrpcInterfaceManager") */ protected GrpcInterfaceManager $interfaceManager; - public function __construct(GrpcClient $client, string $name, ?string $interface = null) + public function __construct( + /** + * 客户端. + */ + protected GrpcClient $client, + /** + * 完整服务名称. + */ + protected string $name, + /** + * 服务接口. + */ + protected ?string $interface = null) { - $this->client = $client; - $this->name = $name; - $this->interface = $interface; if (preg_match('/^(.+)\.([^\.]+)$/', $name, $matches) > 0) { $this->package = $matches[1]; diff --git a/src/Components/grpc/src/Client/ServiceAgent.php b/src/Components/grpc/src/Client/ServiceAgent.php index b07d5bb150..3124f8e195 100644 --- a/src/Components/grpc/src/Client/ServiceAgent.php +++ b/src/Components/grpc/src/Client/ServiceAgent.php @@ -11,26 +11,20 @@ */ class ServiceAgent { - /** - * 连接池名称. - */ - public ?string $poolName = null; - - /** - * 服务名称. - */ - public string $serviceName = ''; - - /** - * 服务接口. - */ - public string $interface = ''; - - public function __construct(?string $poolName, string $serviceName, string $interface) - { - $this->poolName = $poolName; - $this->serviceName = $serviceName; - $this->interface = $interface; + public function __construct( + /** + * 连接池名称. + */ + public ?string $poolName, + /** + * 服务名称. + */ + public string $serviceName, + /** + * 服务接口. + */ + public string $interface + ) { } /** diff --git a/src/Components/grpc/src/Listener/WorkerExit.php b/src/Components/grpc/src/Listener/WorkerExit.php index 1cf4f06cfd..a526c09ba0 100644 --- a/src/Components/grpc/src/Listener/WorkerExit.php +++ b/src/Components/grpc/src/Listener/WorkerExit.php @@ -36,7 +36,7 @@ public function handle(EventParam $e): void } else { - Coroutine::create(static function () use ($pool) { + Coroutine::create(static function () use ($pool): void { $pool->close(); }); } diff --git a/src/Components/grpc/src/Proxy/Http/GrpcHttpClient.php b/src/Components/grpc/src/Proxy/Http/GrpcHttpClient.php index 694f3092fd..cc73369d15 100644 --- a/src/Components/grpc/src/Proxy/Http/GrpcHttpClient.php +++ b/src/Components/grpc/src/Proxy/Http/GrpcHttpClient.php @@ -17,15 +17,9 @@ class GrpcHttpClient { protected HttpRequest $httpRequest; - protected string $url = ''; - - protected string $requestMethod = ''; - - public function __construct(string $url, string $requestMethod = RequestMethod::POST, ?int $timeout = null) + public function __construct(protected string $url, protected string $requestMethod = RequestMethod::POST, ?int $timeout = null) { - $this->url = $url; $this->httpRequest = $httpRequest = new HttpRequest(); - $this->requestMethod = $requestMethod; if (null !== $timeout) { $httpRequest->timeout($timeout); diff --git a/src/Components/grpc/src/Proxy/Http/GrpcHttpProxy.php b/src/Components/grpc/src/Proxy/Http/GrpcHttpProxy.php index 6a8803f968..4d4c6016d5 100644 --- a/src/Components/grpc/src/Proxy/Http/GrpcHttpProxy.php +++ b/src/Components/grpc/src/Proxy/Http/GrpcHttpProxy.php @@ -83,7 +83,7 @@ public function proxy(string $poolName, IHttpRequest $request, IHttpResponse $re // trailer $trailer = $http2Response->getHeaderLine(ResponseHeader::TRAILER); $response->setHeader(ResponseHeader::TRAILER, $trailer); - foreach (explode(',', $trailer) as $trailerItem) + foreach (explode(',', (string) $trailer) as $trailerItem) { $trailerItem = trim($trailerItem); if ('' === $trailerItem) diff --git a/src/Components/grpc/src/Server/Error/DefaultGrpcErrorHandler.php b/src/Components/grpc/src/Server/Error/DefaultGrpcErrorHandler.php index 4f0414dad6..eba4c36d63 100644 --- a/src/Components/grpc/src/Server/Error/DefaultGrpcErrorHandler.php +++ b/src/Components/grpc/src/Server/Error/DefaultGrpcErrorHandler.php @@ -36,7 +36,7 @@ public function handle(\Throwable $throwable): bool private function getGrpcStatus(\Throwable $throwable): int { - $class = \get_class($throwable); + $class = $throwable::class; switch ($class) { case \BadFunctionCallException::class: diff --git a/src/Components/grpc/src/Util/ProtobufUtil.php b/src/Components/grpc/src/Util/ProtobufUtil.php index d2c1c17ffa..b0ef534d9f 100644 --- a/src/Components/grpc/src/Util/ProtobufUtil.php +++ b/src/Components/grpc/src/Util/ProtobufUtil.php @@ -31,7 +31,7 @@ public static function setMessageData(Message $message, $data, bool $ignoreUnkno } else { - $ref = ReflectionContainer::getMethodReflection(\get_class($message), 'mergeFromJsonArray'); + $ref = ReflectionContainer::getMethodReflection($message::class, 'mergeFromJsonArray'); $ref->setAccessible(true); $ref->invoke($message, $data, $ignoreUnknown); } @@ -104,15 +104,12 @@ public static function getMessageValue($message, array $options = []) } if ($message instanceof \Google\Protobuf\EnumValue) { - switch ($enumReturnType = ($options['enumReturnType'] ?? 'value')) + return match ($enumReturnType = ($options['enumReturnType'] ?? 'value')) { - case 'value': - return $message->getNumber(); - case 'name': - return $message->getName(); - default: - throw new \RuntimeException(sprintf('Unknown enumReturnType %s', $enumReturnType)); - } + 'value' => $message->getNumber(), + 'name' => $message->getName(), + default => throw new \RuntimeException(sprintf('Unknown enumReturnType %s', $enumReturnType)), + }; } if ($message instanceof \Google\Protobuf\GPBEmpty) { @@ -174,7 +171,7 @@ public static function getMessageValue($message, array $options = []) /** @var DescriptorPool $pool */ $pool = DescriptorPool::getGeneratedPool(); /** @var Descriptor $desc */ - $desc = $pool->getDescriptorByClassName(\get_class($message)); + $desc = $pool->getDescriptorByClassName($message::class); $result = []; /** @var FieldDescriptor $field */ foreach ($desc->getField() as $field) diff --git a/src/Components/grpc/tests/Grpc/PHPUnitHook.php b/src/Components/grpc/tests/Grpc/PHPUnitHook.php index 7ff0f5249f..972e61732d 100644 --- a/src/Components/grpc/tests/Grpc/PHPUnitHook.php +++ b/src/Components/grpc/tests/Grpc/PHPUnitHook.php @@ -18,7 +18,7 @@ class PHPUnitHook implements BeforeFirstTestHook, AfterLastTestHook public function executeBeforeFirstTest(): void { $this->channel = $channel = new Channel(1); - Coroutine::create(static fn () => App::run('GrpcApp', SwooleApp::class, static function () use ($channel) { + Coroutine::create(static fn () => App::run('GrpcApp', SwooleApp::class, static function () use ($channel): void { $channel->push(1); $channel->pop(); })); diff --git a/src/Components/grpc/tests/bootstrap.php b/src/Components/grpc/tests/bootstrap.php index 79e34dfaa9..da29ff2c43 100644 --- a/src/Components/grpc/tests/bootstrap.php +++ b/src/Components/grpc/tests/bootstrap.php @@ -32,10 +32,8 @@ function checkHttpServerStatus() /** * 开启服务器. - * - * @return void */ -function startServer() +function startServer(): void { $dirname = \dirname(__DIR__); $servers = [ @@ -49,13 +47,13 @@ function startServer() $callbacks = []; foreach ($servers as $name => $options) { - $callbacks[] = static function () use ($options, $name) { + $callbacks[] = static function () use ($options, $name): void { // start server $cmd = 'nohup ' . $options['start'] . ' > /dev/null 2>&1'; echo "Starting {$name}...", \PHP_EOL; shell_exec($cmd); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { \Swoole\Runtime::enableCoroutine(false); // stop server $cmd = $options['stop']; @@ -76,7 +74,7 @@ function startServer() } batch($callbacks, 120, max(swoole_cpu_num() - 1, 1)); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([8081]); }); } diff --git a/src/Components/jwt/src/Model/JWTConfig.php b/src/Components/jwt/src/Model/JWTConfig.php index b8472e165b..6bc8374ea4 100644 --- a/src/Components/jwt/src/Model/JWTConfig.php +++ b/src/Components/jwt/src/Model/JWTConfig.php @@ -59,10 +59,8 @@ class JWTConfig * 设为 true 则为当前时间 * 设为 false 不设置 * 其它值则直接写入. - * - * @var bool|mixed */ - private $issuedAt = true; + private bool $issuedAt = true; /** * Token id. diff --git a/src/Components/jwt/tests/PHPUnitHook.php b/src/Components/jwt/tests/PHPUnitHook.php index ad9f21847e..b69bd0a231 100644 --- a/src/Components/jwt/tests/PHPUnitHook.php +++ b/src/Components/jwt/tests/PHPUnitHook.php @@ -12,7 +12,7 @@ class PHPUnitHook implements BeforeFirstTestHook { public function executeBeforeFirstTest(): void { - App::run('Imi\JWT\Test', CliApp::class, static function () { + App::run('Imi\JWT\Test', CliApp::class, static function (): void { }); } } diff --git a/src/Components/jwt/tests/Unit/JWTTest.php b/src/Components/jwt/tests/Unit/JWTTest.php index f44d944798..e6ef8e1cfb 100644 --- a/src/Components/jwt/tests/Unit/JWTTest.php +++ b/src/Components/jwt/tests/Unit/JWTTest.php @@ -11,15 +11,12 @@ class JWTTest extends TestCase { - /** - * @return void - */ - public function testJWT() + public function testJWT(): void { $data = [ 'memberId' => 19260817, ]; - $token = JWT::getToken($data, null, static function (Builder $builder) { + $token = JWT::getToken($data, null, static function (Builder $builder): void { if (3 === JWT::getJwtPackageVersion()) { $builder->expiresAt(strtotime('1926-08-17')); @@ -44,10 +41,7 @@ public function testJWT() $token2 = JWT::parseToken($tokenStr, null, true); // 验证 } - /** - * @return void - */ - public function testJWTValidation() + public function testJWTValidation(): void { $excepted = [ 'memberId' => 19260817, @@ -59,10 +53,7 @@ public function testJWTValidation() $this->assertEquals(json_encode($excepted), json_encode($data)); } - /** - * @return void - */ - public function testJWTValidateFail() + public function testJWTValidateFail(): void { $this->expectException(\Imi\JWT\Exception\InvalidTokenException::class); /** @var \Imi\JWT\Test\Test\A $a */ diff --git a/src/Components/kafka/example/Process/SwooleTestProcess.php b/src/Components/kafka/example/Process/SwooleTestProcess.php index 91d19cabb8..08d04c97aa 100644 --- a/src/Components/kafka/example/Process/SwooleTestProcess.php +++ b/src/Components/kafka/example/Process/SwooleTestProcess.php @@ -32,7 +32,7 @@ public function run(\Swoole\Process $process): void $this->running = true; $this->runConsumer($this->testConsumer); $channel = new \Swoole\Coroutine\Channel(); - Event::on('IMI.PROCESS.END', function () use ($channel) { + Event::on('IMI.PROCESS.END', function () use ($channel): void { $this->running = false; $this->testConsumer->close(); $channel->push(1); @@ -42,7 +42,7 @@ public function run(\Swoole\Process $process): void private function runConsumer(IConsumer $consumer): void { - Coroutine::create(function () use ($consumer) { + Coroutine::create(function () use ($consumer): void { try { $consumer->run(); diff --git a/src/Components/kafka/src/Base/BaseConsumer.php b/src/Components/kafka/src/Base/BaseConsumer.php index 6406c851c1..7d754d77a7 100644 --- a/src/Components/kafka/src/Base/BaseConsumer.php +++ b/src/Components/kafka/src/Base/BaseConsumer.php @@ -62,7 +62,7 @@ public function run(): void { if ($isSwoole) { - goWait(function () use ($message, $consumer) { + goWait(function () use ($message, $consumer): void { $this->consume($message); $consumer->ack($message); }, -1, true); diff --git a/src/Components/kafka/src/Pool/KafkaPool.php b/src/Components/kafka/src/Pool/KafkaPool.php index 64566b892e..a23eeefa75 100644 --- a/src/Components/kafka/src/Pool/KafkaPool.php +++ b/src/Components/kafka/src/Pool/KafkaPool.php @@ -90,10 +90,8 @@ public static function getInstance(?string $poolName = null): Producer /** * 释放连接实例. - * - * @return void */ - public static function release(Producer $client) + public static function release(Producer $client): void { $resource = RequestContext::get('poolResources.' . spl_object_id($client)); if (null !== $resource) diff --git a/src/Components/kafka/src/Pool/KafkaResource.php b/src/Components/kafka/src/Pool/KafkaResource.php index cd6619fa50..04dcb95e35 100644 --- a/src/Components/kafka/src/Pool/KafkaResource.php +++ b/src/Components/kafka/src/Pool/KafkaResource.php @@ -12,15 +12,13 @@ */ class KafkaResource extends BasePoolResource { - /** - * Kafka 生产者. - */ - private Producer $connection; - - public function __construct(\Imi\Pool\Interfaces\IPool $pool, Producer $connection) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * Kafka 生产者. + */ + private readonly Producer $connection) { parent::__construct($pool); - $this->connection = $connection; } /** diff --git a/src/Components/kafka/src/Queue/KafkaQueueDriver.php b/src/Components/kafka/src/Queue/KafkaQueueDriver.php index 4bf3039ba2..f19ee85e91 100644 --- a/src/Components/kafka/src/Queue/KafkaQueueDriver.php +++ b/src/Components/kafka/src/Queue/KafkaQueueDriver.php @@ -31,11 +31,6 @@ class KafkaQueueDriver implements IQueueDriver */ protected ?string $poolName = null; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 分组ID. */ @@ -46,9 +41,12 @@ class KafkaQueueDriver implements IQueueDriver */ private array $consumers = []; - public function __construct(string $name, array $config = []) + public function __construct( + /** + * 队列名称. + */ + protected string $name, array $config = []) { - $this->name = $name; $this->traitConstruct($config); } diff --git a/src/Components/kafka/tests/PHPUnitHook.php b/src/Components/kafka/tests/PHPUnitHook.php index 9f8d7445d3..77afa5ca8a 100644 --- a/src/Components/kafka/tests/PHPUnitHook.php +++ b/src/Components/kafka/tests/PHPUnitHook.php @@ -18,7 +18,7 @@ class PHPUnitHook implements BeforeFirstTestHook, AfterLastTestHook public function executeBeforeFirstTest(): void { $this->channel = $channel = new Channel(1); - Coroutine::create(static fn () => App::run('KafkaApp', SwooleApp::class, static function () use ($channel) { + Coroutine::create(static fn () => App::run('KafkaApp', SwooleApp::class, static function () use ($channel): void { $channel->push(1); $channel->pop(); })); diff --git a/src/Components/kafka/tests/bootstrap.php b/src/Components/kafka/tests/bootstrap.php index 2bef3e54f9..b08cacb2fd 100644 --- a/src/Components/kafka/tests/bootstrap.php +++ b/src/Components/kafka/tests/bootstrap.php @@ -34,10 +34,8 @@ function checkHttpServerStatus() /** * 开启服务器. - * - * @return void */ -function startServer() +function startServer(): void { $dirname = \dirname(__DIR__); $mode = env('KAFKA_TEST_MODE'); @@ -56,13 +54,13 @@ function startServer() $callbacks = []; foreach ($servers as $name => $options) { - $callbacks[] = static function () use ($options, $name) { + $callbacks[] = static function () use ($options, $name): void { // start server $cmd = 'nohup ' . $options['start'] . ' > /dev/null 2>&1'; echo "Starting {$name}...", \PHP_EOL; shell_exec($cmd); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { \Swoole\Runtime::enableCoroutine(false); // stop server $cmd = $options['stop']; @@ -83,12 +81,12 @@ function startServer() } batch($callbacks, 120, max(swoole_cpu_num() - 1, 1)); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([8080]); }); } startServer(); -\Swoole\Coroutine::defer(static function () { +\Swoole\Coroutine::defer(static function (): void { \Imi\Event\Event::trigger('IMI.MAIN_SERVER.WORKER.EXIT', [], null, \Imi\Swoole\Server\Event\Param\WorkerExitEventParam::class); }); diff --git a/src/Components/macro/src/AutoLoader.php b/src/Components/macro/src/AutoLoader.php index 0d73a3d7cd..ce0ce04abb 100644 --- a/src/Components/macro/src/AutoLoader.php +++ b/src/Components/macro/src/AutoLoader.php @@ -12,8 +12,6 @@ class AutoLoader { - protected ClassLoader $composerClassLoader; - protected bool $hasSwoole = false; protected int $loadingCount = 0; @@ -32,9 +30,8 @@ class AutoLoader */ protected string $outputDir = ''; - public function __construct(ClassLoader $composerClassLoader) + public function __construct(protected ClassLoader $composerClassLoader) { - $this->composerClassLoader = $composerClassLoader; // @phpstan-ignore-next-line if (\defined('IMI_IN_PHAR') && IMI_IN_PHAR) { diff --git a/src/Components/macro/src/bootstrap.php b/src/Components/macro/src/bootstrap.php index d216b0a1a9..a00fbbca76 100644 --- a/src/Components/macro/src/bootstrap.php +++ b/src/Components/macro/src/bootstrap.php @@ -8,7 +8,7 @@ { function str_starts_with(?string $haystack, ?string $needle): bool { - return 0 === strncmp($haystack, $needle, \strlen($needle)); + return str_starts_with($haystack, $needle); } } diff --git a/src/Components/mqtt/src/Client/Connection.php b/src/Components/mqtt/src/Client/Connection.php index a23933a487..220afe19f0 100644 --- a/src/Components/mqtt/src/Client/Connection.php +++ b/src/Components/mqtt/src/Client/Connection.php @@ -12,26 +12,6 @@ */ class Connection extends DefaultConnection { - /** - * 主机地址 - */ - private string $host = ''; - - /** - * 端口号. - */ - private int $port = 0; - - /** - * 超时时间,单位:秒. - */ - private ?float $timeout = null; - - /** - * Ping 时间间隔,为 NULL 则不自动 Ping. - */ - private ?float $pingTimespan = null; - /** * 使用 SSL 连接. */ @@ -76,10 +56,22 @@ class Connection extends DefaultConnection * {@inheritDoc} */ public function __construct( - string $host, - int $port, - ?float $timeout = null, - ?float $pingTimespan = null, + /** + * 主机地址 + */ + private string $host, + /** + * 端口号. + */ + private int $port, + /** + * 超时时间,单位:秒. + */ + private ?float $timeout = null, + /** + * Ping 时间间隔,为 NULL 则不自动 Ping. + */ + private ?float $pingTimespan = null, string $username = '', #[\SensitiveParameter] string $password = '', @@ -90,10 +82,6 @@ public function __construct( bool $clean = true ) { parent::__construct($username, $password, $will, $clientId, $keepAlive, $protocol, $clean); - $this->host = $host; - $this->port = $port; - $this->timeout = $timeout; - $this->pingTimespan = $pingTimespan; } /** diff --git a/src/Components/mqtt/src/Client/MQTTClient.php b/src/Components/mqtt/src/Client/MQTTClient.php index cfe2521fc1..050c2fe490 100644 --- a/src/Components/mqtt/src/Client/MQTTClient.php +++ b/src/Components/mqtt/src/Client/MQTTClient.php @@ -40,17 +40,12 @@ class MQTTClient */ private Connection $connection; - /** - * 事件监听器. - */ - private IMQTTClientListener $listener; - /** * 已连接状态 */ private bool $connected = false; - private DefaultPacketFactory $packetFactory; + private readonly DefaultPacketFactory $packetFactory; /** * Ping 定时器ID. @@ -72,7 +67,11 @@ class MQTTClient Packet::TYPE_PINGRESP => 'ping', ]; - public function __construct(array $config, IMQTTClientListener $listener) + public function __construct(array $config, + /** + * 事件监听器. + */ + private readonly IMQTTClientListener $listener) { if (!isset($config['host'])) { @@ -83,7 +82,6 @@ public function __construct(array $config, IMQTTClientListener $listener) throw new \InvalidArgumentException('MQTTClient config must have "port"'); } $this->packetFactory = App::getBean(\BinSoul\Net\Mqtt\DefaultPacketFactory::class); - $this->listener = $listener; if ($configWill = $config['will'] ?? null) { $will = new Message($configWill['topic'] ?? '', $configWill['payload'] ?? '', $configWill['qosLevel'] ?? 0, $configWill['retain'] ?? false, $configWill['duplicate'] ?? false); @@ -339,7 +337,7 @@ public function send(Packet $packet) } else { - throw new SendException(sprintf('Send %s failed! error: [%s]%s', Imi::getClassShortName(\get_class($packet)), $client->errCode, $client->errMsg)); + throw new SendException(sprintf('Send %s failed! error: [%s]%s', Imi::getClassShortName($packet::class), $client->errCode, $client->errMsg)); } } @@ -378,7 +376,7 @@ public function wait(): void $pingTimespan = $this->connection->getPingTimespan(); if ($pingTimespan > 0) { - $this->pingTimerId = Timer::tick((int) ($pingTimespan * 1000), [$this, 'ping']); + $this->pingTimerId = Timer::tick((int) ($pingTimespan * 1000), $this->ping(...)); } while ($this->connected) { diff --git a/src/Components/mqtt/src/imi/Server/MQTT/Message/ReceiveData.php b/src/Components/mqtt/src/imi/Server/MQTT/Message/ReceiveData.php index 802afe1263..87b711e72f 100644 --- a/src/Components/mqtt/src/imi/Server/MQTT/Message/ReceiveData.php +++ b/src/Components/mqtt/src/imi/Server/MQTT/Message/ReceiveData.php @@ -11,23 +11,6 @@ class ReceiveData implements IReceiveData { - /** - * 客户端连接的标识符. - * - * @var string|int - */ - protected $clientId; - - /** - * Reactor线程ID. - */ - protected int $reactorId = 0; - - /** - * 接收到的数据. - */ - protected string $data = ''; - /** * 接收到的数据. */ @@ -38,15 +21,16 @@ class ReceiveData implements IReceiveData */ protected ?IPEndPoint $clientAddress = null; - /** - * @param string|int $clientId - * @param mixed $data - */ - public function __construct($clientId, int $reactorId, $data) + public function __construct( + /** + * 客户端连接的标识符. + */ + protected int|string $clientId, + /** + * Reactor线程ID. + */ + protected int $reactorId, protected string $data) { - $this->clientId = $clientId; - $this->reactorId = $reactorId; - $this->data = $data; $this->formatData = RequestContext::getServerBean(DataParser::class)->decode($data); } diff --git a/src/Components/mqtt/tests/MQTT/MQTTTest.php b/src/Components/mqtt/tests/MQTT/MQTTTest.php index 241b3d7291..45041ee234 100644 --- a/src/Components/mqtt/tests/MQTT/MQTTTest.php +++ b/src/Components/mqtt/tests/MQTT/MQTTTest.php @@ -42,7 +42,7 @@ private function privateTest(array $config): void $listener = new TestClientListener(); $initChannel = new Channel(1); $client = new MQTTClient($config, $listener); - Coroutine::create(function () use ($initChannel, $client) { + Coroutine::create(function () use ($initChannel, $client): void { $this->assertTrue($client->connect()); $initChannel->push(1); $client->wait(); diff --git a/src/Components/mqtt/tests/PHPUnitHook.php b/src/Components/mqtt/tests/PHPUnitHook.php index 1d2cb5b967..02bccd7877 100644 --- a/src/Components/mqtt/tests/PHPUnitHook.php +++ b/src/Components/mqtt/tests/PHPUnitHook.php @@ -18,7 +18,7 @@ class PHPUnitHook implements BeforeFirstTestHook, AfterLastTestHook public function executeBeforeFirstTest(): void { $this->channel = $channel = new Channel(1); - Coroutine::create(static fn () => App::run('MQTTApp', SwooleApp::class, static function () use ($channel) { + Coroutine::create(static fn () => App::run('MQTTApp', SwooleApp::class, static function () use ($channel): void { $channel->push(1); $channel->pop(); })); diff --git a/src/Components/mqtt/tests/bootstrap.php b/src/Components/mqtt/tests/bootstrap.php index 5262fe3d85..8d724411d2 100644 --- a/src/Components/mqtt/tests/bootstrap.php +++ b/src/Components/mqtt/tests/bootstrap.php @@ -36,10 +36,8 @@ function checkMQTTServerStatus() /** * 开启服务器. - * - * @return void */ -function startServer() +function startServer(): void { $dirname = \dirname(__DIR__); $servers = [ @@ -53,13 +51,13 @@ function startServer() $callbacks = []; foreach ($servers as $name => $options) { - $callbacks[] = static function () use ($options, $name) { + $callbacks[] = static function () use ($options, $name): void { // start server $cmd = 'nohup ' . $options['start'] . ' > /dev/null 2>&1'; echo "Starting {$name}...", \PHP_EOL; shell_exec($cmd); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { \Swoole\Runtime::enableCoroutine(false); // stop server $cmd = $options['stop']; @@ -80,7 +78,7 @@ function startServer() } batch($callbacks, 120, max(swoole_cpu_num() - 1, 1)); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([8081, 8082]); }); } diff --git a/src/Components/pgsql/src/Db/Drivers/PdoPgsql/Driver.php b/src/Components/pgsql/src/Db/Drivers/PdoPgsql/Driver.php index 8b57195a6d..6c670d9667 100644 --- a/src/Components/pgsql/src/Db/Drivers/PdoPgsql/Driver.php +++ b/src/Components/pgsql/src/Db/Drivers/PdoPgsql/Driver.php @@ -33,12 +33,8 @@ public function __construct(array $option = []) protected function buildDSN(): string { $option = $this->option; - if (isset($option['dsn'])) - { - return $option['dsn']; - } - return 'pgsql:' + return $option['dsn'] ?? 'pgsql:' . 'host=' . ($option['host'] ?? '127.0.0.1') . ';port=' . ($option['port'] ?? '5432') . ';dbname=' . ($option['database'] ?? 'database') diff --git a/src/Components/pgsql/src/Db/Drivers/Swoole/Statement.php b/src/Components/pgsql/src/Db/Drivers/Swoole/Statement.php index 693f0d7124..5cbbaea9ba 100644 --- a/src/Components/pgsql/src/Db/Drivers/Swoole/Statement.php +++ b/src/Components/pgsql/src/Db/Drivers/Swoole/Statement.php @@ -16,16 +16,6 @@ */ class Statement extends PgsqlBaseStatement implements IPgsqlStatement { - /** - * @var mixed - */ - protected $queryResult; - - /** - * 数据库操作对象 - */ - protected ?IPgsqlDb $db = null; - /** * 绑定数据. */ @@ -36,21 +26,6 @@ class Statement extends PgsqlBaseStatement implements IPgsqlStatement */ protected array $result = []; - /** - * 最后执行过的SQL语句. - */ - protected string $lastSql = ''; - - /** - * SQL 参数映射. - */ - protected ?array $sqlParamsMap = null; - - /** - * statement 名字. - */ - protected ?string $statementName = null; - /** * 最后插入ID. */ @@ -59,13 +34,24 @@ class Statement extends PgsqlBaseStatement implements IPgsqlStatement /** * @param mixed $queryResult */ - public function __construct(IPgsqlDb $db, $queryResult, string $originSql, ?string $statementName = null, ?array $sqlParamsMap = null) + public function __construct( + /** + * 数据库操作对象 + */ + protected ?IPgsqlDb $db, protected $queryResult, + /** + * 最后执行过的SQL语句. + */ + protected string $lastSql, + /** + * statement 名字. + */ + protected ?string $statementName = null, + /** + * SQL 参数映射. + */ + protected ?array $sqlParamsMap = null) { - $this->db = $db; - $this->queryResult = $queryResult; - $this->lastSql = $originSql; - $this->statementName = $statementName; - $this->sqlParamsMap = $sqlParamsMap; if ($queryResult) { /** @var \Swoole\Coroutine\PostgreSQL $pgDb */ diff --git a/src/Components/pgsql/src/Db/Drivers/SwooleNew/Statement.php b/src/Components/pgsql/src/Db/Drivers/SwooleNew/Statement.php index 054ae2d34d..96bf4a00ec 100644 --- a/src/Components/pgsql/src/Db/Drivers/SwooleNew/Statement.php +++ b/src/Components/pgsql/src/Db/Drivers/SwooleNew/Statement.php @@ -17,13 +17,6 @@ */ class Statement extends PgsqlBaseStatement implements IPgsqlStatement { - protected ?PostgreSQLStatement $stmt = null; - - /** - * 数据库操作对象 - */ - protected ?IPgsqlDb $db = null; - /** * 绑定数据. */ @@ -34,27 +27,25 @@ class Statement extends PgsqlBaseStatement implements IPgsqlStatement */ protected array $result = []; - /** - * 最后执行过的SQL语句. - */ - protected string $lastSql = ''; - - /** - * SQL 参数映射. - */ - protected ?array $sqlParamsMap = null; - /** * 最后插入ID. */ protected string $lastInsertId = ''; - public function __construct(IPgsqlDb $db, PostgreSQLStatement $stmt, string $originSql, ?array $sqlParamsMap = null, bool $isExecuted = false) + public function __construct( + /** + * 数据库操作对象 + */ + protected ?IPgsqlDb $db, protected ?PostgreSQLStatement $stmt, + /** + * 最后执行过的SQL语句. + */ + protected string $lastSql, + /** + * SQL 参数映射. + */ + protected ?array $sqlParamsMap = null, bool $isExecuted = false) { - $this->db = $db; - $this->stmt = $stmt; - $this->lastSql = $originSql; - $this->sqlParamsMap = $sqlParamsMap; if ($isExecuted) { if ($result = $stmt->fetchAll(\SW_PGSQL_ASSOC)) diff --git a/src/Components/pgsql/src/Model/Cli/Model/ModelGenerate.php b/src/Components/pgsql/src/Model/Cli/Model/ModelGenerate.php index 5a5e0571df..099cd3c85e 100644 --- a/src/Components/pgsql/src/Model/Cli/Model/ModelGenerate.php +++ b/src/Components/pgsql/src/Model/Cli/Model/ModelGenerate.php @@ -195,7 +195,7 @@ public function generate(string $namespace, string $baseClass, ?string $database $this->output->writeln('Skip ' . $table . ''); continue; } - if ($usePrefix = ('' !== $tablePrefix && str_starts_with($table, $tablePrefix))) + if ($usePrefix = ('' !== $tablePrefix && str_starts_with((string) $table, (string) $tablePrefix))) { $tableName = Text::ltrimText($table, $tablePrefix); } @@ -276,7 +276,7 @@ private function getClassName(string $table, array $prefixs): string { foreach ($prefixs as $prefix) { - $prefixLen = \strlen($prefix); + $prefixLen = \strlen((string) $prefix); if (substr($table, 0, $prefixLen) === $prefix) { $table = substr($table, $prefixLen); @@ -320,7 +320,7 @@ private function parseFields(?string $poolName, array $fields, ?array &$data, bo $data['fields'][] = [ 'name' => $field['attname'], 'varName' => Text::toCamelName($field['attname']), - 'type' => $type = ('_' === $field['typname'][0] ? substr($field['typname'], 1) : $field['typname']), + 'type' => $type = ('_' === $field['typname'][0] ? substr((string) $field['typname'], 1) : $field['typname']), 'ndims' => $field['attndims'], 'phpType' => $phpType . '|null', 'phpDefinitionType' => $phpDefinitionType, @@ -392,7 +392,7 @@ private function dbFieldTypeToPhp(array $field): array $isArray = $field['typelem'] > 0; if ($isArray) { - $type = substr($field['typname'], 1); + $type = substr((string) $field['typname'], 1); } else { @@ -427,38 +427,18 @@ private function parseFieldDefaultValue(?string $poolName, string $type, $defaul $result = Db::query($poolName)->execute('select ' . $default); $resultAfterExec = $result->getScalar(); } - catch (\Throwable $_) + catch (\Throwable) { $resultAfterExec = $default; } - switch ($type) + + return match ($type) { - case 'int': - case 'int2': - case 'int4': - case 'int8': - case 'smallint': - case 'bigint': - case 'smallserial': - case 'serial': - case 'bigserial': - case 'serial2': - case 'serial4': - case 'serial8': - return (int) $resultAfterExec; - case 'bool': - case 'boolean': - return (bool) $resultAfterExec; - case 'double': - case 'float4': - case 'float8': - return (float) $resultAfterExec; - case 'varchar': - case 'char': - case 'text': - return (string) $resultAfterExec; - default: - return null; - } + 'int', 'int2', 'int4', 'int8', 'smallint', 'bigint', 'smallserial', 'serial', 'bigserial', 'serial2', 'serial4', 'serial8' => (int) $resultAfterExec, + 'bool', 'boolean' => (bool) $resultAfterExec, + 'double', 'float4', 'float8' => (float) $resultAfterExec, + 'varchar', 'char', 'text' => (string) $resultAfterExec, + default => null, + }; } } diff --git a/src/Components/pgsql/tests/PHPUnitHook.php b/src/Components/pgsql/tests/PHPUnitHook.php index 4ed4d08e6d..494228741f 100644 --- a/src/Components/pgsql/tests/PHPUnitHook.php +++ b/src/Components/pgsql/tests/PHPUnitHook.php @@ -17,9 +17,9 @@ class PHPUnitHook implements BeforeFirstTestHook { public function executeBeforeFirstTest(): void { - Event::on('IMI.APP_RUN', static function (EventParam $param) { + Event::on('IMI.APP_RUN', static function (EventParam $param): void { $param->stopPropagation(); - PoolManager::use(\in_array('pgsql', pdo_drivers()) ? 'maindb' : 'swoole', static function (IPoolResource $resource, IDb $db) { + PoolManager::use(\in_array('pgsql', pdo_drivers()) ? 'maindb' : 'swoole', static function (IPoolResource $resource, IDb $db): void { $truncateList = [ 'tb_article', 'tb_member', @@ -33,7 +33,7 @@ public function executeBeforeFirstTest(): void } }); }, 1); - App::run('Imi\Pgsql\Test', SwooleApp::class, static function () { + App::run('Imi\Pgsql\Test', SwooleApp::class, static function (): void { }); } } diff --git a/src/Components/pgsql/tests/Unit/Db/DbBaseTest.php b/src/Components/pgsql/tests/Unit/Db/DbBaseTest.php index bc8b69800f..7d9371bd67 100644 --- a/src/Components/pgsql/tests/Unit/Db/DbBaseTest.php +++ b/src/Components/pgsql/tests/Unit/Db/DbBaseTest.php @@ -200,7 +200,7 @@ public function testTransactionRollback(): void public function testTransUseCommit(): void { $id = null; - Db::transUse(static function (IDb $db) use (&$id) { + Db::transUse(static function (IDb $db) use (&$id): void { Assert::assertTrue($db->inTransaction()); $result = $db->exec("insert into tb_article(title,content,time)values('title', 'content', '2019-06-21')"); Assert::assertEquals(1, $result); @@ -226,7 +226,7 @@ public function testTransUseRollback(): void $id = null; try { - Db::transUse(static function (IDb $db) use (&$id) { + Db::transUse(static function (IDb $db) use (&$id): void { Assert::assertTrue($db->inTransaction()); $result = $db->exec("insert into tb_article(title,content,time)values('title', 'content', '2019-06-21')"); Assert::assertEquals(1, $result); @@ -253,7 +253,7 @@ public function testTransactionRollbackRollbackEvent(): void Assert::assertTrue($db->inTransaction()); $this->assertEquals(1, $db->getTransactionLevels()); $r1 = false; - $db->getTransaction()->onTransactionRollback(static function () use (&$r1) { + $db->getTransaction()->onTransactionRollback(static function () use (&$r1): void { $r1 = true; }); @@ -274,7 +274,7 @@ public function testTransactionRollbackCommitEvent(): void Assert::assertTrue($db->inTransaction()); $this->assertEquals(1, $db->getTransactionLevels()); $r1 = false; - $db->getTransaction()->onTransactionCommit(static function () use (&$r1) { + $db->getTransaction()->onTransactionCommit(static function () use (&$r1): void { $r1 = true; }); $db->commit(); diff --git a/src/Components/phar/config/imi-phar-cfg.php b/src/Components/phar/config/imi-phar-cfg.php index ccd91212bb..785458fce5 100644 --- a/src/Components/phar/config/imi-phar-cfg.php +++ b/src/Components/phar/config/imi-phar-cfg.php @@ -63,10 +63,10 @@ // 构建配置 'build' => [ - 'before' => static function () { + 'before' => static function (): void { // 构建前执行的代码 }, - 'after' => static function () { + 'after' => static function (): void { // 构建后执行的代码 }, ], diff --git a/src/Components/phar/phar_init.php b/src/Components/phar/phar_init.php index 7965cf4b8c..4ed5a3bc43 100644 --- a/src/Components/phar/phar_init.php +++ b/src/Components/phar/phar_init.php @@ -5,7 +5,7 @@ use Imi\App; use Imi\AppContexts; -(static function () { +(static function (): void { // putenv('IMI_MACRO_LOCK_FILE_DIR=/dev/shm'); putenv('IMI_MACRO_OUTPUT_DIR=' . (is_dir('/run/shm') && is_writable('/run/shm') ? '/run/shm' : sys_get_temp_dir())); diff --git a/src/Components/phar/src/PharHandler.php b/src/Components/phar/src/PharHandler.php index 463e8bd6da..9e59075577 100644 --- a/src/Components/phar/src/PharHandler.php +++ b/src/Components/phar/src/PharHandler.php @@ -6,7 +6,7 @@ use Imi\Bean\ReflectionUtil; -(static function () { +(static function (): void { $refMethod = new \ReflectionMethod(\Composer\XdebugHandler\XdebugHandler::class, 'check'); $returnType = $refMethod->getReturnType(); if ('void' === ReflectionUtil::getTypeCode($returnType)) diff --git a/src/Components/phar/src/PharService.php b/src/Components/phar/src/PharService.php index 4c9ac2dd23..9b8baef460 100644 --- a/src/Components/phar/src/PharService.php +++ b/src/Components/phar/src/PharService.php @@ -155,7 +155,7 @@ public function build(?string $container): bool $outputDir = \dirname($outputPhar); if (!is_dir($outputDir)) { - mkdir($outputDir, 0755, true); + mkdir($outputDir, 0o755, true); } if (file_exists($outputPhar)) @@ -229,7 +229,7 @@ public function outputResources(): bool $destFileName = $this->outputDir . \DIRECTORY_SEPARATOR . $value; } $destDir = \dirname($destFileName); - if (!is_dir($destDir) && !mkdir($destDir, 0755, true)) + if (!is_dir($destDir) && !mkdir($destDir, 0o755, true)) { $this->output->writeln("mkdir {$destDir} failed"); diff --git a/src/Components/phar/tests/run-tests.php b/src/Components/phar/tests/run-tests.php index 80535fed18..312db67dfe 100644 --- a/src/Components/phar/tests/run-tests.php +++ b/src/Components/phar/tests/run-tests.php @@ -70,7 +70,7 @@ ], $testProjectDir, [ // 'COMPOSER_DISABLE_NETWORK' => '1', // 本地测试提升速度用 ])) - ->mustRun(static function ($type, $buffer) { + ->mustRun(static function ($type, $buffer): void { echo $buffer; }); @@ -98,7 +98,7 @@ '--no-interaction', '--no-ansi', ], $testProjectDir)) - ->mustRun(static function ($type, $buffer) { + ->mustRun(static function ($type, $buffer): void { echo $buffer; }); @@ -112,7 +112,7 @@ '--no-interaction', '--no-ansi', ], $testProjectDir)) - ->mustRun(static function ($type, $buffer) { + ->mustRun(static function ($type, $buffer): void { echo $buffer; }); } @@ -126,7 +126,7 @@ '--no-ansi', ], $testProjectDir)); - $testServer->start(static function ($type, $buffer) { + $testServer->start(static function ($type, $buffer): void { echo $buffer; }); $testSuccess = false; diff --git a/src/Components/queue/example/Listener/WorkerStartListener.php b/src/Components/queue/example/Listener/WorkerStartListener.php index 8fbf4793fa..e15f04ebb2 100644 --- a/src/Components/queue/example/Listener/WorkerStartListener.php +++ b/src/Components/queue/example/Listener/WorkerStartListener.php @@ -30,13 +30,13 @@ class WorkerStartListener implements IEventListener public function handle(EventParam $e): void { // 每 1 秒投递进 test1 队列 - Timer::tick(1000, function () { + Timer::tick(1000, function (): void { $message = new Message(); $message->setMessage((string) time()); $this->imiQueue->getQueue('test1')->push($message); }); // 每 3 秒投递进 test2 队列 - Timer::tick(3000, function () { + Timer::tick(3000, function (): void { $message = new Message(); $message->setMessage((string) time()); $this->imiQueue->getQueue('test2')->push($message); diff --git a/src/Components/queue/src/Driver/RedisQueueDriver.php b/src/Components/queue/src/Driver/RedisQueueDriver.php index 9d7165ee91..6a292ad4d0 100644 --- a/src/Components/queue/src/Driver/RedisQueueDriver.php +++ b/src/Components/queue/src/Driver/RedisQueueDriver.php @@ -34,11 +34,6 @@ class RedisQueueDriver implements IQueueDriver */ protected string $prefix = 'imi:'; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 循环尝试 pop 的时间间隔,单位:秒. */ @@ -46,15 +41,18 @@ class RedisQueueDriver implements IQueueDriver private ?string $keyName = null; - public function __construct(string $name, array $config = []) + public function __construct( + /** + * 队列名称. + */ + protected string $name, array $config = []) { - $this->name = $name; $this->traitConstruct($config); } public function __init(): void { - Redis::use(function (\Imi\Redis\RedisHandler $redis) { + Redis::use(function (\Imi\Redis\RedisHandler $redis): void { if ($redis->isCluster()) { $this->keyName = '{' . $this->name . '}'; @@ -319,7 +317,7 @@ public function clear($queueType = null): void $keys[] = $this->getQueueKey($tmpQueueType); } - Redis::use(static function (\Imi\Redis\RedisHandler $redis) use ($keys) { + Redis::use(static function (\Imi\Redis\RedisHandler $redis) use ($keys): void { $redis->del(...$keys); }, $this->poolName, true); } @@ -404,17 +402,12 @@ public function status(): QueueStatus foreach (QueueType::getValues() as $value) { $data = QueueType::getData($value); - switch ($data['type']) + $count = match ($data['type']) { - case 'list': - $count = $redis->lLen($this->getQueueKey($value)); - break; - case 'zset': - $count = $redis->zCard($this->getQueueKey($value)); - break; - default: - throw new QueueException('Invalid type ' . $data['type']); - } + 'list' => $redis->lLen($this->getQueueKey($value)), + 'zset' => $redis->zCard($this->getQueueKey($value)), + default => throw new QueueException('Invalid type ' . $data['type']), + }; $status[strtolower(QueueType::getName($value))] = $count; } diff --git a/src/Components/queue/src/Driver/RedisStreamQueueDriver.php b/src/Components/queue/src/Driver/RedisStreamQueueDriver.php index 93981657fa..470b7a9f40 100644 --- a/src/Components/queue/src/Driver/RedisStreamQueueDriver.php +++ b/src/Components/queue/src/Driver/RedisStreamQueueDriver.php @@ -37,11 +37,6 @@ class RedisStreamQueueDriver implements IQueueDriver */ protected string $prefix = 'imi:'; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 队列最大长度. * @@ -81,15 +76,18 @@ class RedisStreamQueueDriver implements IQueueDriver private ?string $keyName = null; - public function __construct(string $name, array $config = []) + public function __construct( + /** + * 队列名称. + */ + protected string $name, array $config = []) { - $this->name = $name; $this->traitConstruct($config); } public function __init(): void { - Redis::use(function (\Imi\Redis\RedisHandler $redis) { + Redis::use(function (\Imi\Redis\RedisHandler $redis): void { if ($redis->isCluster()) { $this->keyName = '{' . $this->name . '}'; @@ -211,7 +209,7 @@ public function delete(IMessage $message): bool */ public function clear($queueType = null): void { - Redis::use(function (\Imi\Redis\RedisHandler $redis) { + Redis::use(function (\Imi\Redis\RedisHandler $redis): void { $redis->del($this->getQueueKey()); }, $this->poolName, true); } diff --git a/src/Components/queue/src/Model/QueueConfig.php b/src/Components/queue/src/Model/QueueConfig.php index 8b1fd1a55c..8e3aa32e25 100644 --- a/src/Components/queue/src/Model/QueueConfig.php +++ b/src/Components/queue/src/Model/QueueConfig.php @@ -6,11 +6,6 @@ class QueueConfig { - /** - * 队列名称. - */ - private string $name = ''; - /** * 使用的队列驱动. */ @@ -53,9 +48,12 @@ class QueueConfig */ private string $consumer = ''; - public function __construct(string $name, array $data) + public function __construct( + /** + * 队列名称. + */ + private readonly string $name, array $data) { - $this->name = $name; if (isset($data['driver'])) { $this->driver = $data['driver']; diff --git a/src/Components/queue/src/Partial/SwooleBaseQueueConsumerPartial.php b/src/Components/queue/src/Partial/SwooleBaseQueueConsumerPartial.php index c812054f0c..790ee8ec55 100644 --- a/src/Components/queue/src/Partial/SwooleBaseQueueConsumerPartial.php +++ b/src/Components/queue/src/Partial/SwooleBaseQueueConsumerPartial.php @@ -45,7 +45,7 @@ public function start(?int $co = null): void { $co = $config->getCo(); } - $task = function () use ($config) { + $task = function () use ($config): void { while ($this->working) { try @@ -65,7 +65,7 @@ public function start(?int $co = null): void /** * {@inheritDoc} */ - public function run(ITaskParam $param) + public function run(ITaskParam $param): void { ($param->getData()['task'])(); } @@ -119,7 +119,7 @@ protected function task(QueueConfig $config): void $context = RequestContext::getContext(); $handlerName = 'QueueDriver.handler.' . $queue->getName(); $handler = $context[$handlerName] ?? null; - goWait(function () use ($queue, $message, $handlerName, $handler) { + goWait(function () use ($queue, $message, $handlerName, $handler): void { RequestContext::set($handlerName, $handler); Event::trigger('IMI.QUEUE.CONSUMER.BEFORE_CONSUME', [ 'queue' => $queue, diff --git a/src/Components/queue/src/Process/SwooleQueueConsumerProcess.php b/src/Components/queue/src/Process/SwooleQueueConsumerProcess.php index 1d6929aa8f..fde9ea670c 100644 --- a/src/Components/queue/src/Process/SwooleQueueConsumerProcess.php +++ b/src/Components/queue/src/Process/SwooleQueueConsumerProcess.php @@ -40,7 +40,7 @@ class SwooleQueueConsumerProcess extends BaseProcess public function run(\Swoole\Process $process): void { $running = true; - \Imi\Event\Event::on('IMI.PROCESS.END', static function () use (&$running) { + \Imi\Event\Event::on('IMI.PROCESS.END', static function () use (&$running): void { $running = false; }, ImiPriority::IMI_MAX); $imiQueue = $this->imiQueue; @@ -65,7 +65,7 @@ public function run(\Swoole\Process $process): void { $processPools[] = $processPool = new \Imi\Swoole\Process\Pool($options['process']); $configs = $options['configs']; - $processPool->on('WorkerStart', function (\Imi\Swoole\Process\Pool\WorkerEventParam $e) use ($group, $configs) { + $processPool->on('WorkerStart', function (\Imi\Swoole\Process\Pool\WorkerEventParam $e) use ($group, $configs): void { $processName = 'QueueConsumer-' . $group; // 进程开始事件 ImiEvent::trigger('IMI.PROCESS.BEGIN', [ @@ -78,7 +78,7 @@ public function run(\Swoole\Process $process): void /** @var \Imi\Queue\Model\QueueConfig[] $configs */ foreach ($configs as $config) { - Coroutine::create(function () use ($config) { + Coroutine::create(function () use ($config): void { /** @var \Imi\Queue\Service\BaseQueueConsumer $queueConsumer */ $queueConsumer = $this->consumers[] = App::newInstance($config->getConsumer(), $config->getName()); $queueConsumer->start(); @@ -86,7 +86,7 @@ public function run(\Swoole\Process $process): void } }); // 工作进程退出事件-可选 - $processPool->on('WorkerExit', function (\Imi\Swoole\Process\Pool\WorkerEventParam $e) use ($group) { + $processPool->on('WorkerExit', function (\Imi\Swoole\Process\Pool\WorkerEventParam $e) use ($group): void { // 做一些释放操作 foreach ($this->consumers as $consumer) { @@ -116,7 +116,7 @@ public function run(\Swoole\Process $process): void else { Log::warning('@app.beans.imiQueue.list is empty'); - Coroutine::create(static function () use (&$running) { + Coroutine::create(static function () use (&$running): void { // @phpstan-ignore-next-line while ($running) { diff --git a/src/Components/queue/src/Service/BaseQueueConsumer.php b/src/Components/queue/src/Service/BaseQueueConsumer.php index cc7ddf6a46..b593880e2e 100644 --- a/src/Components/queue/src/Service/BaseQueueConsumer.php +++ b/src/Components/queue/src/Service/BaseQueueConsumer.php @@ -18,19 +18,17 @@ abstract class BaseQueueConsumer */ protected QueueService $imiQueue; - /** - * 队列名称. - */ - protected string $name = ''; - /** * 是否正在工作. */ protected bool $working = false; - public function __construct(?string $name = null) - { - $this->name = $name; + public function __construct( + /** + * 队列名称. + */ + protected ?string $name = null + ) { } /** diff --git a/src/Components/queue/src/Service/QueueService.php b/src/Components/queue/src/Service/QueueService.php index 0c10a73f60..ec2c50b85b 100644 --- a/src/Components/queue/src/Service/QueueService.php +++ b/src/Components/queue/src/Service/QueueService.php @@ -99,11 +99,7 @@ public function getQueue(?string $name = null): IQueueDriver $name = $config->getName(); } $queueInstances = &$this->queueInstances; - if (isset($queueInstances[$name])) - { - return $queueInstances[$name]; - } - return $queueInstances[$name] = App::newInstance($config->getDriver(), $name, $config->getConfig()); + return $queueInstances[$name] ?? ($queueInstances[$name] = App::newInstance($config->getDriver(), $name, $config->getConfig())); } } diff --git a/src/Components/queue/src/Tool/QueueTool.php b/src/Components/queue/src/Tool/QueueTool.php index 4659f633ef..5cad7067d9 100644 --- a/src/Components/queue/src/Tool/QueueTool.php +++ b/src/Components/queue/src/Tool/QueueTool.php @@ -21,10 +21,8 @@ class QueueTool extends BaseCommand * @CommandAction(name="status", description="获取队列状态") * * @Argument(name="queue", type="string", required=true) - * - * @return void */ - public function status(string $queue) + public function status(string $queue): void { fwrite(\STDOUT, json_encode(Queue::getQueue($queue)->status(), \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) . \PHP_EOL); } @@ -35,10 +33,8 @@ public function status(string $queue) * @CommandAction(name="restoreFail", description="将失败消息恢复到队列") * * @Argument(name="queue", type="string", required=true) - * - * @return void */ - public function restoreFail(string $queue) + public function restoreFail(string $queue): void { fwrite(\STDOUT, Queue::getQueue($queue)->restoreFailMessages() . \PHP_EOL); } @@ -49,10 +45,8 @@ public function restoreFail(string $queue) * @CommandAction(name="restoreTimeout", description="将超时消息恢复到队列") * * @Argument(name="queue", type="string", required=true) - * - * @return void */ - public function restoreTimeout(string $queue) + public function restoreTimeout(string $queue): void { fwrite(\STDOUT, Queue::getQueue($queue)->restoreTimeoutMessages() . \PHP_EOL); } diff --git a/src/Components/queue/tests/PHPUnitHook.php b/src/Components/queue/tests/PHPUnitHook.php index b1c259dae5..ef88bf426a 100644 --- a/src/Components/queue/tests/PHPUnitHook.php +++ b/src/Components/queue/tests/PHPUnitHook.php @@ -18,7 +18,7 @@ class PHPUnitHook implements BeforeFirstTestHook, AfterLastTestHook public function executeBeforeFirstTest(): void { $this->channel = $channel = new Channel(1); - Coroutine::create(static fn () => App::run('QueueApp', SwooleApp::class, static function () use ($channel) { + Coroutine::create(static fn () => App::run('QueueApp', SwooleApp::class, static function () use ($channel): void { $channel->push(1); $channel->pop(); })); diff --git a/src/Components/queue/tests/Queue/BaseQueueTest.php b/src/Components/queue/tests/Queue/BaseQueueTest.php index 584f6cebed..93f7357c64 100644 --- a/src/Components/queue/tests/Queue/BaseQueueTest.php +++ b/src/Components/queue/tests/Queue/BaseQueueTest.php @@ -41,8 +41,8 @@ public function testPopTimeout(): void { $message = $totalTime = null; $channel = new Channel(1); - Coroutine::create(function () use (&$message, &$totalTime, $channel) { - Coroutine::create(function () use ($channel) { + Coroutine::create(function () use (&$message, &$totalTime, $channel): void { + Coroutine::create(function () use ($channel): void { Coroutine::sleep(1); $message = new Message(); $message->setMessage('a'); diff --git a/src/Components/rate-limit/src/RateLimiter.php b/src/Components/rate-limit/src/RateLimiter.php index 892561c853..9de3e1caf9 100644 --- a/src/Components/rate-limit/src/RateLimiter.php +++ b/src/Components/rate-limit/src/RateLimiter.php @@ -50,7 +50,7 @@ public static function limit(string $name, int $capacity, ?callable $callback = } else { - return static::defaultCallback($name); + static::defaultCallback($name); } } else @@ -90,7 +90,7 @@ public static function limitBlock(string $name, int $capacity, ?callable $callba return true; } - catch (TimeoutException $ex) + catch (TimeoutException) { if ($callback) { @@ -98,7 +98,7 @@ public static function limitBlock(string $name, int $capacity, ?callable $callba } else { - return static::defaultCallback($name); + static::defaultCallback($name); } } } @@ -126,10 +126,8 @@ public static function getTokens(string $name, int $capacity, ?int $fill = null, * 默认限流回调. * * @param string $name 限流器名称 - * - * @return mixed */ - public static function defaultCallback(string $name) + public static function defaultCallback(string $name): never { throw new RateLimitException(sprintf('%s Rate Limit', $name)); } diff --git a/src/Components/rate-limit/src/Storage/ImiRedisStorage.php b/src/Components/rate-limit/src/Storage/ImiRedisStorage.php index e35647e415..60206a7b08 100644 --- a/src/Components/rate-limit/src/Storage/ImiRedisStorage.php +++ b/src/Components/rate-limit/src/Storage/ImiRedisStorage.php @@ -19,17 +19,7 @@ final class ImiRedisStorage implements Storage, GlobalScope /** * The mutex. */ - private PHPRedisMutex $mutex; - - /** - * The redis API. - */ - private RedisHandler $redis; - - /** - * The key. - */ - private string $key = ''; + private readonly PHPRedisMutex $mutex; /** * Sets the connected Redis API. @@ -37,23 +27,19 @@ final class ImiRedisStorage implements Storage, GlobalScope * The Redis API needs to be connected yet. I.e. Redis::connect() was * called already. * - * @param string $name the resource name + * @param string $key the resource name * @param \Imi\Redis\RedisHandler $redis the Redis API */ - public function __construct(string $name, RedisHandler $redis, int $timeout = 3) + public function __construct(private readonly string $key, private readonly RedisHandler $redis, int $timeout = 3) { - $this->key = $name; - $this->redis = $redis; // @phpstan-ignore-next-line - $this->mutex = new PHPRedisMutex([$redis], $name, $timeout); + $this->mutex = new PHPRedisMutex([$redis], $key, $timeout); } /** * @param float $microtime - * - * @return void */ - public function bootstrap($microtime) + public function bootstrap($microtime): void { $this->setMicrotime($microtime); } @@ -73,10 +59,7 @@ public function isBootstrapped() } } - /** - * @return void - */ - public function remove() + public function remove(): void { try { @@ -95,10 +78,8 @@ public function remove() * @SuppressWarnings(PHPMD) * * @param float $microtime - * - * @return void */ - public function setMicrotime($microtime) + public function setMicrotime($microtime): void { try { @@ -146,10 +127,7 @@ public function getMutex() return $this->mutex; } - /** - * @return void - */ - public function letMicrotimeUnchanged() + public function letMicrotimeUnchanged(): void { } } diff --git a/src/Components/rate-limit/src/WorkerLimiter.php b/src/Components/rate-limit/src/WorkerLimiter.php index a01a281d56..00956ad484 100644 --- a/src/Components/rate-limit/src/WorkerLimiter.php +++ b/src/Components/rate-limit/src/WorkerLimiter.php @@ -37,7 +37,7 @@ public static function call(callable $callable, string $name, int $max, ?float $ } else { - return static::defaultCallback($name); + static::defaultCallback($name); } } // 执行任务 @@ -95,7 +95,7 @@ public static function callBlock(callable $callable, string $name, int $max, ?fl } else { - return static::defaultCallback($name); + static::defaultCallback($name); } } continue; @@ -113,10 +113,8 @@ public static function callBlock(callable $callable, string $name, int $max, ?fl * 默认限流回调. * * @param string $name 限流器名称 - * - * @return mixed */ - public static function defaultCallback(string $name) + public static function defaultCallback(string $name): never { throw new RateLimitException(sprintf('%s Worker Limit', $name)); } diff --git a/src/Components/roadrunner/bootstrap.php b/src/Components/roadrunner/bootstrap.php index e6a02e6d1b..f4642f6213 100644 --- a/src/Components/roadrunner/bootstrap.php +++ b/src/Components/roadrunner/bootstrap.php @@ -6,7 +6,7 @@ use Imi\App; -return static function () { +return static function (): void { $path = null; if (\defined('IMI_IN_PHAR') && IMI_IN_PHAR) @@ -15,7 +15,7 @@ } elseif (!class_exists(\Imi\App::class)) { - (static function () use (&$path) { + (static function () use (&$path): void { foreach ([ $_SERVER['PWD'] ?? null, getcwd(), diff --git a/src/Components/roadrunner/src/HotUpdate/HotUpdateProcess.php b/src/Components/roadrunner/src/HotUpdate/HotUpdateProcess.php index 348be0dc6c..8cba7fa575 100644 --- a/src/Components/roadrunner/src/HotUpdate/HotUpdateProcess.php +++ b/src/Components/roadrunner/src/HotUpdate/HotUpdateProcess.php @@ -250,7 +250,7 @@ private function beginBuildRuntime(array $changedFiles): void */ private function closeBuildRuntime(): void { - $closePipes = static function (?array $buildRuntimePipes) { + $closePipes = static function (?array $buildRuntimePipes): void { if (null !== $buildRuntimePipes) { foreach ($buildRuntimePipes as $pipe) diff --git a/src/Components/roadrunner/src/Http/Message/RoadRunnerRequest.php b/src/Components/roadrunner/src/Http/Message/RoadRunnerRequest.php index cf0a0d3ae4..7a5abf9aa8 100644 --- a/src/Components/roadrunner/src/Http/Message/RoadRunnerRequest.php +++ b/src/Components/roadrunner/src/Http/Message/RoadRunnerRequest.php @@ -49,7 +49,7 @@ public function withParsedBody($data): static { $result = parent::withParsedBody($data); $contentType = $_SERVER['CONTENT_TYPE'] ?? ''; - if (MediaType::APPLICATION_FORM_URLENCODED === $contentType || str_starts_with($contentType, MediaType::MULTIPART_FORM_DATA)) + if (MediaType::APPLICATION_FORM_URLENCODED === $contentType || str_starts_with((string) $contentType, MediaType::MULTIPART_FORM_DATA)) { $result->post = $_POST = $data; } diff --git a/src/Components/roadrunner/src/Http/Message/RoadRunnerResponse.php b/src/Components/roadrunner/src/Http/Message/RoadRunnerResponse.php index 6495c86a03..08e8a30b1a 100644 --- a/src/Components/roadrunner/src/Http/Message/RoadRunnerResponse.php +++ b/src/Components/roadrunner/src/Http/Message/RoadRunnerResponse.php @@ -12,17 +12,14 @@ class RoadRunnerResponse extends Response { - protected ?\Spiral\RoadRunner\Http\PSR7Worker $worker = null; - /** * 是否可写. */ protected bool $isWritable = true; - public function __construct(?\Spiral\RoadRunner\Http\PSR7Worker $worker = null) + public function __construct(protected ?\Spiral\RoadRunner\Http\PSR7Worker $worker = null) { parent::__construct(); - $this->worker = $worker; } /** @@ -65,7 +62,7 @@ public function send(): static protected function cookieArrayToHeader(array $cookie): string { - $header = rawurlencode($cookie['key']) . '=' . rawurlencode($cookie['value']); + $header = rawurlencode((string) $cookie['key']) . '=' . rawurlencode((string) $cookie['value']); if ($cookie['expire'] > 0) { $header .= '; Expires=' . gmdate(\DateTime::COOKIE, $cookie['expire']); diff --git a/src/Components/roadrunner/src/RoadRunnerApp.php b/src/Components/roadrunner/src/RoadRunnerApp.php index d9f1d597f0..b6283d17a5 100644 --- a/src/Components/roadrunner/src/RoadRunnerApp.php +++ b/src/Components/roadrunner/src/RoadRunnerApp.php @@ -29,7 +29,7 @@ class RoadRunnerApp extends BaseApp public function __construct(string $namespace) { parent::__construct($namespace); - Event::one('IMI.SCAN_APP', function () { + Event::one('IMI.SCAN_APP', function (): void { $this->onScanApp(); }); } diff --git a/src/Components/roadrunner/src/Server/Http/Server.php b/src/Components/roadrunner/src/Server/Http/Server.php index c72187af8a..2037da7f25 100644 --- a/src/Components/roadrunner/src/Server/Http/Server.php +++ b/src/Components/roadrunner/src/Server/Http/Server.php @@ -174,7 +174,7 @@ public function start(): void $rrProcess->setTty(true); } } - catch (\Throwable $th) + catch (\Throwable) { } /** @var Process|null $hotUpdateProcess */ diff --git a/src/Components/roadrunner/tests/bootstrap.php b/src/Components/roadrunner/tests/bootstrap.php index 68c7341afd..7b6e81ab7c 100644 --- a/src/Components/roadrunner/tests/bootstrap.php +++ b/src/Components/roadrunner/tests/bootstrap.php @@ -64,7 +64,7 @@ function checkHttpServerStatus(): bool echo "Starting {$name}...", \PHP_EOL; shell_exec("{$cmd}"); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { // stop server $cmd = $options['stop']; if ('\\' === \DIRECTORY_SEPARATOR) diff --git a/src/Components/rpc/src/Client/Pool/RpcClientResource.php b/src/Components/rpc/src/Client/Pool/RpcClientResource.php index 91551c737c..6701ca2580 100644 --- a/src/Components/rpc/src/Client/Pool/RpcClientResource.php +++ b/src/Components/rpc/src/Client/Pool/RpcClientResource.php @@ -12,15 +12,13 @@ */ class RpcClientResource extends BasePoolResource { - /** - * rpcClient对象 - */ - private ?IRpcClient $client = null; - - public function __construct(\Imi\Pool\Interfaces\IPool $pool, IRpcClient $client) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * rpcClient对象 + */ + private readonly ?IRpcClient $client) { parent::__construct($pool); - $this->client = $client; } /** diff --git a/src/Components/rpc/src/Route/Annotation/Parser/RpcControllerParser.php b/src/Components/rpc/src/Route/Annotation/Parser/RpcControllerParser.php index 76e6759666..b71bf1244f 100644 --- a/src/Components/rpc/src/Route/Annotation/Parser/RpcControllerParser.php +++ b/src/Components/rpc/src/Route/Annotation/Parser/RpcControllerParser.php @@ -21,7 +21,7 @@ class RpcControllerParser extends BaseParser */ public function parse(\Imi\Bean\Annotation\Base $annotation, string $className, string $target, string $targetName): void { - $eventName = 'IMI.RPC.ANNOTATION.PARSER:' . \get_class($annotation); + $eventName = 'IMI.RPC.ANNOTATION.PARSER:' . $annotation::class; Event::trigger($eventName, compact('annotation', 'className', 'target', 'targetName'), $this); } @@ -37,7 +37,7 @@ public function getByServer(string $serverName, string $controllerAnnotationClas $namespaces = Config::get('@server.' . $serverName . '.beanScan', []); foreach ($namespaces as &$namespace) { - if (!str_ends_with($namespace, '\\')) + if (!str_ends_with((string) $namespace, '\\')) { $namespace .= '\\'; } @@ -49,7 +49,7 @@ public function getByServer(string $serverName, string $controllerAnnotationClas $class = $option->getClass(); foreach ($namespaces as $namespace) { - if (str_starts_with($class, $namespace)) + if (str_starts_with($class, (string) $namespace)) { $result[$class] = $option; continue 2; diff --git a/src/Components/shared-memory/src/Pool/ClientResource.php b/src/Components/shared-memory/src/Pool/ClientResource.php index f4fb2af6d4..8164b0dc82 100644 --- a/src/Components/shared-memory/src/Pool/ClientResource.php +++ b/src/Components/shared-memory/src/Pool/ClientResource.php @@ -12,15 +12,13 @@ */ class ClientResource extends BasePoolResource { - /** - * 客户端对象 - */ - private ?Client $client = null; - - public function __construct(\Imi\Pool\Interfaces\IPool $pool, Client $client) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * 客户端对象 + */ + private readonly ?Client $client) { parent::__construct($pool); - $this->client = $client; } /** diff --git a/src/Components/smarty/src/smarty-plugins/smarty_internal_compile_private_special_variable.php b/src/Components/smarty/src/smarty-plugins/smarty_internal_compile_private_special_variable.php index 5d7c1c61f3..fca2c5a821 100644 --- a/src/Components/smarty/src/smarty-plugins/smarty_internal_compile_private_special_variable.php +++ b/src/Components/smarty/src/smarty-plugins/smarty_internal_compile_private_special_variable.php @@ -27,7 +27,7 @@ class smarty_internal_compile_private_special_variable extends Smarty_Internal_C public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { $compiled_ref = null; - $_index = preg_split("/\]\[/", substr($parameter, 1, \strlen($parameter) - 2)); + $_index = preg_split("/\]\[/", substr((string) $parameter, 1, \strlen((string) $parameter) - 2)); $variable = strtolower($compiler->getId($_index[0])); // @phpstan-ignore-next-line if (false === $variable) diff --git a/src/Components/smarty/tests/bootstrap.php b/src/Components/smarty/tests/bootstrap.php index c2736789f3..9483cfbe93 100644 --- a/src/Components/smarty/tests/bootstrap.php +++ b/src/Components/smarty/tests/bootstrap.php @@ -46,7 +46,7 @@ function startServer(): void echo "Starting {$name}...", \PHP_EOL; echo shell_exec("{$cmd}"), \PHP_EOL; - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { // stop server $cmd = $options['stop']; echo "Stoping {$name}...", \PHP_EOL; @@ -63,7 +63,7 @@ function startServer(): void throw new \RuntimeException("{$name} start failed"); } } - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { checkPorts([13456]); }); } diff --git a/src/Components/snowflake/src/ImiRedisResolver.php b/src/Components/snowflake/src/ImiRedisResolver.php index a52b48e54e..e427a55f54 100644 --- a/src/Components/snowflake/src/ImiRedisResolver.php +++ b/src/Components/snowflake/src/ImiRedisResolver.php @@ -14,13 +14,6 @@ class ImiRedisResolver implements SequenceResolver */ protected string $prefix = ''; - /** - * Redis 连接池名称. - * - * 为 NULL 则使用默认连接池 - */ - protected ?string $redisPool = null; - public const SEQUENCE_LUA = <<<'LUA' if(redis.call('exists',KEYS[1])<1 and redis.call('psetex',KEYS[1],ARGV[2],ARGV[1])) then @@ -30,9 +23,14 @@ class ImiRedisResolver implements SequenceResolver end LUA; - public function __construct(?string $redisPool = null) - { - $this->redisPool = $redisPool; + public function __construct( + /** + * Redis 连接池名称. + * + * 为 NULL 则使用默认连接池 + */ + protected ?string $redisPool = null + ) { } /** diff --git a/src/Components/snowflake/tests/PHPUnitHook.php b/src/Components/snowflake/tests/PHPUnitHook.php index 3fff719737..f5d2dbd47c 100644 --- a/src/Components/snowflake/tests/PHPUnitHook.php +++ b/src/Components/snowflake/tests/PHPUnitHook.php @@ -12,7 +12,7 @@ class PHPUnitHook implements BeforeFirstTestHook { public function executeBeforeFirstTest(): void { - App::run('Imi\Snowflake\Test', CliApp::class, static function () { + App::run('Imi\Snowflake\Test', CliApp::class, static function (): void { }); } } diff --git a/src/Components/swoole-tracker/example/HttpServer/ApiServer/Controller/IndexController.php b/src/Components/swoole-tracker/example/HttpServer/ApiServer/Controller/IndexController.php index 4554cf6cd3..cb7924f576 100644 --- a/src/Components/swoole-tracker/example/HttpServer/ApiServer/Controller/IndexController.php +++ b/src/Components/swoole-tracker/example/HttpServer/ApiServer/Controller/IndexController.php @@ -30,10 +30,8 @@ public function index() /** * @Action - * - * @return void */ - public function fail() + public function fail(): void { throw new \RuntimeException('test gg'); } diff --git a/src/Components/swoole-tracker/example/TCPServer/test-client/eof-client.php b/src/Components/swoole-tracker/example/TCPServer/test-client/eof-client.php index daae3e071f..85e00e781e 100644 --- a/src/Components/swoole-tracker/example/TCPServer/test-client/eof-client.php +++ b/src/Components/swoole-tracker/example/TCPServer/test-client/eof-client.php @@ -4,7 +4,7 @@ // EOF自动分包的客户端测试 -Swoole\Coroutine\run(static function () { +Swoole\Coroutine\run(static function (): void { $client = new Swoole\Coroutine\Client(\SWOOLE_SOCK_TCP); $client->set([ diff --git a/src/Components/swoole-tracker/example/TCPServer/test-client/fixed-client.php b/src/Components/swoole-tracker/example/TCPServer/test-client/fixed-client.php index df27dcc63f..20b4a4365f 100644 --- a/src/Components/swoole-tracker/example/TCPServer/test-client/fixed-client.php +++ b/src/Components/swoole-tracker/example/TCPServer/test-client/fixed-client.php @@ -6,7 +6,7 @@ // EOF自动分包的客户端测试 -Swoole\Coroutine\run(static function () { +Swoole\Coroutine\run(static function (): void { $client = new Client(\SWOOLE_SOCK_TCP); $client->set([ diff --git a/src/Components/swoole-tracker/example/UDPServer/test-client/client.php b/src/Components/swoole-tracker/example/UDPServer/test-client/client.php index 913ad70c76..4b0f13eab8 100644 --- a/src/Components/swoole-tracker/example/UDPServer/test-client/client.php +++ b/src/Components/swoole-tracker/example/UDPServer/test-client/client.php @@ -2,7 +2,7 @@ declare(strict_types=1); -Swoole\Coroutine\run(static function () { +Swoole\Coroutine\run(static function (): void { $client = new Swoole\Coroutine\Client(\SWOOLE_SOCK_UDP); $client->connect('127.0.0.1', 8083); diff --git a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/HandShake.php b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/HandShake.php index 20ff95a433..ecad807e3f 100644 --- a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/HandShake.php +++ b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/HandShake.php @@ -26,10 +26,8 @@ class HandShake extends HttpController * @Action * * @Route("/testHandShake") - * - * @return void */ - public function index() + public function index(): void { // 手动握手处理 diff --git a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/IndexController.php b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/IndexController.php index 1838b33252..3fb8950560 100644 --- a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/IndexController.php +++ b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/Http/IndexController.php @@ -28,10 +28,8 @@ class IndexController extends HttpController * @Route("/") * * @WSConfig(parserClass=\Imi\Server\DataParser\JsonObjectParser::class) - * - * @return void */ - public function index() + public function index(): void { // 握手处理,什么都不做,框架会帮你做好 } diff --git a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/TestController.php b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/TestController.php index 828820eef0..6dd4f8b0ff 100644 --- a/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/TestController.php +++ b/src/Components/swoole-tracker/example/WebSocketServer/MainServer/Controller/TestController.php @@ -48,10 +48,8 @@ public function login($data) * @WSMiddleware(Imi\SwooleTracker\Example\WebSocketServer\MainServer\Middleware\Test::class) * * @param mixed $data - * - * @return void */ - public function send($data) + public function send($data): void { $message = ConnectionContext::get('username') . ':' . $data->message; Server::sendToGroup('g1', $message); diff --git a/src/Components/swoole/bootstrap.php b/src/Components/swoole/bootstrap.php index 3218549387..1e12ceb81c 100644 --- a/src/Components/swoole/bootstrap.php +++ b/src/Components/swoole/bootstrap.php @@ -8,9 +8,9 @@ use Imi\Event\Event; use Imi\Log\Log; -return static function () { +return static function (): void { $status = 0; - \Swoole\Coroutine\run(static function () use (&$status) { + \Swoole\Coroutine\run(static function () use (&$status): void { try { $path = null; @@ -21,7 +21,7 @@ } elseif (!class_exists(\Imi\App::class)) { - (static function () use (&$path) { + (static function () use (&$path): void { foreach ([ $_SERVER['PWD'] ?? null, getcwd(), diff --git a/src/Components/swoole/src/Async/SwooleHandler.php b/src/Components/swoole/src/Async/SwooleHandler.php index b1abc07c7e..73a58cfb5d 100644 --- a/src/Components/swoole/src/Async/SwooleHandler.php +++ b/src/Components/swoole/src/Async/SwooleHandler.php @@ -18,7 +18,7 @@ public function exec(callable $callable): IAsyncResult { $channel = new Channel(); $result = new SwooleResult($channel); - imigo(static function () use ($callable, $channel) { + imigo(static function () use ($callable, $channel): void { try { $channel->push([ @@ -45,7 +45,7 @@ public function defer(callable $callable): IAsyncResult { $channel = new Channel(); $result = new SwooleResult($channel); - Coroutine::defer(static function () use ($callable, $channel) { + Coroutine::defer(static function () use ($callable, $channel): void { try { $channel->push([ @@ -72,7 +72,7 @@ public function deferAsync(callable $callable): IAsyncResult { $channel = new Channel(); $result = new SwooleResult($channel); - Coroutine::defer(static fn () => imigo(static function () use ($callable, $channel) { + Coroutine::defer(static fn () => imigo(static function () use ($callable, $channel): void { try { $channel->push([ diff --git a/src/Components/swoole/src/Async/SwooleResult.php b/src/Components/swoole/src/Async/SwooleResult.php index 12319d9d2d..27c9dcb09b 100644 --- a/src/Components/swoole/src/Async/SwooleResult.php +++ b/src/Components/swoole/src/Async/SwooleResult.php @@ -11,13 +11,10 @@ class SwooleResult implements IAsyncResult { - private ?Channel $channel = null; - private bool $isGeted = false; - public function __construct(Channel $channel) + public function __construct(private ?Channel $channel) { - $this->channel = $channel; } public function __destruct() diff --git a/src/Components/swoole/src/Context/CoroutineContextManager.php b/src/Components/swoole/src/Context/CoroutineContextManager.php index 33e21284d4..a0cda8ac1f 100644 --- a/src/Components/swoole/src/Context/CoroutineContextManager.php +++ b/src/Components/swoole/src/Context/CoroutineContextManager.php @@ -35,7 +35,7 @@ public function create(string $flag, array $data = []): \ArrayObject if (!($context['__bindDestroy'] ?? false)) { $context['__bindDestroy'] = true; - Coroutine::defer([$this, '__destroy']); + Coroutine::defer($this->__destroy(...)); } if ($data) { @@ -92,7 +92,7 @@ public function get(string $flag, bool $autoCreate = false): \ArrayObject if (!($context['__bindDestroy'] ?? false)) { $context['__bindDestroy'] = true; - Coroutine::defer([$this, '__destroy']); + Coroutine::defer($this->__destroy(...)); } return $context; diff --git a/src/Components/swoole/src/Cron/CronManager.php b/src/Components/swoole/src/Cron/CronManager.php index cb1b6cbeca..3da2b815be 100644 --- a/src/Components/swoole/src/Cron/CronManager.php +++ b/src/Components/swoole/src/Cron/CronManager.php @@ -206,14 +206,14 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp { case CronTaskType::ALL_WORKER: case CronTaskType::RANDOM_WORKER: - $task = static function (string $id, $data) use ($class) { + $task = static function (string $id, $data) use ($class): void { /** @var \Imi\Cron\Contract\ICronTask $handler */ $handler = App::getBean($class); $handler->run($id, $data); }; break; case CronTaskType::TASK: - $task = static function (string $id, $data) use ($class) { + $task = static function (string $id, $data) use ($class): void { TaskManager::nPost('imiCronTask', [ 'id' => $id, 'data' => $data, @@ -222,7 +222,7 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp }; break; case CronTaskType::PROCESS: - $task = function (string $id, $data) use ($class) { + $task = function (string $id, $data) use ($class): void { ProcessManager::run('CronWorkerProcess', [ 'id' => $id, 'data' => json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE), @@ -232,7 +232,7 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp }; break; case CronTaskType::CRON_PROCESS: - return static fn (string $id, $data) => goWait(static function () use ($class, $id, $data) { + return static fn (string $id, $data) => goWait(static function () use ($class, $id, $data): void { /** @var \Imi\Cron\Contract\ICronTask $handler */ $handler = App::getBean($class); $handler->run($id, $data); @@ -248,7 +248,7 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp { throw new \RuntimeException(sprintf('Cron %s, class %s must have a @Process Annotation', $cronId, $class)); } - $task = function (string $id, $data) use ($process) { + $task = function (string $id, $data) use ($process): void { ProcessManager::run($process->name, [ 'id' => $id, 'data' => json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE), @@ -265,7 +265,7 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp { throw new \RuntimeException(sprintf('Cron %s, class %s must have a @Task Annotation', $cronId, $class)); } - $task = static function (string $id, $data) use ($taskAnnotation) { + $task = static function (string $id, $data) use ($taskAnnotation): void { TaskManager::nPost($taskAnnotation->name, $data); }; } diff --git a/src/Components/swoole/src/Cron/Process/CronProcess.php b/src/Components/swoole/src/Cron/Process/CronProcess.php index 9bcde30ec0..59aa065b05 100644 --- a/src/Components/swoole/src/Cron/Process/CronProcess.php +++ b/src/Components/swoole/src/Cron/Process/CronProcess.php @@ -47,10 +47,10 @@ class CronProcess extends BaseProcess public function run(\Swoole\Process $process): void { - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function () { + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function (): void { $this->stop(); }, \Imi\Util\ImiPriority::IMI_MIN); - Event::on('IMI.PROCESS.PIPE_MESSAGE', function (PipeMessageEventParam $e) { + Event::on('IMI.PROCESS.PIPE_MESSAGE', function (PipeMessageEventParam $e): void { $data = $e->data; if ($data instanceof Result) { diff --git a/src/Components/swoole/src/Cron/Process/CronWorkerProcess.php b/src/Components/swoole/src/Cron/Process/CronWorkerProcess.php index 43880489b4..4dc4cce03d 100644 --- a/src/Components/swoole/src/Cron/Process/CronWorkerProcess.php +++ b/src/Components/swoole/src/Cron/Process/CronWorkerProcess.php @@ -26,7 +26,7 @@ public function run(\Swoole\Process $process): void try { $exitCode = 0; - $data = json_decode($input->getParameterOption('--data'), true); + $data = json_decode((string) $input->getParameterOption('--data'), true); $class = $input->getParameterOption('--class'); /** @var \Imi\Cron\Contract\ICronTask $handler */ $handler = App::getBean($class); diff --git a/src/Components/swoole/src/Cron/Scheduler.php b/src/Components/swoole/src/Cron/Scheduler.php index c1a45df9ed..7b3f856df7 100644 --- a/src/Components/swoole/src/Cron/Scheduler.php +++ b/src/Components/swoole/src/Cron/Scheduler.php @@ -35,7 +35,7 @@ class Scheduler extends \Imi\Cron\Scheduler /** * 协程工作池. */ - private CoPool $coPool; + private readonly CoPool $coPool; public function __construct() { @@ -47,7 +47,7 @@ public function __construct() /** * {@inheritDoc} */ - public function run(ITaskParam $param) + public function run(ITaskParam $param): void { /** @var \Imi\Cron\CronTask $task */ $task = $param->getData(); diff --git a/src/Components/swoole/src/Cron/Task/CronTask.php b/src/Components/swoole/src/Cron/Task/CronTask.php index 5fb639b362..eb1034f4bc 100644 --- a/src/Components/swoole/src/Cron/Task/CronTask.php +++ b/src/Components/swoole/src/Cron/Task/CronTask.php @@ -18,7 +18,7 @@ class CronTask implements ITaskHandler /** * {@inheritDoc} */ - public function handle(TaskParam $param, \Swoole\Server $server, int $taskId, int $workerId) + public function handle(TaskParam $param, \Swoole\Server $server, int $taskId, int $workerId): void { $success = false; $message = ''; diff --git a/src/Components/swoole/src/Db/Driver/Swoole/Statement.php b/src/Components/swoole/src/Db/Driver/Swoole/Statement.php index 4396f99840..6be42bca42 100644 --- a/src/Components/swoole/src/Db/Driver/Swoole/Statement.php +++ b/src/Components/swoole/src/Db/Driver/Swoole/Statement.php @@ -14,23 +14,11 @@ */ class Statement extends MysqlBaseStatement implements IMysqlStatement { - /** - * Statement. - * - * @var \Swoole\Coroutine\MySQL\Statement|array - */ - protected $statement; - /** * 数据. */ protected array $data = []; - /** - * 数据库操作对象 - */ - protected ?IMysqlDb $db = null; - /** * 绑定数据. */ @@ -41,29 +29,31 @@ class Statement extends MysqlBaseStatement implements IMysqlStatement */ protected array $result = []; - /** - * 最后执行过的SQL语句. - */ - protected string $lastSql = ''; - - /** - * SQL 参数映射. - */ - protected ?array $sqlParamsMap = null; - /** * @param \Swoole\Coroutine\MySQL\Statement|array $statement */ - public function __construct(IMysqlDb $db, $statement, string $originSql, ?array $sqlParamsMap = null) + public function __construct( + /** + * 数据库操作对象 + */ + protected ?IMysqlDb $db, + /** + * Statement. + */ + protected $statement, + /** + * 最后执行过的SQL语句. + */ + protected string $lastSql, + /** + * SQL 参数映射. + */ + protected ?array $sqlParamsMap = null) { - $this->db = $db; - $this->statement = $statement; if (\is_array($statement)) { $this->result = $statement; } - $this->lastSql = $originSql; - $this->sqlParamsMap = $sqlParamsMap; } /** diff --git a/src/Components/swoole/src/HotUpdate/HotUpdateProcess.php b/src/Components/swoole/src/HotUpdate/HotUpdateProcess.php index c06be6518a..63e798b76a 100644 --- a/src/Components/swoole/src/HotUpdate/HotUpdateProcess.php +++ b/src/Components/swoole/src/HotUpdate/HotUpdateProcess.php @@ -126,7 +126,7 @@ public function run(\Swoole\Process $process): void $time = 0; $this->initBuildRuntime(); $this->startBuildRuntimeTimer(); - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function () { + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function (): void { $this->running = false; }, \Imi\Util\ImiPriority::IMI_MIN); /** @phpstan-ignore-next-line */ @@ -176,7 +176,7 @@ public function run(\Swoole\Process $process): void */ private function startBuildRuntimeTimer(): void { - $this->buildRuntimeTimerId = Timer::tick(1000, [$this, 'buildRuntimeTimer']); + $this->buildRuntimeTimerId = Timer::tick(1000, $this->buildRuntimeTimer(...)); } /** @@ -303,7 +303,7 @@ private function beginBuildRuntime(array $changedFiles): void */ private function closeBuildRuntime(): void { - $closePipes = static function (?array $buildRuntimePipes) { + $closePipes = static function (?array $buildRuntimePipes): void { if (null !== $buildRuntimePipes) { foreach ($buildRuntimePipes as $pipe) diff --git a/src/Components/swoole/src/Http/Message/SwooleEmitHandler.php b/src/Components/swoole/src/Http/Message/SwooleEmitHandler.php index 815f7b201f..d567196037 100644 --- a/src/Components/swoole/src/Http/Message/SwooleEmitHandler.php +++ b/src/Components/swoole/src/Http/Message/SwooleEmitHandler.php @@ -9,11 +9,8 @@ class SwooleEmitHandler implements IEmitHandler { - private Response $response; - - public function __construct(Response $response) + public function __construct(private readonly Response $response) { - $this->response = $response; } public function send(string $data): bool diff --git a/src/Components/swoole/src/Http/Message/SwooleRequest.php b/src/Components/swoole/src/Http/Message/SwooleRequest.php index f25d76d818..82dff59b4b 100644 --- a/src/Components/swoole/src/Http/Message/SwooleRequest.php +++ b/src/Components/swoole/src/Http/Message/SwooleRequest.php @@ -14,24 +14,18 @@ class SwooleRequest extends Request { /** - * swoole的http请求对象 + * @param \Imi\Swoole\Server\Http\Server|\Imi\Swoole\Server\WebSocket\Server $serverInstance */ - protected ?\Swoole\Http\Request $swooleRequest = null; - - /** - * 对应的服务器. - * - * @var \Imi\Swoole\Server\Http\Server|\Imi\Swoole\Server\WebSocket\Server - */ - protected ?ISwooleServer $serverInstance = null; - - /** - * @param \Imi\Swoole\Server\Http\Server|\Imi\Swoole\Server\WebSocket\Server $server - */ - public function __construct(ISwooleServer $server, \Swoole\Http\Request $request) - { - $this->swooleRequest = $request; - $this->serverInstance = $server; + public function __construct( + /** + * 对应的服务器. + */ + protected ?ISwooleServer $serverInstance, + /** + * swoole的http请求对象 + */ + protected ?\Swoole\Http\Request $swooleRequest + ) { } /** @@ -39,7 +33,7 @@ public function __construct(ISwooleServer $server, \Swoole\Http\Request $request */ protected function initProtocolVersion(): void { - [, $this->protocolVersion] = explode('/', $this->swooleRequest->server['server_protocol'], 2); + [, $this->protocolVersion] = explode('/', (string) $this->swooleRequest->server['server_protocol'], 2); } /** diff --git a/src/Components/swoole/src/Http/Message/SwooleResponse.php b/src/Components/swoole/src/Http/Message/SwooleResponse.php index 49a08e6d69..2337a594ca 100644 --- a/src/Components/swoole/src/Http/Message/SwooleResponse.php +++ b/src/Components/swoole/src/Http/Message/SwooleResponse.php @@ -11,22 +11,18 @@ class SwooleResponse extends Response { - /** - * swoole响应对象 - */ - protected ?\Swoole\Http\Response $swooleResponse = null; - - /** - * 对应的服务器. - */ - protected ?ISwooleServer $serverInstance = null; - protected bool $emitterWritting = false; - public function __construct(ISwooleServer $server, \Swoole\Http\Response $response) + public function __construct( + /** + * 对应的服务器. + */ + protected ?ISwooleServer $serverInstance, + /** + * swoole响应对象 + */ + protected ?\Swoole\Http\Response $swooleResponse) { - $this->swooleResponse = $response; - $this->serverInstance = $server; parent::__construct(); } diff --git a/src/Components/swoole/src/Lock/Handler/Atomic.php b/src/Components/swoole/src/Lock/Handler/Atomic.php index 311fae0f92..68a7420f22 100644 --- a/src/Components/swoole/src/Lock/Handler/Atomic.php +++ b/src/Components/swoole/src/Lock/Handler/Atomic.php @@ -79,7 +79,7 @@ private function startTimeoutTimer(): void { $this->stopTimeoutTimer(); } - $this->timeoutTimerId = Timer::after($this->lockExpire, function () { + $this->timeoutTimerId = Timer::after($this->lockExpire, function (): void { $this->unlock(); }); } diff --git a/src/Components/swoole/src/Log/SwooleLogger.php b/src/Components/swoole/src/Log/SwooleLogger.php index c7307be7f3..fdb950e7d1 100644 --- a/src/Components/swoole/src/Log/SwooleLogger.php +++ b/src/Components/swoole/src/Log/SwooleLogger.php @@ -43,10 +43,10 @@ public function __construct(...$args) return $record; }); $this->logChannel = new Channel(Config::get('@app.logger.asyncQueueLength', 1024)); - Coroutine::create(function () { + Coroutine::create(function (): void { $this->__logProcessor(); }); - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END', 'IMI.SWOOLE.MAIN_COROUTINE.END', 'IMI.QUICK_START_AFTER'], function () { + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END', 'IMI.SWOOLE.MAIN_COROUTINE.END', 'IMI.QUICK_START_AFTER'], function (): void { $this->asyncLogging = false; $this->logChannel->close(); }, \Imi\Util\ImiPriority::IMI_MIN + 1); diff --git a/src/Components/swoole/src/Pool/BaseAsyncPool.php b/src/Components/swoole/src/Pool/BaseAsyncPool.php index 919de6739f..a40d964fa1 100644 --- a/src/Components/swoole/src/Pool/BaseAsyncPool.php +++ b/src/Components/swoole/src/Pool/BaseAsyncPool.php @@ -230,7 +230,7 @@ protected function push(IPoolResource $resource): void } else { - \Swoole\Coroutine\run(function () use ($poolItem) { + \Swoole\Coroutine\run(function () use ($poolItem): void { $this->queue->push($poolItem); }); } @@ -255,8 +255,8 @@ public function startAutoGC(): void $gcInterval = $this->config->getGCInterval(); if ($gcInterval > 0) { - $this->gcTimerId = Timer::tick($gcInterval * 1000, [$this, 'gc']); - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function () { + $this->gcTimerId = Timer::tick($gcInterval * 1000, $this->gc(...)); + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function (): void { $this->stopAutoGC(); }, \Imi\Util\ImiPriority::IMI_MIN + 1); } @@ -340,8 +340,8 @@ public function startHeartbeat(): void { if ((null !== Worker::getWorkerId() || Coroutine::stats()['coroutine_num'] > 0) && null !== ($heartbeatInterval = $this->config->getHeartbeatInterval())) { - $this->heartbeatTimerId = Timer::tick((int) ($heartbeatInterval * 1000), [$this, 'heartbeat']); - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function () { + $this->heartbeatTimerId = Timer::tick((int) ($heartbeatInterval * 1000), $this->heartbeat(...)); + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function (): void { $this->stopHeartbeat(); }, \Imi\Util\ImiPriority::IMI_MIN + 1); } diff --git a/src/Components/swoole/src/Process/BasePoolProcess.php b/src/Components/swoole/src/Process/BasePoolProcess.php index 41cc521b6b..1ec3bbca36 100644 --- a/src/Components/swoole/src/Process/BasePoolProcess.php +++ b/src/Components/swoole/src/Process/BasePoolProcess.php @@ -8,14 +8,12 @@ abstract class BasePoolProcess implements IPoolProcess { - /** - * 数据. - */ - protected array $data = []; - - public function __construct(array $data = []) + public function __construct( + /** + * 数据. + */ + protected array $data = []) { - $this->data = $data; if ($data) { foreach ($data as $k => $v) diff --git a/src/Components/swoole/src/Process/BaseProcess.php b/src/Components/swoole/src/Process/BaseProcess.php index a740896c0c..3ad6e3e397 100644 --- a/src/Components/swoole/src/Process/BaseProcess.php +++ b/src/Components/swoole/src/Process/BaseProcess.php @@ -8,14 +8,12 @@ abstract class BaseProcess implements IProcess { - /** - * 数据. - */ - protected array $data = []; - - public function __construct(array $data = []) + public function __construct( + /** + * 数据. + */ + protected array $data = []) { - $this->data = $data; if ($data) { foreach ($data as $k => $v) diff --git a/src/Components/swoole/src/Process/Cli/Process.php b/src/Components/swoole/src/Process/Cli/Process.php index 82d2f5fd02..e05411a435 100644 --- a/src/Components/swoole/src/Process/Cli/Process.php +++ b/src/Components/swoole/src/Process/Cli/Process.php @@ -31,7 +31,7 @@ class Process extends BaseCommand */ public function start(string $name, ?bool $redirectStdinStdout, ?int $pipeType): void { - Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', function () use ($name, $redirectStdinStdout, $pipeType) { + Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', function () use ($name, $redirectStdinStdout, $pipeType): never { $process = ProcessManager::create($name, $_SERVER['argv'], $redirectStdinStdout, $pipeType); $process->start(); $result = \Swoole\Process::wait(true); @@ -53,7 +53,7 @@ public function start(string $name, ?bool $redirectStdinStdout, ?int $pipeType): */ public function pool(string $name, ?int $worker, ?int $ipcType, ?string $msgQueueKey): void { - Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', static function () use ($name, $worker, $ipcType, $msgQueueKey) { + Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', static function () use ($name, $worker, $ipcType, $msgQueueKey): void { $processPool = ProcessPoolManager::create($name, $worker, $_SERVER['argv'], $ipcType, $msgQueueKey); $processPool->start(); }); @@ -68,14 +68,14 @@ public function pool(string $name, ?int $worker, ?int $ipcType, ?string $msgQueu */ public function run(string $name): void { - Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', static function () use ($name) { + Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', static function () use ($name): void { $processOption = ProcessManager::get($name); if (null === $processOption) { throw new \RuntimeException(sprintf('Not found process %s', $name)); } $callable = ProcessManager::getProcessCallable($_SERVER['argv'], $name, $processOption); - $callable(new \Imi\Swoole\Process\Process(static function () { + $callable(new \Imi\Swoole\Process\Process(static function (): void { })); }); } diff --git a/src/Components/swoole/src/Process/Pool.php b/src/Components/swoole/src/Process/Pool.php index 7c9042eef0..b15f7da5fe 100644 --- a/src/Components/swoole/src/Process/Pool.php +++ b/src/Components/swoole/src/Process/Pool.php @@ -17,11 +17,6 @@ class Pool { use TEvent; - /** - * 工作进程数量. - */ - private int $workerNum = 0; - /** * 工作进程列表 * 以 WorkerId 作为 Key. @@ -47,17 +42,13 @@ class Pool */ private int $masterPID = 0; - /** - * @param int $workerNum - */ - public function __construct($workerNum) + public function __construct(private readonly int $workerNum) { - $this->workerNum = $workerNum; } protected function listenSigChild(): void { - Signal::waitCallback(\SIGCHLD, function () { + Signal::waitCallback(\SIGCHLD, function (): void { if ($this->workers) { while ($result = Process::wait(false)) @@ -81,10 +72,8 @@ protected function listenSigChild(): void /** * 启动进程池. - * - * @return void */ - public function start() + public function start(): void { $this->masterPID = getmypid(); $this->working = true; @@ -95,7 +84,7 @@ public function start() $this->listenSigChild(); - imigo(function () { + imigo(function (): void { if (Signal::wait(\SIGTERM)) { if ($this->workers) @@ -206,20 +195,16 @@ public function wait(bool $blocking = true): bool /** * 停止工作池. - * - * @return void */ - public function shutdown() + public function shutdown(): void { Process::kill($this->masterPID, \SIGTERM); } /** * 重启所有工作进程. - * - * @return void */ - public function restartAllWorker() + public function restartAllWorker(): void { foreach ($this->workers as $worker) { @@ -238,10 +223,8 @@ public function restartAllWorker() * 重启指定工作进程. * * @param int ...$workerIds - * - * @return void */ - public function restartWorker(...$workerIds) + public function restartWorker(...$workerIds): void { $workers = &$this->workers; foreach ($workerIds as $workerId) @@ -269,10 +252,8 @@ public function restartWorker(...$workerIds) * 启动工作进程. * * @param int $workerId - * - * @return void */ - private function startWorker($workerId) + private function startWorker($workerId): void { $workers = &$this->workers; if (isset($workers[$workerId])) @@ -283,8 +264,8 @@ private function startWorker($workerId) Coroutine::set([ 'enable_deadlock_check' => false, ]); - $worker = new Process(function (Process $worker) use ($workerId) { - Process::signal(\SIGTERM, function () use ($worker, $workerId) { + $worker = new Process(function (Process $worker) use ($workerId): void { + Process::signal(\SIGTERM, function () use ($worker, $workerId): void { $this->trigger('WorkerExit', [ 'pool' => $this, 'worker' => $worker, @@ -292,7 +273,7 @@ private function startWorker($workerId) ], $this, WorkerEventParam::class); Event::exit(); }); - register_shutdown_function(function () use ($worker, $workerId) { + register_shutdown_function(function () use ($worker, $workerId): void { $this->trigger('WorkerStop', [ 'pool' => $this, 'worker' => $worker, @@ -319,7 +300,7 @@ private function startWorker($workerId) $workers[$workerId] = $worker; $this->workerIdMap[$pid] = $workerId; - Event::add($worker->pipe, function ($pipe) use ($worker, $workerId) { + Event::add($worker->pipe, function ($pipe) use ($worker, $workerId): void { $content = $worker->read(); if (false === $content || '' === $content) { diff --git a/src/Components/swoole/src/Process/Process.php b/src/Components/swoole/src/Process/Process.php index 80182314dc..5534480f60 100644 --- a/src/Components/swoole/src/Process/Process.php +++ b/src/Components/swoole/src/Process/Process.php @@ -51,7 +51,7 @@ public function exit($exitCode = 0): void public function getUnixSocketFile(): string { - return '/tmp/imi.process.' . md5(App::get(AppContexts::APP_PATH)) . '.' . spl_object_id($this) . '.sock'; + return '/tmp/imi.process.' . md5((string) App::get(AppContexts::APP_PATH)) . '.' . spl_object_id($this) . '.sock'; } public function createUnixSocketClient(): Client @@ -80,10 +80,10 @@ public function getUnixSocketClient(): Client else { $this->unixSocketClient = $client = $this->createUnixSocketClient(); - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], static function () use ($client) { + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], static function () use ($client): void { $client->close(); }, \Imi\Util\ImiPriority::IMI_MIN + 1); - Coroutine::create(function () use ($client) { + Coroutine::create(function () use ($client): void { while ($client->isConnected()) { $data = $client->recv(1); @@ -152,10 +152,10 @@ public function startUnixSocketServer(): void return; } $this->unixSocketRunning = true; - Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function () { + Event::on(['IMI.MAIN_SERVER.WORKER.EXIT', 'IMI.PROCESS.END'], function (): void { $this->stopUnixSocketServer(); }, \Imi\Util\ImiPriority::IMI_MIN + 1); - Coroutine::create(function () { + Coroutine::create(function (): void { $socketFile = $this->getUnixSocketFile(); if (file_exists($socketFile)) { @@ -169,7 +169,7 @@ public function startUnixSocketServer(): void 'package_body_offset' => 4, ]); // 接收到新的连接请求 并自动创建一个协程 - $server->handle(function (Connection $conn) { + $server->handle(function (Connection $conn): void { while ($this->unixSocketRunning) { // 接收数据 diff --git a/src/Components/swoole/src/Process/ProcessManager.php b/src/Components/swoole/src/Process/ProcessManager.php index 37aa74aded..0d0918a190 100644 --- a/src/Components/swoole/src/Process/ProcessManager.php +++ b/src/Components/swoole/src/Process/ProcessManager.php @@ -117,7 +117,7 @@ public static function create(string $name, array $args = [], ?bool $redirectStd */ public static function getProcessCallable(array $args, string $name, array $processOption, ?string $alias = null, bool $runWithManager = false): callable { - return static function (Process $swooleProcess) use ($args, $name, $processOption, $alias, $runWithManager) { + return static function (Process $swooleProcess) use ($args, $name, $processOption, $alias, $runWithManager): void { App::set(ProcessAppContexts::PROCESS_TYPE, ProcessType::PROCESS, true); App::set(ProcessAppContexts::PROCESS_NAME, $name, true); // 设置进程名称 @@ -133,7 +133,7 @@ public static function getProcessCallable(array $args, string $name, array $proc mt_srand(); Imi::loadRuntimeInfo(Imi::getCurrentModeRuntimePath('runtime')); $exitCode = 0; - $callable = static function () use ($swooleProcess, $args, $name, $alias, $processOption, &$exitCode, $runWithManager) { + $callable = static function () use ($swooleProcess, $args, $name, $alias, $processOption, &$exitCode, $runWithManager): void { if ($runWithManager) { Log::info('Process start [' . $name . ']. pid: ' . getmypid() . ', UnixSocket: ' . $swooleProcess->getUnixSocketFile()); @@ -143,7 +143,7 @@ public static function getProcessCallable(array $args, string $name, array $proc // 正常退出 Event::on('IMI.PROCESS.END', static fn () => Signal::clear(), ImiPriority::IMI_MIN); $processEnded = false; - imigo(static function () use ($name, $swooleProcess, &$processEnded) { + imigo(static function () use ($name, $swooleProcess, &$processEnded): void { if (Signal::wait(\SIGTERM)) { if ($processEnded) @@ -160,7 +160,7 @@ public static function getProcessCallable(array $args, string $name, array $proc }); if ($inCoroutine = Coroutine::isIn()) { - Coroutine::defer(static function () use ($name, $swooleProcess, &$processEnded) { + Coroutine::defer(static function () use ($name, $swooleProcess, &$processEnded): void { if ($processEnded) { return; @@ -330,7 +330,7 @@ public static function run(string $name, array $args = [], ?bool $redirectStdinS */ public static function coRun(string $name, array $args = [], ?bool $redirectStdinStdout = null, ?int $pipeType = null): void { - Coroutine::create(static function () use ($name, $args, $redirectStdinStdout, $pipeType) { + Coroutine::create(static function () use ($name, $args, $redirectStdinStdout, $pipeType): void { static::run($name, $args, $redirectStdinStdout, $pipeType); }); } diff --git a/src/Components/swoole/src/Process/ProcessPoolManager.php b/src/Components/swoole/src/Process/ProcessPoolManager.php index 910a506811..37c799e676 100644 --- a/src/Components/swoole/src/Process/ProcessPoolManager.php +++ b/src/Components/swoole/src/Process/ProcessPoolManager.php @@ -76,14 +76,14 @@ public static function create(string $name, ?int $workerNum = null, array $args $pool = new \Swoole\Process\Pool($workerNum, $ipcType, $msgQueueKey); - $pool->on('WorkerStart', static function (\Swoole\Process\Pool $pool, int $workerId) use ($name, $workerNum, $args, $ipcType, $msgQueueKey, $processPoolOption) { + $pool->on('WorkerStart', static function (\Swoole\Process\Pool $pool, int $workerId) use ($name, $workerNum, $args, $ipcType, $msgQueueKey, $processPoolOption): void { Imi::setProcessName('processPool', [ 'processPoolName' => $name, 'workerId' => $workerId, ]); // 随机数播种 mt_srand(); - \Swoole\Coroutine\run(static function () use ($pool, $workerId, $name, $workerNum, $args, $ipcType, $msgQueueKey, $processPoolOption) { + \Swoole\Coroutine\run(static function () use ($pool, $workerId, $name, $workerNum, $args, $ipcType, $msgQueueKey, $processPoolOption): void { $processInstance = App::newInstance($processPoolOption['className'], $args); // 进程开始事件 Event::trigger('IMI.PROCESS_POOL.PROCESS.BEGIN', [ @@ -100,7 +100,7 @@ public static function create(string $name, ?int $workerNum = null, array $args }); }); - $pool->on('WorkerStop', imiCallable(static function (\Swoole\Process\Pool $pool, int $workerId) use ($name, $workerNum, $args, $ipcType, $msgQueueKey) { + $pool->on('WorkerStop', imiCallable(static function (\Swoole\Process\Pool $pool, int $workerId) use ($name, $workerNum, $args, $ipcType, $msgQueueKey): void { // 进程结束事件 Event::trigger('IMI.PROCESS_POOL.PROCESS.END', [ 'name' => $name, diff --git a/src/Components/swoole/src/Process/Signal.php b/src/Components/swoole/src/Process/Signal.php index a79cdc86fa..7cb43d2b42 100644 --- a/src/Components/swoole/src/Process/Signal.php +++ b/src/Components/swoole/src/Process/Signal.php @@ -34,7 +34,7 @@ public static function wait(int $signo, float $timeout = -1): bool self::$waitingSignals[$signo][$coid] = $channel; if ($needCreateCoroutineWait) { - self::$cids[$signo] = Coroutine::create(static function () use ($signo) { + self::$cids[$signo] = Coroutine::create(static function () use ($signo): void { $waitResult = System::waitSignal($signo); if (!isset(self::$waitingSignals[$signo])) { @@ -59,7 +59,7 @@ public static function waitCallback(int $signo, callable $callback): void if (!isset(self::$waitingProcessSignals[$signo])) { self::$waitingProcessSignals[$signo] = true; - Process::signal($signo, static function ($signo) { + Process::signal($signo, static function ($signo): void { if (!isset(self::$waitCallbacks[$signo])) { return; diff --git a/src/Components/swoole/src/Server/Base.php b/src/Components/swoole/src/Server/Base.php index d80fb74ffc..bc4804cc5c 100644 --- a/src/Components/swoole/src/Server/Base.php +++ b/src/Components/swoole/src/Server/Base.php @@ -55,18 +55,16 @@ abstract class Base extends BaseServer implements ISwooleServer */ protected \Swoole\Server\Port $swoolePort; - /** - * 是否为子服务器. - */ - protected bool $isSubServer = false; - /** * {@inheritDoc} */ - public function __construct(string $name, array $config, bool $isSubServer = false) + public function __construct(string $name, array $config, + /** + * 是否为子服务器. + */ + protected bool $isSubServer = false) { parent::__construct($name, $config); - $this->isSubServer = $isSubServer; if ($isSubServer) { $this->createSubServer(); @@ -166,7 +164,7 @@ public function callServerMethod(string $methodName, ...$args) $server = $this->swooleServer; if (!method_exists($server, $methodName)) { - throw new MethodNotFoundException(sprintf('%s->%s() method is not exists', \get_class($server), $methodName)); + throw new MethodNotFoundException(sprintf('%s->%s() method is not exists', $server::class, $methodName)); } /** @var \Swoole\WebSocket\Server $server */ @@ -187,7 +185,7 @@ protected function bindEvents(): void { if (\SWOOLE_BASE !== $this->swooleServer->mode) { - $this->swooleServer->on('start', function (Server $server) { + $this->swooleServer->on('start', function (Server $server): void { try { \Imi\Swoole\Util\Imi::setProcessName('master'); @@ -207,7 +205,7 @@ protected function bindEvents(): void }); } - $this->swooleServer->on('shutdown', function (Server $server) { + $this->swooleServer->on('shutdown', function (Server $server): void { try { Event::trigger('IMI.MAIN_SERVER.SHUTDOWN', [ @@ -224,7 +222,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('WorkerStart', function (Server $server, int $workerId) { + $this->swooleServer->on('WorkerStart', function (Server $server, int $workerId): void { try { Event::trigger('IMI.MAIN_SERVER.WORKER.START', [ @@ -249,7 +247,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('WorkerStop', function (Server $server, int $workerId) { + $this->swooleServer->on('WorkerStop', function (Server $server, int $workerId): void { try { Event::trigger('IMI.MAIN_SERVER.WORKER.STOP', [ @@ -271,7 +269,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('WorkerExit', function (Server $server, int $workerId) { + $this->swooleServer->on('WorkerExit', function (Server $server, int $workerId): void { try { Event::trigger('IMI.MAIN_SERVER.WORKER.EXIT', [ @@ -285,7 +283,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('ManagerStart', function (Server $server) { + $this->swooleServer->on('ManagerStart', function (Server $server): void { try { Event::trigger('IMI.MAIN_SERVER.MANAGER.START', [ @@ -303,7 +301,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('ManagerStop', function (Server $server) { + $this->swooleServer->on('ManagerStop', function (Server $server): void { try { Event::trigger('IMI.MAIN_SERVER.MANAGER.STOP', [ @@ -323,7 +321,7 @@ protected function bindEvents(): void $configs = $this->config['configs'] ?? null; if (0 !== ($configs['task_worker_num'] ?? -1)) { - $this->swooleServer->on('task', function (Server $server, Server\Task $task) { + $this->swooleServer->on('task', function (Server $server, Server\Task $task): void { try { Event::trigger('IMI.MAIN_SERVER.TASK', [ @@ -342,7 +340,7 @@ protected function bindEvents(): void }); } - $this->swooleServer->on('finish', function (Server $server, int $taskId, $data) { + $this->swooleServer->on('finish', function (Server $server, int $taskId, $data): void { try { Event::trigger('IMI.MAIN_SERVER.FINISH', [ @@ -357,7 +355,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('PipeMessage', function (Server $server, int $workerId, string $message) { + $this->swooleServer->on('PipeMessage', function (Server $server, int $workerId, string $message): void { try { Event::trigger('IMI.MAIN_SERVER.PIPE_MESSAGE', [ @@ -372,7 +370,7 @@ protected function bindEvents(): void } }); - $this->swooleServer->on('WorkerError', function (Server $server, int $workerId, int $workerPid, int $exitCode, int $signal) { + $this->swooleServer->on('WorkerError', function (Server $server, int $workerId, int $workerPid, int $exitCode, int $signal): void { try { Event::trigger('IMI.MAIN_SERVER.WORKER_ERROR', [ diff --git a/src/Components/swoole/src/Server/Cli/Server.php b/src/Components/swoole/src/Server/Cli/Server.php index ca2cbf2e33..4d7fadf626 100644 --- a/src/Components/swoole/src/Server/Cli/Server.php +++ b/src/Components/swoole/src/Server/Cli/Server.php @@ -38,13 +38,13 @@ class Server extends BaseCommand */ public function start(?int $workerNum, $d): void { - Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', function () use ($workerNum, $d) { + Event::one('IMI.SWOOLE.MAIN_COROUTINE.AFTER', function () use ($workerNum, $d): void { $server = (function () use ($workerNum, $d) { $this->outStartupInfo(); if (Config::get('@app.server.checkPoolResource', false)) { $exit = false; - run(static function () use (&$exit) { + run(static function () use (&$exit): void { if (!PoolManager::checkPoolResource()) { $exit = true; diff --git a/src/Components/swoole/src/Server/ConnectionContext/StoreHandler/MemoryTable.php b/src/Components/swoole/src/Server/ConnectionContext/StoreHandler/MemoryTable.php index 75e69764f8..62b07bc7a6 100644 --- a/src/Components/swoole/src/Server/ConnectionContext/StoreHandler/MemoryTable.php +++ b/src/Components/swoole/src/Server/ConnectionContext/StoreHandler/MemoryTable.php @@ -63,7 +63,7 @@ public function __init(): void { if (0 === Worker::getWorkerId()) { - $this->useRedis(function (RedisHandler $redis) { + $this->useRedis(function (RedisHandler $redis): void { $key = $this->key; $keys = (array) $key; $count = 0; @@ -133,7 +133,7 @@ public function destroy(string $key): void */ public function delayDestroy(string $key, int $ttl): void { - Timer::after($ttl * 1000, function () use ($key) { + Timer::after($ttl * 1000, function () use ($key): void { $this->destroy($key); }); } @@ -181,12 +181,12 @@ public function unlock(): bool */ public function bind(string $flag, $clientId): void { - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); }); - $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId) { + $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId): void { $redis->hSet($this->key . ':binder', $flag, $clientId); }); } @@ -199,7 +199,7 @@ public function bindNx(string $flag, $clientId): bool $result = $this->useRedis(fn (RedisHandler $redis) => $redis->hSetNx($this->key . ':binder', $flag, $clientId)); if ($result) { - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); @@ -214,9 +214,9 @@ public function bindNx(string $flag, $clientId): bool */ public function unbind(string $flag, $clientId, ?int $keepTime = null): void { - $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId, $keepTime) { + $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId, $keepTime): void { $key = $this->key . ':binder'; - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); diff --git a/src/Components/swoole/src/Server/Http/Listener/BeforeRequest.php b/src/Components/swoole/src/Server/Http/Listener/BeforeRequest.php index ed24b399c8..a6beaf65bd 100644 --- a/src/Components/swoole/src/Server/Http/Listener/BeforeRequest.php +++ b/src/Components/swoole/src/Server/Http/Listener/BeforeRequest.php @@ -18,17 +18,11 @@ class BeforeRequest implements IRequestEventListener { protected Dispatcher $dispatcher; - /** - * @var \Imi\Swoole\Server\Http\Server|\Imi\Swoole\Server\WebSocket\Server - */ - protected ISwooleServer $server; - /** * @param \Imi\Swoole\Server\Http\Server|\Imi\Swoole\Server\WebSocket\Server $server */ - public function __construct(ISwooleServer $server) + public function __construct(protected ISwooleServer $server) { - $this->server = $server; } /** diff --git a/src/Components/swoole/src/Server/Http/Middleware/ExecuteTimeoutMiddleware.php b/src/Components/swoole/src/Server/Http/Middleware/ExecuteTimeoutMiddleware.php index fe081e3313..15ea15b6a4 100644 --- a/src/Components/swoole/src/Server/Http/Middleware/ExecuteTimeoutMiddleware.php +++ b/src/Components/swoole/src/Server/Http/Middleware/ExecuteTimeoutMiddleware.php @@ -40,14 +40,14 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $context = RequestContext::getContext(); $response = $context['response']; $server = $context['server']; - $timerId = Timer::after($this->maxExecuteTime, function () use ($request, $response, $server, $context) { + $timerId = Timer::after($this->maxExecuteTime, function () use ($request, $response, $server, $context): void { RequestContext::muiltiSet((array) $context); /** @var \Imi\Server\Http\Error\IExecuteTimeoutHandler $handler */ $handler = $server->getBean($this->handler); // @phpstan-ignore-next-line $handler->handle($request, $response); }); - Coroutine::defer(static function () use ($timerId) { + Coroutine::defer(static function () use ($timerId): void { Timer::del($timerId); }); diff --git a/src/Components/swoole/src/Server/Http/Server.php b/src/Components/swoole/src/Server/Http/Server.php index 76abdd02bd..e9b3b014e2 100644 --- a/src/Components/swoole/src/Server/Http/Server.php +++ b/src/Components/swoole/src/Server/Http/Server.php @@ -91,7 +91,7 @@ protected function getServerInitConfig(): array */ protected function __bindEvents(): void { - Event::one('IMI.MAIN_SERVER.WORKER.START.APP', function (WorkerStartEventParam $e) { + Event::one('IMI.MAIN_SERVER.WORKER.START.APP', function (WorkerStartEventParam $e): void { // 内置事件监听 $this->on('request', [new BeforeRequest($this), 'handle'], ImiPriority::IMI_MAX); if ($this->http2) @@ -106,7 +106,7 @@ protected function __bindEvents(): void $events = $this->config['events'] ?? null; if ($event = ($events['request'] ?? true)) { - $this->swoolePort->on('request', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse) { + $this->swoolePort->on('request', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse): void { try { if (!Worker::isInited()) @@ -139,14 +139,14 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('request', static function () { + $this->swoolePort->on('request', static function (): void { }); } if ($event = ($events['close'] ?? false) || $this->http2) { // @phpstan-ignore-next-line - $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) { + $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId): void { try { $this->trigger('close', [ @@ -163,7 +163,7 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('close', static function () { + $this->swoolePort->on('close', static function (): void { }); } } diff --git a/src/Components/swoole/src/Server/Listener/OnPipeMessage.php b/src/Components/swoole/src/Server/Listener/OnPipeMessage.php index f5f90f0ea1..3512692348 100644 --- a/src/Components/swoole/src/Server/Listener/OnPipeMessage.php +++ b/src/Components/swoole/src/Server/Listener/OnPipeMessage.php @@ -19,7 +19,7 @@ class OnPipeMessage implements IPipeMessageEventListener */ public function handle(PipeMessageEventParam $e): void { - $data = json_decode($e->message, true); + $data = json_decode((string) $e->message, true); $action = $data['action'] ?? null; if (!$action) { diff --git a/src/Components/swoole/src/Server/TcpServer/Message/ReceiveData.php b/src/Components/swoole/src/Server/TcpServer/Message/ReceiveData.php index 0490750913..66c7146aa9 100644 --- a/src/Components/swoole/src/Server/TcpServer/Message/ReceiveData.php +++ b/src/Components/swoole/src/Server/TcpServer/Message/ReceiveData.php @@ -6,18 +6,16 @@ class ReceiveData extends \Imi\Server\TcpServer\Message\ReceiveData { - /** - * Reactor线程ID. - */ - protected int $reactorId = 0; - /** * @param int|string $clientId */ - public function __construct($clientId, int $reactorId, string $data) + public function __construct($clientId, + /** + * Reactor线程ID. + */ + protected int $reactorId, string $data) { parent::__construct($clientId, $data); - $this->reactorId = $reactorId; } /** diff --git a/src/Components/swoole/src/Server/TcpServer/Server.php b/src/Components/swoole/src/Server/TcpServer/Server.php index 7e3ab360ed..fab82835b4 100644 --- a/src/Components/swoole/src/Server/TcpServer/Server.php +++ b/src/Components/swoole/src/Server/TcpServer/Server.php @@ -96,7 +96,7 @@ protected function __bindEvents(): void $events = $this->config['events'] ?? null; if ($event = ($events['connect'] ?? true)) { - $this->swoolePort->on('connect', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect) { + $this->swoolePort->on('connect', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -129,13 +129,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('connect', static function () { + $this->swoolePort->on('connect', static function (): void { }); } if ($event = ($events['receive'] ?? true)) { - $this->swoolePort->on('receive', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId, string $data) use ($enableSyncConnect) { + $this->swoolePort->on('receive', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId, string $data) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -169,13 +169,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('receive', static function () { + $this->swoolePort->on('receive', static function (): void { }); } if ($event = ($events['close'] ?? true)) { - $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect) { + $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -204,7 +204,7 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('close', static function () { + $this->swoolePort->on('close', static function (): void { }); } } diff --git a/src/Components/swoole/src/Server/UdpServer/Message/PacketData.php b/src/Components/swoole/src/Server/UdpServer/Message/PacketData.php index 4b93b2e76e..5f331239f2 100644 --- a/src/Components/swoole/src/Server/UdpServer/Message/PacketData.php +++ b/src/Components/swoole/src/Server/UdpServer/Message/PacketData.php @@ -6,15 +6,13 @@ class PacketData extends \Imi\Server\UdpServer\Message\PacketData implements IPacketData { - /** - * 客户端信息. - */ - protected array $clientInfo = []; - - public function __construct(string $remoteIp, int $remotePort, string $data, array $clientInfo) + public function __construct(string $remoteIp, int $remotePort, string $data, + /** + * 客户端信息. + */ + protected array $clientInfo) { parent::__construct($remoteIp, $remotePort, $data); - $this->clientInfo = $clientInfo; } /** diff --git a/src/Components/swoole/src/Server/UdpServer/Server.php b/src/Components/swoole/src/Server/UdpServer/Server.php index 01dea5df27..5f1f9613a6 100644 --- a/src/Components/swoole/src/Server/UdpServer/Server.php +++ b/src/Components/swoole/src/Server/UdpServer/Server.php @@ -78,7 +78,7 @@ protected function __bindEvents(): void { if ($event = ($this->config['events']['packet'] ?? true)) { - $this->swoolePort->on('packet', \is_callable($event) ? $event : function (\Swoole\Server $server, string $data, array $clientInfo) { + $this->swoolePort->on('packet', \is_callable($event) ? $event : function (\Swoole\Server $server, string $data, array $clientInfo): void { try { if (!Worker::isInited()) @@ -103,7 +103,7 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('packet', static function () { + $this->swoolePort->on('packet', static function (): void { }); } } diff --git a/src/Components/swoole/src/Server/Util/Amqp/AmqpServerConsumer.php b/src/Components/swoole/src/Server/Util/Amqp/AmqpServerConsumer.php index e85cb0b6fe..05eaa33f0f 100644 --- a/src/Components/swoole/src/Server/Util/Amqp/AmqpServerConsumer.php +++ b/src/Components/swoole/src/Server/Util/Amqp/AmqpServerConsumer.php @@ -26,11 +26,8 @@ */ class AmqpServerConsumer extends BaseConsumer { - protected ?AmqpServerUtil $amqpServerUtil; - - public function __construct(?AmqpServerUtil $amqpServerUtil = null) + public function __construct(protected ?AmqpServerUtil $amqpServerUtil = null) { - $this->amqpServerUtil = $amqpServerUtil; parent::__construct(); } @@ -83,21 +80,14 @@ protected function consume(IMessage $message) $data = json_decode($message->getBody(), true); $serverName = $data['serverName']; RequestContext::set('server', $server = ServerManager::getServer($serverName)); - switch ($data['action'] ?? null) + match ($data['action'] ?? null) { - case 'sendRawByFlag': - Server::sendRawByFlag($data['data'], $data['flag'], $serverName, false); - break; - case 'closeByFlag': - Server::closeByFlag($data['flag'], $serverName, false); - break; - case 'sendRawToGroup': - Server::sendRawToGroup($data['group'], $data['data'], $serverName, false); - break; - case 'sendRawToAll': - Server::sendRawToAll($data['data'], $serverName, false); - break; - } + 'sendRawByFlag' => Server::sendRawByFlag($data['data'], $data['flag'], $serverName, false), + 'closeByFlag' => Server::closeByFlag($data['flag'], $serverName, false), + 'sendRawToGroup' => Server::sendRawToGroup($data['group'], $data['data'], $serverName, false), + 'sendRawToAll' => Server::sendRawToAll($data['data'], $serverName, false), + default => ConsumerResult::ACK, + }; return ConsumerResult::ACK; } diff --git a/src/Components/swoole/src/Server/Util/Amqp/AmqpServerPublisher.php b/src/Components/swoole/src/Server/Util/Amqp/AmqpServerPublisher.php index cb32c0275e..c9d040a88a 100644 --- a/src/Components/swoole/src/Server/Util/Amqp/AmqpServerPublisher.php +++ b/src/Components/swoole/src/Server/Util/Amqp/AmqpServerPublisher.php @@ -18,11 +18,8 @@ */ class AmqpServerPublisher extends BasePublisher { - protected ?AmqpServerUtil $amqpServerUtil; - - public function __construct(?AmqpServerUtil $amqpServerUtil = null) + public function __construct(protected ?AmqpServerUtil $amqpServerUtil = null) { - $this->amqpServerUtil = $amqpServerUtil; parent::__construct(); } diff --git a/src/Components/swoole/src/Server/Util/AmqpServerUtil.php b/src/Components/swoole/src/Server/Util/AmqpServerUtil.php index 7bdf36f9fa..567477f7cf 100644 --- a/src/Components/swoole/src/Server/Util/AmqpServerUtil.php +++ b/src/Components/swoole/src/Server/Util/AmqpServerUtil.php @@ -60,7 +60,7 @@ public function __init(): void { $this->server = $server = RequestContext::getServer(); $this->consumerInstance = $server->getBean($this->consumerClass, $this); - Event::one('IMI.MAIN_SERVER.WORKER.EXIT', function () { + Event::one('IMI.MAIN_SERVER.WORKER.EXIT', function (): void { $this->subscribeEnable = false; }); $this->startSubscribe(); @@ -307,7 +307,7 @@ public function startSubscribe(): void $server = RequestContext::getServer(); if ($this->subscribeEnable && $server && $server->isLongConnection()) { - defer(fn () => imigo(function () { + defer(fn () => imigo(function (): void { try { $this->consumerInstance->run(); @@ -336,12 +336,8 @@ public function getPublisherInstance(): IPublisher { return RequestContext::use(function (\ArrayObject $context) { $key = static::class . ':' . $this->server->getName() . ':publisherClass'; - if (isset($context[$key])) - { - return $context[$key]; - } - return $context[$key] = $this->server->getBean($this->publisherClass, $this); + return $context[$key] ?? ($context[$key] = $this->server->getBean($this->publisherClass, $this)); }); } diff --git a/src/Components/swoole/src/Server/Util/LocalServerUtil.php b/src/Components/swoole/src/Server/Util/LocalServerUtil.php index 999d451359..a2fe67c658 100644 --- a/src/Components/swoole/src/Server/Util/LocalServerUtil.php +++ b/src/Components/swoole/src/Server/Util/LocalServerUtil.php @@ -61,7 +61,7 @@ public function sendMessageRaw(string $message, $workerId = null): int { if ($tmpWorkerId === $currentWorkerId) { - Coroutine::create(static function () use ($server, $currentWorkerId, $message) { + Coroutine::create(static function () use ($server, $currentWorkerId, $message): void { Event::trigger('IMI.MAIN_SERVER.PIPE_MESSAGE', [ 'server' => $server, 'workerId' => $currentWorkerId, diff --git a/src/Components/swoole/src/Server/Util/RedisServerUtil.php b/src/Components/swoole/src/Server/Util/RedisServerUtil.php index 26351befd7..77b42de16e 100644 --- a/src/Components/swoole/src/Server/Util/RedisServerUtil.php +++ b/src/Components/swoole/src/Server/Util/RedisServerUtil.php @@ -37,7 +37,7 @@ class RedisServerUtil extends LocalServerUtil public function __init(): void { - Event::one('IMI.MAIN_SERVER.WORKER.EXIT', function () { + Event::one('IMI.MAIN_SERVER.WORKER.EXIT', function (): void { $this->subscribeEnable = false; }); $this->startSubscribe(); @@ -293,14 +293,14 @@ public function flagExists(?string $flag, ?string $serverName = null, bool $toAl public function startSubscribe(): void { - Coroutine::create(function () { + Coroutine::create(function (): void { $redis = RedisManager::getInstance($this->redisName); while ($this->subscribeEnable) { try { - $redis->subscribe([$this->channel], function ($redis, string $channel, string $msg) { - Coroutine::create(function () use ($msg) { + $redis->subscribe([$this->channel], function ($redis, string $channel, string $msg): void { + Coroutine::create(function () use ($msg): void { $data = json_decode($msg, true); if (!isset($data['action'], $data['serverName'])) { diff --git a/src/Components/swoole/src/Server/WebSocket/Message/Frame.php b/src/Components/swoole/src/Server/WebSocket/Message/Frame.php index 38422880e0..fb7cceea73 100644 --- a/src/Components/swoole/src/Server/WebSocket/Message/Frame.php +++ b/src/Components/swoole/src/Server/WebSocket/Message/Frame.php @@ -10,11 +10,6 @@ class Frame implements ISwooleWebSocketFrame { - /** - * swoole websocket frame. - */ - protected ?\Swoole\WebSocket\Frame $frame = null; - /** * 客户端地址 */ @@ -27,9 +22,12 @@ class Frame implements ISwooleWebSocketFrame */ protected $data; - public function __construct(\Swoole\Websocket\Frame $frame) + public function __construct( + /** + * swoole websocket frame. + */ + protected ?\Swoole\WebSocket\Frame $frame) { - $this->frame = $frame; $this->data = RequestContext::getServerBean(DataParser::class)->decode($frame->data); } diff --git a/src/Components/swoole/src/Server/WebSocket/Middleware/HandShakeMiddleware.php b/src/Components/swoole/src/Server/WebSocket/Middleware/HandShakeMiddleware.php index 75491f2475..6fb22a10f8 100644 --- a/src/Components/swoole/src/Server/WebSocket/Middleware/HandShakeMiddleware.php +++ b/src/Components/swoole/src/Server/WebSocket/Middleware/HandShakeMiddleware.php @@ -68,7 +68,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface else { $clientId = $requestContext['clientId']; - Coroutine::defer(static function () use ($clientId) { + Coroutine::defer(static function () use ($clientId): void { Server::close($clientId); }); } diff --git a/src/Components/swoole/src/Server/WebSocket/Server.php b/src/Components/swoole/src/Server/WebSocket/Server.php index c35621bcb9..a990ab2e27 100644 --- a/src/Components/swoole/src/Server/WebSocket/Server.php +++ b/src/Components/swoole/src/Server/WebSocket/Server.php @@ -118,7 +118,7 @@ protected function getServerInitConfig(): array */ protected function __bindEvents(): void { - Event::one('IMI.MAIN_SERVER.WORKER.START.APP', function (WorkerStartEventParam $e) { + Event::one('IMI.MAIN_SERVER.WORKER.START.APP', function (WorkerStartEventParam $e): void { // 内置事件监听 $this->on('request', [new BeforeRequest($this), 'handle'], ImiPriority::IMI_MAX); }); @@ -127,7 +127,7 @@ protected function __bindEvents(): void $events = $this->config['events'] ?? null; if ($event = ($events['handshake'] ?? true)) { - $this->swoolePort->on('handshake', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse) use ($enableSyncConnect) { + $this->swoolePort->on('handshake', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -172,13 +172,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('handshake', static function () { + $this->swoolePort->on('handshake', static function (): void { }); } if ($event = ($events['message'] ?? true)) { - $this->swoolePort->on('message', \is_callable($event) ? $event : function (\Swoole\Server $server, \Swoole\WebSocket\Frame $frame) use ($enableSyncConnect) { + $this->swoolePort->on('message', \is_callable($event) ? $event : function (\Swoole\Server $server, \Swoole\WebSocket\Frame $frame) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -214,13 +214,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('message', static function () { + $this->swoolePort->on('message', static function (): void { }); } if ($event = ($events['close'] ?? true)) { - $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect) { + $this->swoolePort->on('close', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd, int $reactorId) use ($enableSyncConnect): void { try { if ($enableSyncConnect) @@ -252,13 +252,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('close', static function () { + $this->swoolePort->on('close', static function (): void { }); } if ($event = ($events['request'] ?? true)) { - $this->swoolePort->on('request', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse) { + $this->swoolePort->on('request', \is_callable($event) ? $event : function (\Swoole\Http\Request $swooleRequest, \Swoole\Http\Response $swooleResponse): void { try { if (!Worker::isInited()) @@ -291,13 +291,13 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('request', static function () { + $this->swoolePort->on('request', static function (): void { }); } if ($event = ($events['disconnect'] ?? true)) { - $this->swoolePort->on('disconnect', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd) { + $this->swoolePort->on('disconnect', \is_callable($event) ? $event : function (\Swoole\Server $server, int $fd): void { try { RequestContext::muiltiSet([ @@ -316,7 +316,7 @@ protected function __bindEvents(): void } else { - $this->swoolePort->on('disconnect', static function () { + $this->swoolePort->on('disconnect', static function (): void { }); } } diff --git a/src/Components/swoole/src/SwooleApp.php b/src/Components/swoole/src/SwooleApp.php index 6463cd2868..12c2500c2f 100644 --- a/src/Components/swoole/src/SwooleApp.php +++ b/src/Components/swoole/src/SwooleApp.php @@ -51,10 +51,10 @@ class SwooleApp extends CliApp public function __construct(string $namespace) { parent::__construct($namespace); - $this->cliEventDispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $e) { + $this->cliEventDispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $e): void { $this->onCommand($e); }, \PHP_INT_MAX - 1000); - Event::one('IMI.SCAN_APP', function () { + Event::one('IMI.SCAN_APP', function (): void { $this->onScanApp(); }); } @@ -198,7 +198,7 @@ public function loadMain(): void public function init(): void { parent::init(); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { // @phpstan-ignore-next-line App::getBean('Logger')->clear(); }); @@ -213,7 +213,7 @@ public function init(): void // @phpstan-ignore-next-line Worker::setWorkerHandler(App::getBean('SwooleWorkerHandler')); } - Event::on(['IMI.PROCESS.BEGIN', 'IMI.MAIN_SERVER.WORKER.START'], static function () { + Event::on(['IMI.PROCESS.BEGIN', 'IMI.MAIN_SERVER.WORKER.START'], static function (): void { PoolManager::init(); CacheManager::init(); Lock::init(); diff --git a/src/Components/swoole/src/SwooleTimer.php b/src/Components/swoole/src/SwooleTimer.php index c9774dbb60..e05385acd2 100644 --- a/src/Components/swoole/src/SwooleTimer.php +++ b/src/Components/swoole/src/SwooleTimer.php @@ -15,7 +15,7 @@ class SwooleTimer implements ITimer */ public function tick(int $ms, callable $callback): int { - return Timer::tick($ms, static function () use ($callback) { + return Timer::tick($ms, static function () use ($callback): void { try { $callback(); @@ -32,7 +32,7 @@ public function tick(int $ms, callable $callback): int */ public function after(int $ms, callable $callback): int { - return Timer::after($ms, static function () use ($callback) { + return Timer::after($ms, static function () use ($callback): void { try { $callback(); diff --git a/src/Components/swoole/src/Task/Handler/BeanTaskHandler.php b/src/Components/swoole/src/Task/Handler/BeanTaskHandler.php index 8bdd931d17..8cbe86c12f 100644 --- a/src/Components/swoole/src/Task/Handler/BeanTaskHandler.php +++ b/src/Components/swoole/src/Task/Handler/BeanTaskHandler.php @@ -10,14 +10,12 @@ class BeanTaskHandler implements ITaskHandler { - /** - * 任务类类名. - */ - private string $taskHandlerClass = ''; - - public function __construct(string $taskHandlerClass) - { - $this->taskHandlerClass = $taskHandlerClass; + public function __construct( + /** + * 任务类类名. + */ + private readonly string $taskHandlerClass + ) { } /** diff --git a/src/Components/swoole/src/Task/TaskInfo.php b/src/Components/swoole/src/Task/TaskInfo.php index 422804ca41..b9db795451 100644 --- a/src/Components/swoole/src/Task/TaskInfo.php +++ b/src/Components/swoole/src/Task/TaskInfo.php @@ -8,20 +8,16 @@ class TaskInfo { - /** - * 任务执行器. - */ - private ITaskHandler $taskHandler; - - /** - * 任务参数. - */ - private TaskParam $param; - - public function __construct(ITaskHandler $taskHandler, TaskParam $param) - { - $this->taskHandler = $taskHandler; - $this->param = $param; + public function __construct( + /** + * 任务执行器. + */ + private readonly ITaskHandler $taskHandler, + /** + * 任务参数. + */ + private readonly TaskParam $param + ) { } public function getTaskHandler(): ITaskHandler diff --git a/src/Components/swoole/src/Task/TaskParam.php b/src/Components/swoole/src/Task/TaskParam.php index 096c94bdf8..60e5357ae6 100644 --- a/src/Components/swoole/src/Task/TaskParam.php +++ b/src/Components/swoole/src/Task/TaskParam.php @@ -8,17 +8,11 @@ class TaskParam implements ITaskParam { - /** - * @var mixed - */ - protected $data = []; - /** * @param mixed $data */ - public function __construct($data = []) + public function __construct(protected $data = []) { - $this->data = $data; } /** diff --git a/src/Components/swoole/src/Util/Imi.php b/src/Components/swoole/src/Util/Imi.php index 475029dde4..c8d7074cbe 100644 --- a/src/Components/swoole/src/Util/Imi.php +++ b/src/Components/swoole/src/Util/Imi.php @@ -80,7 +80,7 @@ public static function getProcessName(string $type, array $data = []): string { continue; } - $result = str_replace('{' . $k . '}', (string) $v, $result); + $result = str_replace('{' . $k . '}', (string) $v, (string) $result); } return $result; diff --git a/src/Components/swoole/src/Worker/SwooleWorkerHandler.php b/src/Components/swoole/src/Worker/SwooleWorkerHandler.php index e525079a22..220e398331 100644 --- a/src/Components/swoole/src/Worker/SwooleWorkerHandler.php +++ b/src/Components/swoole/src/Worker/SwooleWorkerHandler.php @@ -106,7 +106,7 @@ public function inited(): void ], $mainServer, WorkerStartEventParam::class); $this->workerStartAppComplete = true; } - $func = static function () { + $func = static function (): void { if (ChannelContainer::hasChannel('workerInit')) { ChannelContainer::removeChannel('workerInit'); diff --git a/src/Components/swoole/src/functions.php b/src/Components/swoole/src/functions.php index fa17e030e9..e9bcd15ff5 100644 --- a/src/Components/swoole/src/functions.php +++ b/src/Components/swoole/src/functions.php @@ -16,7 +16,7 @@ function imigo(callable $callable, ...$args): int { $callable = imiCallable($callable); - return Coroutine::create(static function () use ($callable, $args) { + return Coroutine::create(static function () use ($callable, $args): void { try { $callable(...$args); diff --git a/src/Components/swoole/tests/bootstrap.php b/src/Components/swoole/tests/bootstrap.php index 4f45e8ebd2..6c28121249 100644 --- a/src/Components/swoole/tests/bootstrap.php +++ b/src/Components/swoole/tests/bootstrap.php @@ -271,14 +271,14 @@ function checkWebSocketServerWithAmqpRouteServerUtilStatus(): bool $callbacks = []; foreach ($servers as $name => $options) { - $callbacks[] = static function () use ($options, $name) { + $callbacks[] = static function () use ($options, $name): void { // start server $cmd = 'nohup ' . $options['start'] . ' > /dev/null 2>&1'; echo "Starting {$name}...", \PHP_EOL; $code = ttyExec($cmd); if (0 === $code) { - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { \Swoole\Runtime::enableCoroutine(false); // stop server $cmd = $options['stop']; @@ -305,7 +305,7 @@ function checkWebSocketServerWithAmqpRouteServerUtilStatus(): bool batch($callbacks, 1200, max(swoole_cpu_num() - 1, 1)); - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { \Swoole\Runtime::enableCoroutine(false); checkPorts([13000, 13001, 13002, 13003, 13004, 13005, 13006, 13007, 13008, 13009, 13010]); }); diff --git a/src/Components/swoole/tests/unit/BaseTest.php b/src/Components/swoole/tests/unit/BaseTest.php index cd6a71563e..57525f6c52 100644 --- a/src/Components/swoole/tests/unit/BaseTest.php +++ b/src/Components/swoole/tests/unit/BaseTest.php @@ -28,7 +28,7 @@ protected function go(callable $callable, ?callable $finally = null, int $retry } $throwable = null; $time = microtime(true); - goWait(static function () use ($callable, &$throwable) { + goWait(static function () use ($callable, &$throwable): void { try { $callable(); diff --git a/src/Components/swoole/tests/unit/Component/PHPUnitHook.php b/src/Components/swoole/tests/unit/Component/PHPUnitHook.php index adf9db4602..7d44a7d15c 100644 --- a/src/Components/swoole/tests/unit/Component/PHPUnitHook.php +++ b/src/Components/swoole/tests/unit/Component/PHPUnitHook.php @@ -21,8 +21,8 @@ class PHPUnitHook implements BeforeFirstTestHook, AfterLastTestHook public function executeBeforeFirstTest(): void { $this->channel = $channel = new Channel(1); - Coroutine::create(static fn () => App::run('Imi\Swoole\Test\Component', SwooleApp::class, static function () use ($channel) { - PoolManager::use('maindb', static function (IPoolResource $resource, IDb $db) { + Coroutine::create(static fn () => App::run('Imi\Swoole\Test\Component', SwooleApp::class, static function () use ($channel): void { + PoolManager::use('maindb', static function (IPoolResource $resource, IDb $db): void { $truncateList = [ 'tb_article', 'tb_member', diff --git a/src/Components/swoole/tests/unit/Component/Tests/CacheAnnotationTest.php b/src/Components/swoole/tests/unit/Component/Tests/CacheAnnotationTest.php index 86fdd42593..f9ce8742c2 100644 --- a/src/Components/swoole/tests/unit/Component/Tests/CacheAnnotationTest.php +++ b/src/Components/swoole/tests/unit/Component/Tests/CacheAnnotationTest.php @@ -19,7 +19,7 @@ class CacheAnnotationTest extends BaseTest */ public function testCacheableTTL(): void { - $this->go(static function () { + $this->go(static function (): void { /** @var \Imi\Swoole\Test\Component\Cache\Classes\TestCacheAnnotation $test */ $test = App::getBean('TestCacheAnnotation'); $id = 1; @@ -46,7 +46,7 @@ public function testCacheableTTL(): void public function testCacheableLock(): void { - $this->go(static function () { + $this->go(static function (): void { /** @var \Imi\Swoole\Test\Component\Cache\Classes\TestCacheAnnotation $test */ $test = App::getBean('TestCacheAnnotation'); $id = 1; @@ -74,7 +74,7 @@ public function testCacheableLock(): void { $throwables[] = null; $index = $i; - Coroutine::create(static function () use (&$throwables, $index, $test, $id, $channel) { + Coroutine::create(static function () use (&$throwables, $index, $test, $id, $channel): void { try { $result2 = $test->testCacheableLock($id); diff --git a/src/Components/swoole/tests/unit/Component/Tests/LockAnnotationTest.php b/src/Components/swoole/tests/unit/Component/Tests/LockAnnotationTest.php index d1da92c22d..052fec0d57 100644 --- a/src/Components/swoole/tests/unit/Component/Tests/LockAnnotationTest.php +++ b/src/Components/swoole/tests/unit/Component/Tests/LockAnnotationTest.php @@ -27,7 +27,7 @@ public function test(): void { $throwables[] = null; $index = $i; - Coroutine::create(static function () use (&$throwables, $index, $test, $channel) { + Coroutine::create(static function () use (&$throwables, $index, $test, $channel): void { try { $test->test(); diff --git a/src/Components/swoole/tests/unit/Component/Tests/PoolTest.php b/src/Components/swoole/tests/unit/Component/Tests/PoolTest.php index 7fe57e1abf..0ab1e1f351 100644 --- a/src/Components/swoole/tests/unit/Component/Tests/PoolTest.php +++ b/src/Components/swoole/tests/unit/Component/Tests/PoolTest.php @@ -13,7 +13,7 @@ class PoolTest extends BaseTest { public function testPoolResource(): void { - $this->go(function () { + $this->go(function (): void { $object = RequestContext::getBean(PoolTestClass::class); $this->assertInstanceOf(DbResource::class, $object->db); }); diff --git a/src/Components/swoole/tests/unit/Component/Tests/RedisManagerTest.php b/src/Components/swoole/tests/unit/Component/Tests/RedisManagerTest.php index 30eb1d2310..927085138a 100644 --- a/src/Components/swoole/tests/unit/Component/Tests/RedisManagerTest.php +++ b/src/Components/swoole/tests/unit/Component/Tests/RedisManagerTest.php @@ -49,7 +49,7 @@ public function testNewInstance(): void public function testInstance(): void { $pool = PoolManager::getInstance('redis_manager_test'); - $this->go(function () use ($pool) { + $this->go(function () use ($pool): void { Assert::assertEquals(1, $pool->getCount()); Assert::assertEquals(1, $pool->getFree()); diff --git a/src/Components/swoole/tests/unit/Component/test.php b/src/Components/swoole/tests/unit/Component/test.php index 29fb914bb6..690b6e7aa3 100644 --- a/src/Components/swoole/tests/unit/Component/test.php +++ b/src/Components/swoole/tests/unit/Component/test.php @@ -10,8 +10,8 @@ require \dirname(__DIR__, 3) . '/vendor/autoload.php'; -run(static function () { - App::runApp(__DIR__, SwooleApp::class, static function () { +run(static function (): void { + App::runApp(__DIR__, SwooleApp::class, static function (): void { Db::getInstance(); // 必须,获取连接后,连接池就被启动了 echo 'Test swoole quick start', \PHP_EOL; }); diff --git a/src/Components/swoole/tests/unit/HttpServer/ApiServer/Controller/MemoryTableController.php b/src/Components/swoole/tests/unit/HttpServer/ApiServer/Controller/MemoryTableController.php index 7774dce1f9..cdd984cdbc 100644 --- a/src/Components/swoole/tests/unit/HttpServer/ApiServer/Controller/MemoryTableController.php +++ b/src/Components/swoole/tests/unit/HttpServer/ApiServer/Controller/MemoryTableController.php @@ -132,7 +132,7 @@ public function count(): array public function lockCallableSetAndGet(): ?array { $result = null; - MemoryTableManager::lock('t1', static function () use (&$result) { + MemoryTableManager::lock('t1', static function () use (&$result): void { $key = '1'; $row = [ 'name' => 'imi', diff --git a/src/Components/swoole/tests/unit/HttpServer/Listener/WorkerStart.php b/src/Components/swoole/tests/unit/HttpServer/Listener/WorkerStart.php index 5b69f03d16..2a657d0f94 100644 --- a/src/Components/swoole/tests/unit/HttpServer/Listener/WorkerStart.php +++ b/src/Components/swoole/tests/unit/HttpServer/Listener/WorkerStart.php @@ -26,7 +26,7 @@ public function handle(WorkerStartEventParam $e): void { if (0 === Worker::getWorkerId()) { - goWait(static function () { + goWait(static function (): void { sleep(1); $cron = new Cron(); $cron->id = 'CronRandomWorkerTest'; diff --git a/src/Components/swoole/tests/unit/HttpServer/Tests/CustomSessionIdTest.php b/src/Components/swoole/tests/unit/HttpServer/Tests/CustomSessionIdTest.php index 7088dd6bde..8009edcbcc 100644 --- a/src/Components/swoole/tests/unit/HttpServer/Tests/CustomSessionIdTest.php +++ b/src/Components/swoole/tests/unit/HttpServer/Tests/CustomSessionIdTest.php @@ -22,7 +22,7 @@ public function __construct(?string $name = null, array $data = [], string $data public function testSetGetDelete(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'session/login'); $sessionId = $response->getCookie('imisid'); @@ -48,7 +48,7 @@ public function testSetGetDelete(): void public function testOnce(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'session/verifySms?vcode=1234'); diff --git a/src/Components/swoole/tests/unit/HttpServer/Tests/Http2Test.php b/src/Components/swoole/tests/unit/HttpServer/Tests/Http2Test.php index 03938029a5..3589bb9afd 100644 --- a/src/Components/swoole/tests/unit/HttpServer/Tests/Http2Test.php +++ b/src/Components/swoole/tests/unit/HttpServer/Tests/Http2Test.php @@ -24,7 +24,7 @@ public function __construct(?string $name = null, array $data = [], string $data */ public function testUri(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->protocolVersion = '2.0'; $uri = $this->host . 'info?get=1'; diff --git a/src/Components/swoole/tests/unit/HttpServer/Tests/HttpsTest.php b/src/Components/swoole/tests/unit/HttpServer/Tests/HttpsTest.php index 3ae45f4f63..42ff2b7205 100644 --- a/src/Components/swoole/tests/unit/HttpServer/Tests/HttpsTest.php +++ b/src/Components/swoole/tests/unit/HttpServer/Tests/HttpsTest.php @@ -35,10 +35,8 @@ public function testUri(): void /** * 控制器指定 server 测试. - * - * @return void */ - public function testOutsideController() + public function testOutsideController(): void { $http = new HttpRequest(); $response = $http->get($this->host . 'testOutside'); diff --git a/src/Components/swoole/tests/unit/TCPServer/Tests/TCPTest.php b/src/Components/swoole/tests/unit/TCPServer/Tests/TCPTest.php index ff3fc4bcd7..e23c078c96 100644 --- a/src/Components/swoole/tests/unit/TCPServer/Tests/TCPTest.php +++ b/src/Components/swoole/tests/unit/TCPServer/Tests/TCPTest.php @@ -16,7 +16,7 @@ class TCPTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $client = new \Swoole\Coroutine\Client(\SWOOLE_SOCK_TCP); $client->set([ 'open_eof_split' => true, @@ -50,7 +50,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $client = new \Swoole\Coroutine\Client(\SWOOLE_SOCK_TCP); $client->set([ 'open_eof_split' => true, diff --git a/src/Components/swoole/tests/unit/UDPServer/Tests/UDPTest.php b/src/Components/swoole/tests/unit/UDPServer/Tests/UDPTest.php index 6c909d4813..f0bf268ca9 100644 --- a/src/Components/swoole/tests/unit/UDPServer/Tests/UDPTest.php +++ b/src/Components/swoole/tests/unit/UDPServer/Tests/UDPTest.php @@ -16,7 +16,7 @@ class UDPTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $uri = new Uri($this->host); $client = new \Swoole\Coroutine\Client(\SWOOLE_SOCK_UDP); $time = time(); @@ -33,7 +33,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $uri = new Uri($this->host); $client = new \Swoole\Coroutine\Client(\SWOOLE_SOCK_UDP); $time = time(); diff --git a/src/Components/swoole/tests/unit/WebSocketServer/Tests/ServerUtilTest.php b/src/Components/swoole/tests/unit/WebSocketServer/Tests/ServerUtilTest.php index ffa5a5a116..eaafb5333e 100644 --- a/src/Components/swoole/tests/unit/WebSocketServer/Tests/ServerUtilTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServer/Tests/ServerUtilTest.php @@ -13,7 +13,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/getServer'); $this->assertEquals([ @@ -26,7 +26,7 @@ public function testGetServer(): void public function testSendMessage(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/sendMessage'); $this->assertEquals([ @@ -42,7 +42,7 @@ public function testSendMessage(): void public function testSend(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -148,7 +148,7 @@ public function testSend(): void public function testSendToGroup(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -249,7 +249,7 @@ public function testSendToGroup(): void public function testExists(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; @@ -318,7 +318,7 @@ public function testExists(): void public function testClose(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; @@ -388,7 +388,7 @@ public function testClose(): void public function testGetConnectionCount(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; diff --git a/src/Components/swoole/tests/unit/WebSocketServer/Tests/WSTest.php b/src/Components/swoole/tests/unit/WebSocketServer/Tests/WSTest.php index cd17e6aa90..59ce9f3f3e 100644 --- a/src/Components/swoole/tests/unit/WebSocketServer/Tests/WSTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServer/Tests/WSTest.php @@ -16,7 +16,7 @@ class WSTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -104,7 +104,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -122,7 +122,7 @@ public function testNotFound(): void public function testMatchHttpRoute(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -157,7 +157,7 @@ public function testMatchHttpRoute(): void public function testContext(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -186,7 +186,7 @@ public function testContext(): void public function testHttp(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->timeout = 10000; $response = $http->get($this->host . 'http'); diff --git a/src/Components/swoole/tests/unit/WebSocketServerWithAmqpRouteServerUtil/Tests/ServerUtilTest.php b/src/Components/swoole/tests/unit/WebSocketServerWithAmqpRouteServerUtil/Tests/ServerUtilTest.php index 56e14dd102..45d7ddad82 100644 --- a/src/Components/swoole/tests/unit/WebSocketServerWithAmqpRouteServerUtil/Tests/ServerUtilTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServerWithAmqpRouteServerUtil/Tests/ServerUtilTest.php @@ -13,7 +13,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/getServer'); $this->assertEquals([ @@ -26,7 +26,7 @@ public function testGetServer(): void public function testSendMessage(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/sendMessage'); $this->assertEquals([ @@ -42,7 +42,7 @@ public function testSendMessage(): void public function testSend(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -148,7 +148,7 @@ public function testSend(): void public function testSendToGroup(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -233,7 +233,7 @@ public function testSendToGroup(): void public function testExists(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; @@ -302,7 +302,7 @@ public function testExists(): void public function testClose(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; diff --git a/src/Components/swoole/tests/unit/WebSocketServerWithAmqpServerUtil/Tests/ServerUtilTest.php b/src/Components/swoole/tests/unit/WebSocketServerWithAmqpServerUtil/Tests/ServerUtilTest.php index 383ff815ce..a6dd2faa3d 100644 --- a/src/Components/swoole/tests/unit/WebSocketServerWithAmqpServerUtil/Tests/ServerUtilTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServerWithAmqpServerUtil/Tests/ServerUtilTest.php @@ -13,7 +13,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/getServer'); $this->assertEquals([ @@ -26,7 +26,7 @@ public function testGetServer(): void public function testSendMessage(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/sendMessage'); $this->assertEquals([ @@ -42,7 +42,7 @@ public function testSendMessage(): void public function testSend(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -148,7 +148,7 @@ public function testSend(): void public function testSendToGroup(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -233,7 +233,7 @@ public function testSendToGroup(): void public function testExists(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; @@ -302,7 +302,7 @@ public function testExists(): void public function testClose(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; diff --git a/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/ServerUtilTest.php b/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/ServerUtilTest.php index 583c3a429a..3c43f6de53 100644 --- a/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/ServerUtilTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/ServerUtilTest.php @@ -13,7 +13,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/getServer'); $this->assertEquals([ @@ -26,7 +26,7 @@ public function testGetServer(): void public function testSendMessage(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->host . 'serverUtil/sendMessage'); $this->assertEquals([ @@ -42,7 +42,7 @@ public function testSendMessage(): void public function testSend(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -148,7 +148,7 @@ public function testSend(): void public function testSendToGroup(): void { - $this->go(function () { + $this->go(function (): void { $dataStr = json_encode([ 'data' => 'test', ]); @@ -233,7 +233,7 @@ public function testSendToGroup(): void public function testExists(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; @@ -302,7 +302,7 @@ public function testExists(): void public function testClose(): void { - $this->go(function () { + $this->go(function (): void { do { echo 'try get workerId 0', \PHP_EOL; diff --git a/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/WSTest.php b/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/WSTest.php index f4942d1220..e08c0e18c0 100644 --- a/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/WSTest.php +++ b/src/Components/swoole/tests/unit/WebSocketServerWithRedisServerUtil/Tests/WSTest.php @@ -16,7 +16,7 @@ class WSTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -62,7 +62,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -79,7 +79,7 @@ public function testNotFound(): void public function testMatchHttpRoute(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->retry = 3; $http->timeout = 10000; @@ -112,7 +112,7 @@ public function testMatchHttpRoute(): void public function testHttp(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $http->timeout = 10000; $response = $http->get($this->host . 'http'); diff --git a/src/Components/workerman-gateway/src/Server/ConnectionContext/StoreHandler/ConnectionContextGateway.php b/src/Components/workerman-gateway/src/Server/ConnectionContext/StoreHandler/ConnectionContextGateway.php index 515e2d581f..ddc6db8dc6 100644 --- a/src/Components/workerman-gateway/src/Server/ConnectionContext/StoreHandler/ConnectionContextGateway.php +++ b/src/Components/workerman-gateway/src/Server/ConnectionContext/StoreHandler/ConnectionContextGateway.php @@ -62,7 +62,7 @@ public function delayDestroy(string $key, int $ttl): void { return; } - Timer::after($ttl * 1000, function () use ($key) { + Timer::after($ttl * 1000, function () use ($key): void { $this->destroy($key); }); } diff --git a/src/Components/workerman-gateway/src/Swoole/Http/Message/WorkermanGatewaySwooleRequest.php b/src/Components/workerman-gateway/src/Swoole/Http/Message/WorkermanGatewaySwooleRequest.php index 65dbe2591b..14b35149ff 100644 --- a/src/Components/workerman-gateway/src/Swoole/Http/Message/WorkermanGatewaySwooleRequest.php +++ b/src/Components/workerman-gateway/src/Swoole/Http/Message/WorkermanGatewaySwooleRequest.php @@ -15,20 +15,14 @@ { class WorkermanGatewaySwooleRequest extends Request { - /** - * 对应的服务器. - */ - protected ?ISwooleServer $serverInstance = null; - - protected string $clientId = ''; - - protected array $data = []; - - public function __construct(ISwooleServer $server, string $clientId, array $data) - { - $this->serverInstance = $server; - $this->clientId = $clientId; - $this->data = $data; + public function __construct( + /** + * 对应的服务器. + */ + protected ?ISwooleServer $serverInstance, + protected string $clientId, + protected array $data + ) { } /** @@ -36,7 +30,7 @@ public function __construct(ISwooleServer $server, string $clientId, array $data */ protected function initProtocolVersion(): void { - [, $this->protocolVersion] = explode('/', $this->data['server']['SERVER_PROTOCOL']); + [, $this->protocolVersion] = explode('/', (string) $this->data['server']['SERVER_PROTOCOL']); } /** @@ -47,9 +41,9 @@ protected function initHeaders(): void $headers = []; foreach ($this->data['server'] as $name => $value) { - if (str_starts_with($name, 'HTTP_')) + if (str_starts_with((string) $name, 'HTTP_')) { - $headers[str_replace('_', '-', substr($name, 5))] = $value; + $headers[str_replace('_', '-', substr((string) $name, 5))] = $value; } } $this->mergeHeaders($headers); diff --git a/src/Components/workerman-gateway/src/Swoole/Server/Business/Task/WorkerTask.php b/src/Components/workerman-gateway/src/Swoole/Server/Business/Task/WorkerTask.php index bb1abf4d3e..696f62294b 100644 --- a/src/Components/workerman-gateway/src/Swoole/Server/Business/Task/WorkerTask.php +++ b/src/Components/workerman-gateway/src/Swoole/Server/Business/Task/WorkerTask.php @@ -32,10 +32,10 @@ abstract class WorkerTask implements ICoTask /** * {@inheritDoc} */ - public function run(ITaskParam $param) + public function run(ITaskParam $param): void { $errorHandler = $this->errorHandler; - goWait(static function () use ($param, $errorHandler) { + goWait(static function () use ($param, $errorHandler): void { $closeConnectionOnFail = false; $cmd = null; try diff --git a/src/Components/workerman-gateway/src/Swoole/Server/Business/TcpBusinessServer.php b/src/Components/workerman-gateway/src/Swoole/Server/Business/TcpBusinessServer.php index 4b6f36960d..8e6ec08871 100644 --- a/src/Components/workerman-gateway/src/Swoole/Server/Business/TcpBusinessServer.php +++ b/src/Components/workerman-gateway/src/Swoole/Server/Business/TcpBusinessServer.php @@ -51,7 +51,7 @@ protected function getServerInitConfig(): array public function __construct(string $name, array $config) { parent::__construct($name, $config); - Event::one('IMI.MAIN_SERVER.WORKER.START', function () { + Event::one('IMI.MAIN_SERVER.WORKER.START', function (): void { if (!SwooleWorker::isTask()) { $this->initGatewayWorker(); @@ -72,23 +72,23 @@ protected function initGatewayWorker(): void } } - Coroutine::create(function () use ($workermanGatewayConfig) { + Coroutine::create(function () use ($workermanGatewayConfig): void { $this->pool = $pool = new CoPool($workermanGatewayConfig['worker_coroutine_num'] ?? swoole_cpu_num(), $workermanGatewayConfig['channel']['size'] ?? 1024, TcpWorkerTask::class); $pool->run(); $pool->wait(); }); - Coroutine::create(function () use ($workermanGatewayConfig) { + Coroutine::create(function () use ($workermanGatewayConfig): void { $config = new GatewayWorkerConfig($workermanGatewayConfig); // Gateway Worker $client = new GatewayWorkerClient(($workermanGatewayConfig['workerName'] ?? $this->getName()) . ':' . Worker::getWorkerId(), $config); // 异常处理 - $client->onException = static function (\Throwable $th) { + $client->onException = static function (\Throwable $th): void { Log::error($th); }; // 网关消息 - $client->onGatewayMessage = function (IGatewayClient $client, array $message) { + $client->onGatewayMessage = function (IGatewayClient $client, array $message): void { $clientId = Context::addressToClientId($message['local_ip'], $message['local_port'], $message['connection_id']); $this->pool->addTaskAsync([ 'server' => $this, diff --git a/src/Components/workerman-gateway/src/Swoole/Server/Business/WebSocketBusinessServer.php b/src/Components/workerman-gateway/src/Swoole/Server/Business/WebSocketBusinessServer.php index 6c22b383f1..fa7c50eb41 100644 --- a/src/Components/workerman-gateway/src/Swoole/Server/Business/WebSocketBusinessServer.php +++ b/src/Components/workerman-gateway/src/Swoole/Server/Business/WebSocketBusinessServer.php @@ -51,7 +51,7 @@ protected function getServerInitConfig(): array public function __construct(string $name, array $config) { parent::__construct($name, $config); - Event::one('IMI.MAIN_SERVER.WORKER.START', function () { + Event::one('IMI.MAIN_SERVER.WORKER.START', function (): void { if (!SwooleWorker::isTask()) { $this->initGatewayWorker(); @@ -72,23 +72,23 @@ protected function initGatewayWorker(): void } } - Coroutine::create(function () use ($workermanGatewayConfig) { + Coroutine::create(function () use ($workermanGatewayConfig): void { $this->pool = $pool = new CoPool($workermanGatewayConfig['worker_coroutine_num'] ?? swoole_cpu_num(), $workermanGatewayConfig['channel']['size'] ?? 1024, WebSocketWorkerTask::class); $pool->run(); $pool->wait(); }); - Coroutine::create(function () use ($workermanGatewayConfig) { + Coroutine::create(function () use ($workermanGatewayConfig): void { $config = new GatewayWorkerConfig($workermanGatewayConfig); // Gateway Worker $client = new GatewayWorkerClient(($workermanGatewayConfig['workerName'] ?? $this->getName()) . ':' . Worker::getWorkerId(), $config); // 异常处理 - $client->onException = static function (\Throwable $th) { + $client->onException = static function (\Throwable $th): void { Log::error($th); }; // 网关消息 - $client->onGatewayMessage = function (IGatewayClient $client, array $message) { + $client->onGatewayMessage = function (IGatewayClient $client, array $message): void { $clientId = Context::addressToClientId($message['local_ip'], $message['local_port'], $message['connection_id']); $this->pool->addTaskAsync([ 'server' => $this, diff --git a/src/Components/workerman-gateway/src/Workerman/Http/Message/WorkermanRequest.php b/src/Components/workerman-gateway/src/Workerman/Http/Message/WorkermanRequest.php index c8ab860add..3cd5c12e9f 100644 --- a/src/Components/workerman-gateway/src/Workerman/Http/Message/WorkermanRequest.php +++ b/src/Components/workerman-gateway/src/Workerman/Http/Message/WorkermanRequest.php @@ -13,20 +13,14 @@ class WorkermanRequest extends Request { - /** - * Workerman 的 Worker 对象 - */ - protected ?Worker $worker = null; - - protected string $clientId = ''; - - protected array $data = []; - - public function __construct(Worker $worker, string $clientId, array $data) - { - $this->worker = $worker; - $this->clientId = $clientId; - $this->data = $data; + public function __construct( + /** + * Workerman 的 Worker 对象 + */ + protected ?Worker $worker, + protected string $clientId, + protected array $data + ) { } /** @@ -34,7 +28,7 @@ public function __construct(Worker $worker, string $clientId, array $data) */ protected function initProtocolVersion(): void { - [, $this->protocolVersion] = explode('/', $this->data['server']['SERVER_PROTOCOL']); + [, $this->protocolVersion] = explode('/', (string) $this->data['server']['SERVER_PROTOCOL']); } /** @@ -45,9 +39,9 @@ protected function initHeaders(): void $headers = []; foreach ($this->data['server'] as $name => $value) { - if (str_starts_with($name, 'HTTP_')) + if (str_starts_with((string) $name, 'HTTP_')) { - $headers[str_replace('_', '-', substr($name, 5))] = $value; + $headers[str_replace('_', '-', substr((string) $name, 5))] = $value; } } $this->mergeHeaders($headers); diff --git a/src/Components/workerman-gateway/src/Workerman/Server/Business/TcpBusinessServer.php b/src/Components/workerman-gateway/src/Workerman/Server/Business/TcpBusinessServer.php index 5f1d2f4bc4..0c2e6add12 100644 --- a/src/Components/workerman-gateway/src/Workerman/Server/Business/TcpBusinessServer.php +++ b/src/Components/workerman-gateway/src/Workerman/Server/Business/TcpBusinessServer.php @@ -31,7 +31,7 @@ class TcpBusinessServer extends \Imi\Workerman\Server\Tcp\Server public function __construct(string $name, array $config) { parent::__construct($name, $config); - Event::one('IMI.WORKERMAN.SERVER.WORKER_START', function () { + Event::one('IMI.WORKERMAN.SERVER.WORKER_START', function (): void { $this->bindBusinessEvents(); }); } @@ -65,7 +65,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnConnect'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId) { + $property->setValue($worker, function (string $clientId): void { RequestContext::muiltiSet([ 'server' => $this, 'clientId' => $clientId, @@ -83,7 +83,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnClose'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId) { + $property->setValue($worker, function (string $clientId): void { RequestContext::muiltiSet([ 'server' => $this, 'clientId' => $clientId, @@ -97,7 +97,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnMessage'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId, $data) { + $property->setValue($worker, function (string $clientId, $data): void { try { RequestContext::muiltiSet([ diff --git a/src/Components/workerman-gateway/src/Workerman/Server/Business/WebSocketBusinessServer.php b/src/Components/workerman-gateway/src/Workerman/Server/Business/WebSocketBusinessServer.php index 526457b497..ab77c5de5c 100644 --- a/src/Components/workerman-gateway/src/Workerman/Server/Business/WebSocketBusinessServer.php +++ b/src/Components/workerman-gateway/src/Workerman/Server/Business/WebSocketBusinessServer.php @@ -50,7 +50,7 @@ protected function bindEvents(): void public function __construct(string $name, array $config) { parent::__construct($name, $config); - Event::one('IMI.WORKERMAN.SERVER.WORKER_START', function () { + Event::one('IMI.WORKERMAN.SERVER.WORKER_START', function (): void { $this->bindBusinessEvents(); }); } @@ -70,7 +70,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnConnect'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId) { + $property->setValue($worker, function (string $clientId): void { RequestContext::muiltiSet([ 'server' => $this, 'clientId' => $clientId, @@ -88,7 +88,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnWebSocketConnect'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId, array $data) { + $property->setValue($worker, function (string $clientId, array $data): void { try { $request = new WorkermanRequest($this->worker, $clientId, $data); @@ -117,7 +117,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnClose'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId) { + $property->setValue($worker, function (string $clientId): void { RequestContext::muiltiSet([ 'server' => $this, 'clientId' => $clientId, @@ -131,7 +131,7 @@ protected function bindBusinessEvents(): void $property = $refClass->getProperty('_eventOnMessage'); $property->setAccessible(true); - $property->setValue($worker, function (string $clientId, $data) { + $property->setValue($worker, function (string $clientId, $data): void { try { RequestContext::muiltiSet([ diff --git a/src/Components/workerman-gateway/src/Workerman/Server/Gateway/GatewayServer.php b/src/Components/workerman-gateway/src/Workerman/Server/Gateway/GatewayServer.php index d94e765ef0..8a3cc21eea 100644 --- a/src/Components/workerman-gateway/src/Workerman/Server/Gateway/GatewayServer.php +++ b/src/Components/workerman-gateway/src/Workerman/Server/Gateway/GatewayServer.php @@ -43,7 +43,7 @@ public function __construct(string $name, array $config) protected function bindEvents(): void { parent::bindEvents(); - $this->worker->onConnect = function (ConnectionInterface $connection) { + $this->worker->onConnect = function (ConnectionInterface $connection): void { try { // @phpstan-ignore-next-line diff --git a/src/Components/workerman-gateway/tests/bootstrap.php b/src/Components/workerman-gateway/tests/bootstrap.php index f88c43a820..d0b63093eb 100644 --- a/src/Components/workerman-gateway/tests/bootstrap.php +++ b/src/Components/workerman-gateway/tests/bootstrap.php @@ -120,7 +120,7 @@ function checkPort13002(): bool if ('/' === \DIRECTORY_SEPARATOR) { - register_shutdown_function(static function () { + register_shutdown_function(static function (): void { echo 'Stoping WorkermanServers...', \PHP_EOL; if ('Darwin' === \PHP_OS) { @@ -154,7 +154,7 @@ function runTestServer(string $name, array $options): void if (isset($options['stop'])) { - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { // stop server $cmd = $options['stop']; if ('\\' === \DIRECTORY_SEPARATOR) @@ -195,6 +195,6 @@ function runTestServer(string $name, array $options): void startServer(); -register_shutdown_function(static function () { +register_shutdown_function(static function (): void { checkPorts([13000, 13002, 13004, 12900]); }); diff --git a/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/ServerUtilTest.php b/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/ServerUtilTest.php index 6a90449895..95019310ae 100644 --- a/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/ServerUtilTest.php +++ b/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/ServerUtilTest.php @@ -15,7 +15,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->httpHost . 'serverUtil/getServer'); $this->assertEquals([ @@ -29,7 +29,7 @@ public function testGetServer(): void public function testSend(): void { $client1 = $client2 = $client3 = null; - $this->go(function () use (&$client1, &$client2, &$client3) { + $this->go(function () use (&$client1, &$client2, &$client3): void { $client1 = new Client($this->host, $this->httpHost); $this->assertTrue($client1->connect()); $client2 = new Client($this->host, $this->httpHost); @@ -132,7 +132,7 @@ public function testSend(): void } } $this->assertEquals(4, $count); - }, static function () use (&$client1, &$client2, &$client3) { + }, static function () use (&$client1, &$client2, &$client3): void { if ($client1) { $client1->disconnect(); @@ -152,7 +152,7 @@ public function testSendToGroup(): void { /** @var Client[] $clients */ $clients = []; - $this->go(function () use (&$clients) { + $this->go(function () use (&$clients): void { for ($i = 0; $i < 2; ++$i) { $clients[] = $client = new Client($this->host, $this->httpHost); @@ -201,7 +201,7 @@ public function testSendToGroup(): void } $this->assertEquals(2, $count); } - }, static function () use (&$clients) { + }, static function () use (&$clients): void { foreach ($clients as $client) { $client->disconnect(); diff --git a/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/WSTest.php b/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/WSTest.php index bbf90b672a..09deba4dcb 100644 --- a/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/WSTest.php +++ b/src/Components/workerman-gateway/tests/unit/AppServer/Tests/WebSocket/Workerman/WSTest.php @@ -17,7 +17,7 @@ class WSTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->host); $this->assertTrue($client->connect()); sleep(1); @@ -61,7 +61,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->host); $this->assertTrue($client->connect()); sleep(1); @@ -77,7 +77,7 @@ public function testNotFound(): void public function testMatchHttpRoute(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->host); $this->assertTrue($client->connect()); sleep(1); diff --git a/src/Components/workerman/bootstrap.php b/src/Components/workerman/bootstrap.php index b622ac0d49..7c0ef8ae24 100644 --- a/src/Components/workerman/bootstrap.php +++ b/src/Components/workerman/bootstrap.php @@ -7,7 +7,7 @@ use Imi\App; use Imi\Event\Event; -return static function () { +return static function (): void { $path = null; if (\defined('IMI_IN_PHAR') && IMI_IN_PHAR) @@ -16,7 +16,7 @@ } elseif (!class_exists(\Imi\App::class)) { - (static function () use (&$path) { + (static function () use (&$path): void { foreach ([ $_SERVER['PWD'] ?? null, getcwd(), diff --git a/src/Components/workerman/src/Cron/Process/CronProcess.php b/src/Components/workerman/src/Cron/Process/CronProcess.php index 2ecca8c480..70a0f70e4d 100644 --- a/src/Components/workerman/src/Cron/Process/CronProcess.php +++ b/src/Components/workerman/src/Cron/Process/CronProcess.php @@ -67,7 +67,7 @@ protected function startSocketServer(): void } $this->unixWorker = $worker = new WorkermanServerWorker('unix://' . $socketFile); $worker->protocol = \Imi\Workerman\Cron\Protocol\Frame::class; - $worker->onMessage = [$this, 'onUnixMessage']; + $worker->onMessage = $this->onUnixMessage(...); $worker->listen(); $this->startSchedule(); } @@ -102,7 +102,7 @@ public function onUnixMessage(ConnectionInterface $connection, $data): void */ protected function startSchedule(): void { - Timer::tick(1000, function () { + Timer::tick(1000, function (): void { $scheduler = $this->scheduler; foreach ($scheduler->schedule() as $task) { diff --git a/src/Components/workerman/src/HotUpdate/HotUpdateProcess.php b/src/Components/workerman/src/HotUpdate/HotUpdateProcess.php index 5860cc848e..de881dc54f 100644 --- a/src/Components/workerman/src/HotUpdate/HotUpdateProcess.php +++ b/src/Components/workerman/src/HotUpdate/HotUpdateProcess.php @@ -252,7 +252,7 @@ private function beginBuildRuntime(array $changedFiles): void */ private function closeBuildRuntime(): void { - $closePipes = static function (?array $buildRuntimePipes) { + $closePipes = static function (?array $buildRuntimePipes): void { if (null !== $buildRuntimePipes) { foreach ($buildRuntimePipes as $pipe) diff --git a/src/Components/workerman/src/Http/Message/WorkermanEmitHandler.php b/src/Components/workerman/src/Http/Message/WorkermanEmitHandler.php index edc88fca9b..55eb1005db 100644 --- a/src/Components/workerman/src/Http/Message/WorkermanEmitHandler.php +++ b/src/Components/workerman/src/Http/Message/WorkermanEmitHandler.php @@ -9,11 +9,8 @@ class WorkermanEmitHandler implements IEmitHandler { - private TcpConnection $connection; - - public function __construct(TcpConnection $connection) + public function __construct(private readonly TcpConnection $connection) { - $this->connection = $connection; } public function send(string $data): bool diff --git a/src/Components/workerman/src/Http/Message/WorkermanRequest.php b/src/Components/workerman/src/Http/Message/WorkermanRequest.php index e8f8f3f5fe..9a4660ddc6 100644 --- a/src/Components/workerman/src/Http/Message/WorkermanRequest.php +++ b/src/Components/workerman/src/Http/Message/WorkermanRequest.php @@ -13,29 +13,21 @@ class WorkermanRequest extends Request { - /** - * Workerman 的 http 请求对象 - */ - protected ?\Workerman\Protocols\Http\Request $workermanRequest = null; - - /** - * Workerman 的 Worker 对象 - */ - protected ?Worker $worker = null; - - /** - * 协议. - */ - protected string $scheme = ''; - - protected ?TcpConnection $connection = null; - - public function __construct(Worker $worker, TcpConnection $connection, \Workerman\Protocols\Http\Request $request, string $scheme = 'http') - { - $this->workermanRequest = $request; - $this->worker = $worker; - $this->connection = $connection; - $this->scheme = $scheme; + public function __construct( + /** + * Workerman 的 Worker 对象 + */ + protected ?Worker $worker, + protected ?TcpConnection $connection, + /** + * Workerman 的 http 请求对象 + */ + protected ?\Workerman\Protocols\Http\Request $workermanRequest, + /** + * 协议. + */ + protected string $scheme = 'http' + ) { } /** diff --git a/src/Components/workerman/src/Http/Message/WorkermanResponse.php b/src/Components/workerman/src/Http/Message/WorkermanResponse.php index e4e733dbaf..883c9953aa 100644 --- a/src/Components/workerman/src/Http/Message/WorkermanResponse.php +++ b/src/Components/workerman/src/Http/Message/WorkermanResponse.php @@ -13,26 +13,6 @@ class WorkermanResponse extends Response { - /** - * Workerman 的 http 响应对象 - */ - protected ?\Workerman\Protocols\Http\Response $workermanResponse = null; - - /** - * Workerman 的 http 请求对象 - */ - protected ?WorkermanRequest $request = null; - - /** - * Workerman 的 Worker 对象 - */ - protected ?Worker $worker = null; - - /** - * Workerman 连接对象 - */ - protected ?TcpConnection $connection = null; - /** * 响应头是否可写. */ @@ -45,12 +25,24 @@ class WorkermanResponse extends Response protected bool $emitterWritting = false; - public function __construct(Worker $worker, TcpConnection $connection, ?\Workerman\Protocols\Http\Response $response = null, ?WorkermanRequest $request = null) + public function __construct( + /** + * Workerman 的 Worker 对象 + */ + protected ?Worker $worker, + /** + * Workerman 连接对象 + */ + protected ?TcpConnection $connection, + /** + * Workerman 的 http 响应对象 + */ + protected ?\Workerman\Protocols\Http\Response $workermanResponse = null, + /** + * Workerman 的 http 请求对象 + */ + protected ?WorkermanRequest $request = null) { - $this->workermanResponse = $response; - $this->worker = $worker; - $this->connection = $connection; - $this->request = $request; parent::__construct(); } diff --git a/src/Components/workerman/src/Process/BaseProcess.php b/src/Components/workerman/src/Process/BaseProcess.php index 8a07d47461..52ba70314f 100644 --- a/src/Components/workerman/src/Process/BaseProcess.php +++ b/src/Components/workerman/src/Process/BaseProcess.php @@ -8,14 +8,12 @@ abstract class BaseProcess implements IProcess { - /** - * 数据. - */ - protected array $data = []; - - public function __construct(array $data = []) + public function __construct( + /** + * 数据. + */ + protected array $data = []) { - $this->data = $data; if ($data) { foreach ($data as $k => $v) diff --git a/src/Components/workerman/src/Process/ProcessManager.php b/src/Components/workerman/src/Process/ProcessManager.php index 7c31a178f7..a3cfe17599 100644 --- a/src/Components/workerman/src/Process/ProcessManager.php +++ b/src/Components/workerman/src/Process/ProcessManager.php @@ -85,7 +85,7 @@ public static function newProcess(string $name, array $args = [], ?string $alias self::$processes[$processName] = $worker = new WorkermanServerWorker(); $worker->name = $processName; $worker->reloadable = false; - $worker->onWorkerStart = static function (Worker $worker) use ($args, $processName, $options) { + $worker->onWorkerStart = static function (Worker $worker) use ($args, $processName, $options): void { // 随机数播种 mt_srand(); Imi::loadRuntimeInfo(Imi::getCurrentModeRuntimePath('runtime')); @@ -125,7 +125,7 @@ public static function newProcess(string $name, array $args = [], ?string $alias { Client::connect($channel['host'] ?: '127.0.0.1', $channel['port'] ?: 2206); // 监听进程通讯 - $callback = static function (array $data) { + $callback = static function (array $data): void { $action = $data['action'] ?? null; if (!$action) { diff --git a/src/Components/workerman/src/Server/Base.php b/src/Components/workerman/src/Server/Base.php index 128e2aaadb..9dc342047f 100644 --- a/src/Components/workerman/src/Server/Base.php +++ b/src/Components/workerman/src/Server/Base.php @@ -133,7 +133,7 @@ public function reload(): void */ protected function bindEvents(): void { - $this->worker->onBufferDrain = function (ConnectionInterface $connection) { + $this->worker->onBufferDrain = function (ConnectionInterface $connection): void { try { // @phpstan-ignore-next-line @@ -155,7 +155,7 @@ protected function bindEvents(): void } }; - $this->worker->onBufferFull = function (ConnectionInterface $connection) { + $this->worker->onBufferFull = function (ConnectionInterface $connection): void { try { // @phpstan-ignore-next-line @@ -177,7 +177,7 @@ protected function bindEvents(): void } }; - $this->worker->onClose = function (ConnectionInterface $connection) { + $this->worker->onClose = function (ConnectionInterface $connection): void { try { // @phpstan-ignore-next-line @@ -199,7 +199,7 @@ protected function bindEvents(): void } }; - $this->worker->onConnect = function (ConnectionInterface $connection) { + $this->worker->onConnect = function (ConnectionInterface $connection): void { try { // @phpstan-ignore-next-line @@ -222,7 +222,7 @@ protected function bindEvents(): void } }; - $this->worker->onError = function (ConnectionInterface $connection, int $code, string $msg) { + $this->worker->onError = function (ConnectionInterface $connection, int $code, string $msg): void { try { // @phpstan-ignore-next-line @@ -246,7 +246,7 @@ protected function bindEvents(): void } }; - $this->worker->onWorkerReload = function (Worker $worker) { + $this->worker->onWorkerReload = function (Worker $worker): void { try { RequestContext::muiltiSet([ @@ -265,7 +265,7 @@ protected function bindEvents(): void } }; - $this->worker->onWorkerStart = function (Worker $worker) { + $this->worker->onWorkerStart = function (Worker $worker): void { try { // 随机数播种 @@ -321,7 +321,7 @@ protected function bindEvents(): void { Client::connect($channel['host'] ?: '127.0.0.1', $channel['port'] ?: 2206); // 监听进程通讯 - $callback = static function (array $data) { + $callback = static function (array $data): void { $action = $data['action'] ?? null; if (!$action) { @@ -376,7 +376,7 @@ protected function bindEvents(): void } }; - $this->worker->onWorkerStop = function (Worker $worker) { + $this->worker->onWorkerStop = function (Worker $worker): void { try { RequestContext::muiltiSet([ diff --git a/src/Components/workerman/src/Server/Cli/Server.php b/src/Components/workerman/src/Server/Cli/Server.php index 4db2ea9a2f..4864cf4f65 100644 --- a/src/Components/workerman/src/Server/Cli/Server.php +++ b/src/Components/workerman/src/Server/Cli/Server.php @@ -39,7 +39,7 @@ class Server extends BaseCommand */ public function start(?string $name, ?int $workerNum, bool $d = false): void { - (function () use ($name, $workerNum, $d) { + (function () use ($name, $workerNum, $d): void { $this->outStartupInfo(); if (Config::get('@app.server.checkPoolResource', false) && !PoolManager::checkPoolResource()) { diff --git a/src/Components/workerman/src/Server/Http/Server.php b/src/Components/workerman/src/Server/Http/Server.php index c89a8626b7..0ee0d67398 100644 --- a/src/Components/workerman/src/Server/Http/Server.php +++ b/src/Components/workerman/src/Server/Http/Server.php @@ -60,7 +60,7 @@ protected function bindEvents(): void Event::on('IMI.WORKERMAN.SERVER.HTTP.REQUEST', [new BeforeRequest(), 'handle'], ImiPriority::IMI_MAX); App::set('has_imi_workerman_http_request_event', true); } - $this->worker->onMessage = function (ConnectionInterface $connection, $data) { + $this->worker->onMessage = function (ConnectionInterface $connection, $data): void { try { $worker = $this->worker; diff --git a/src/Components/workerman/src/Server/Tcp/Server.php b/src/Components/workerman/src/Server/Tcp/Server.php index 34f0b03d9d..627e0a391f 100644 --- a/src/Components/workerman/src/Server/Tcp/Server.php +++ b/src/Components/workerman/src/Server/Tcp/Server.php @@ -41,7 +41,7 @@ protected function bindEvents(): void { parent::bindEvents(); - $this->worker->onMessage = function (TcpConnection $connection, string $data) { + $this->worker->onMessage = function (TcpConnection $connection, string $data): void { try { $clientId = $connection->id; diff --git a/src/Components/workerman/src/Server/Udp/Server.php b/src/Components/workerman/src/Server/Udp/Server.php index 781bc5b6f3..be198aad94 100644 --- a/src/Components/workerman/src/Server/Udp/Server.php +++ b/src/Components/workerman/src/Server/Udp/Server.php @@ -42,7 +42,7 @@ protected function bindEvents(): void { parent::bindEvents(); - $this->worker->onMessage = function (UdpConnection $connection, string $data) { + $this->worker->onMessage = function (UdpConnection $connection, string $data): void { try { $requestContext = RequestContext::getContext(); diff --git a/src/Components/workerman/src/Server/WebSocket/Server.php b/src/Components/workerman/src/Server/WebSocket/Server.php index 780bb897b1..2afabbb890 100644 --- a/src/Components/workerman/src/Server/WebSocket/Server.php +++ b/src/Components/workerman/src/Server/WebSocket/Server.php @@ -121,7 +121,7 @@ protected function bindEvents(): void } }; - $this->worker->onMessage = function (TcpConnection $connection, string $data) { + $this->worker->onMessage = function (TcpConnection $connection, string $data): void { try { $clientId = $connection->id; diff --git a/src/Components/workerman/src/Server/WorkermanServerWorker.php b/src/Components/workerman/src/Server/WorkermanServerWorker.php index 70daccab08..6d58203a78 100644 --- a/src/Components/workerman/src/Server/WorkermanServerWorker.php +++ b/src/Components/workerman/src/Server/WorkermanServerWorker.php @@ -35,7 +35,7 @@ public static function getMasterPid(): int /** * {@inheritDoc} */ - protected static function init() + protected static function init(): void { parent::init(); static::$_startFile = Imi::getCurrentModeRuntimePath('start_file'); @@ -113,7 +113,7 @@ public static function clearAll(): void /** * {@inheritDoc} */ - protected static function displayUI() + protected static function displayUI(): void { // BUG: https://github.com/walkor/workerman/pull/708 // 此处为修复低版本 bug diff --git a/src/Components/workerman/src/Util/Imi.php b/src/Components/workerman/src/Util/Imi.php index 821e90153e..176a874f59 100644 --- a/src/Components/workerman/src/Util/Imi.php +++ b/src/Components/workerman/src/Util/Imi.php @@ -63,7 +63,7 @@ public static function getProcessName(string $type, array $data = []): string { continue; } - $result = str_replace('{' . $k . '}', (string) $v, $result); + $result = str_replace('{' . $k . '}', (string) $v, (string) $result); } return $result; diff --git a/src/Components/workerman/src/WorkermanApp.php b/src/Components/workerman/src/WorkermanApp.php index 50fd8f907c..661c8971ee 100644 --- a/src/Components/workerman/src/WorkermanApp.php +++ b/src/Components/workerman/src/WorkermanApp.php @@ -38,10 +38,10 @@ class WorkermanApp extends CliApp public function __construct(string $namespace) { parent::__construct($namespace); - $this->cliEventDispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $e) { + $this->cliEventDispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $e): void { $this->onCommand($e); }, \PHP_INT_MAX - 1000); - Event::one('IMI.SCAN_APP', function () { + Event::one('IMI.SCAN_APP', function (): void { $this->onScanApp(); }); } diff --git a/src/Components/workerman/tests/bootstrap.php b/src/Components/workerman/tests/bootstrap.php index a813316305..cad5cf6dc9 100644 --- a/src/Components/workerman/tests/bootstrap.php +++ b/src/Components/workerman/tests/bootstrap.php @@ -92,7 +92,7 @@ function checkChannelServerUtilServerStatus(): bool echo "Starting {$name}...", \PHP_EOL; shell_exec("{$cmd}"); - register_shutdown_function(static function () use ($name, $options) { + register_shutdown_function(static function () use ($name, $options): void { // stop server $cmd = $options['stop']; if ('\\' === \DIRECTORY_SEPARATOR) @@ -117,6 +117,6 @@ function checkChannelServerUtilServerStatus(): bool startServer(); -register_shutdown_function(static function () { +register_shutdown_function(static function (): void { checkPorts([13000, 13002, 13003, 13004, 13005, 13006, 13007]); }); diff --git a/src/Components/workerman/tests/unit/AppServer/Tests/Tcp/TCPTest.php b/src/Components/workerman/tests/unit/AppServer/Tests/Tcp/TCPTest.php index c3273c5a8b..2266ffcf09 100644 --- a/src/Components/workerman/tests/unit/AppServer/Tests/Tcp/TCPTest.php +++ b/src/Components/workerman/tests/unit/AppServer/Tests/Tcp/TCPTest.php @@ -14,7 +14,7 @@ class TCPTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $fp = stream_socket_client($this->host); $this->assertIsResource($fp); $name = 'imitest'; @@ -41,7 +41,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $fp = stream_socket_client($this->host); $this->assertIsResource($fp); $sendContent = json_encode([ diff --git a/src/Components/workerman/tests/unit/AppServer/Tests/Udp/UDPTest.php b/src/Components/workerman/tests/unit/AppServer/Tests/Udp/UDPTest.php index 2a1035ca05..b329b610d7 100644 --- a/src/Components/workerman/tests/unit/AppServer/Tests/Udp/UDPTest.php +++ b/src/Components/workerman/tests/unit/AppServer/Tests/Udp/UDPTest.php @@ -14,7 +14,7 @@ class UDPTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $fp = stream_socket_client($this->host); $this->assertIsResource($fp); stream_set_timeout($fp, 3); @@ -34,7 +34,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $fp = stream_socket_client($this->host); $this->assertIsResource($fp); stream_set_timeout($fp, 3); diff --git a/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/ServerUtilTest.php b/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/ServerUtilTest.php index ef7ccf6102..3d363b1cff 100644 --- a/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/ServerUtilTest.php +++ b/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/ServerUtilTest.php @@ -14,7 +14,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->httpHost . 'serverUtil/getServer'); $this->assertEquals([ @@ -28,7 +28,7 @@ public function testGetServer(): void public function testSend(): void { $client1 = $client2 = $client3 = null; - $this->go(function () use (&$client1, &$client2, &$client3) { + $this->go(function () use (&$client1, &$client2, &$client3): void { $client1 = new Client($this->host, $this->httpHost); $this->assertTrue($client1->connect()); $this->assertTrue($client1->sendData(json_encode([ @@ -130,7 +130,7 @@ public function testSend(): void } } $this->assertEquals(4, $count); - }, static function () use (&$client1, &$client2, &$client3) { + }, static function () use (&$client1, &$client2, &$client3): void { if ($client1) { $client1->disconnect(); @@ -150,7 +150,7 @@ public function testSendToGroup(): void { /** @var Client[] $clients */ $clients = []; - $this->go(function () use (&$clients) { + $this->go(function () use (&$clients): void { for ($i = 0; $i < 2; ++$i) { $clients[] = $client = new Client($this->host, $this->httpHost); @@ -193,7 +193,7 @@ public function testSendToGroup(): void } $this->assertEquals(2, $count); } - }, static function () use (&$clients) { + }, static function () use (&$clients): void { foreach ($clients as $client) { $client->disconnect(); diff --git a/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/WSTest.php b/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/WSTest.php index d8af29fa00..10c90d88ee 100644 --- a/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/WSTest.php +++ b/src/Components/workerman/tests/unit/AppServer/Tests/WebSocket/WSTest.php @@ -16,7 +16,7 @@ class WSTest extends BaseTest */ public function test(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->httpHost); $this->assertTrue($client->connect()); $this->assertTrue($client->sendData(json_encode([ @@ -97,7 +97,7 @@ public function test(): void public function testNotFound(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->httpHost); $this->assertTrue($client->connect()); $this->assertTrue($client->sendData(json_encode([ @@ -112,7 +112,7 @@ public function testNotFound(): void public function testMatchHttpRoute(): void { - $this->go(function () { + $this->go(function (): void { $client = new Client($this->host, $this->httpHost); $this->assertTrue($client->connect()); $this->assertTrue($client->sendData(json_encode([ diff --git a/src/Components/workerman/tests/unit/ChannelServerUtilServer/Tests/WebSocket/ServerUtilTest.php b/src/Components/workerman/tests/unit/ChannelServerUtilServer/Tests/WebSocket/ServerUtilTest.php index 244aca91b7..a1f58d783c 100644 --- a/src/Components/workerman/tests/unit/ChannelServerUtilServer/Tests/WebSocket/ServerUtilTest.php +++ b/src/Components/workerman/tests/unit/ChannelServerUtilServer/Tests/WebSocket/ServerUtilTest.php @@ -14,7 +14,7 @@ class ServerUtilTest extends BaseTest { public function testGetServer(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->httpHost . 'serverUtil/getServer'); $this->assertEquals([ @@ -27,7 +27,7 @@ public function testGetServer(): void public function testSendMessage(): void { - $this->go(function () { + $this->go(function (): void { $http = new HttpRequest(); $response = $http->get($this->httpHost . 'serverUtil/sendMessage'); $all = 'Linux' === \PHP_OS ? 2 : 1; @@ -45,7 +45,7 @@ public function testSendMessage(): void public function testSend(): void { $client1 = $client2 = $client3 = null; - $this->go(function () use (&$client1, &$client2, &$client3) { + $this->go(function () use (&$client1, &$client2, &$client3): void { $client1 = new Client($this->host, $this->httpHost); $this->assertTrue($client1->connect()); @@ -141,7 +141,7 @@ public function testSend(): void } } $this->assertEquals(4, $count); - }, static function () use (&$client1, &$client2, &$client3) { + }, static function () use (&$client1, &$client2, &$client3): void { if ($client1) { $client1->disconnect(); @@ -161,7 +161,7 @@ public function testSendToGroup(): void { /** @var Client[] $clients */ $clients = []; - $this->go(function () use (&$clients) { + $this->go(function () use (&$clients): void { for ($i = 0; $i < 2; ++$i) { $clients[] = $client = new Client($this->host, $this->httpHost); @@ -210,7 +210,7 @@ public function testSendToGroup(): void } $this->assertEquals(2, $count); } - }, static function () use (&$clients) { + }, static function () use (&$clients): void { foreach ($clients as $client) { $client->disconnect(); diff --git a/src/Config/DotEnv/Parser.php b/src/Config/DotEnv/Parser.php index 73a90922fd..0ca5912ddf 100644 --- a/src/Config/DotEnv/Parser.php +++ b/src/Config/DotEnv/Parser.php @@ -23,7 +23,7 @@ final class Parser implements ParserInterface */ public function parse(string $content) { - return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static fn () => 'Could not split into separate lines.')->flatMap(static fn (array $lines) => self::process(Lines::process($lines)))->mapError(static function (string $error) { + return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static fn () => 'Could not split into separate lines.')->flatMap(static fn (array $lines) => self::process(Lines::process($lines)))->mapError(static function (string $error): never { throw new InvalidFileException(sprintf('Failed to parse dotenv file. %s', $error)); })->success()->get(); } diff --git a/src/ConnectionContext.php b/src/ConnectionContext.php index 3fec743a3d..a7dfe6aee9 100644 --- a/src/ConnectionContext.php +++ b/src/ConnectionContext.php @@ -153,7 +153,7 @@ public static function set(?string $name, $value, $clientId = null, ?string $ser } $store = self::getConnectionContextStore($serverName); $clientIdStr = (string) $clientId; - $result = $store->lock($clientIdStr, static function () use ($store, $name, $value, $clientIdStr) { + $result = $store->lock($clientIdStr, static function () use ($store, $name, $value, $clientIdStr): void { $data = $store->read($clientIdStr); $data[$name] = $value; $store->save($clientIdStr, $data); @@ -181,7 +181,7 @@ public static function muiltiSet(array $data, $clientId = null, ?string $serverN } $store = self::getConnectionContextStore($serverName); $clientIdStr = (string) $clientId; - $result = $store->lock($clientIdStr, static function () use ($store, $data, $clientIdStr) { + $result = $store->lock($clientIdStr, static function () use ($store, $data, $clientIdStr): void { $storeData = $store->read($clientIdStr); foreach ($data as $name => $value) { @@ -213,7 +213,7 @@ public static function use(callable $callable, $clientId = null, ?string $server /** @var \Imi\Server\ConnectionContext\StoreHandler $store */ $store = self::getConnectionContextStore($serverName); $clientIdStr = (string) $clientId; - $store->lock($clientIdStr, static function () use ($callable, $store, $clientIdStr) { + $store->lock($clientIdStr, static function () use ($callable, $store, $clientIdStr): void { $data = $store->read($clientIdStr); $result = $callable($data); if ($result) diff --git a/src/Core/App/Contract/BaseApp.php b/src/Core/App/Contract/BaseApp.php index 0ac9bee391..adb4211fdc 100644 --- a/src/Core/App/Contract/BaseApp.php +++ b/src/Core/App/Contract/BaseApp.php @@ -18,11 +18,6 @@ abstract class BaseApp implements IApp { - /** - * 命名空间. - */ - protected string $namespace = ''; - /** * 应用模式的配置. */ @@ -31,15 +26,18 @@ abstract class BaseApp implements IApp /** * 构造方法. */ - public function __construct(string $namespace) - { - $this->namespace = $namespace; + public function __construct( + /** + * 命名空间. + */ + protected string $namespace + ) { } protected function __loadConfig(): void { // 加载框架配置 - Config::addConfig('@imi', include \dirname(IMI_PATH) . '/config/config.php'); + Config::addConfig('@imi', include \dirname((string) IMI_PATH) . '/config/config.php'); $appPath = App::get(AppContexts::APP_PATH_PHYSICS); // @phpstan-ignore-next-line diff --git a/src/Core/Context/DefaultContextManager.php b/src/Core/Context/DefaultContextManager.php index f789ad755a..059202a18d 100644 --- a/src/Core/Context/DefaultContextManager.php +++ b/src/Core/Context/DefaultContextManager.php @@ -96,7 +96,7 @@ public function getCurrentFlag(): string protected function bindAutoDestroy(): void { - register_shutdown_function(function () { + register_shutdown_function(function (): void { if ($this->contexts) { foreach ($this->contexts as $flag => $_) diff --git a/src/Cron/Client.php b/src/Cron/Client.php index dc28cec449..2cfb419651 100644 --- a/src/Cron/Client.php +++ b/src/Cron/Client.php @@ -9,11 +9,6 @@ class Client { - /** - * 配置项. - */ - private array $options = []; - /** * socket 文件路径. * @@ -36,9 +31,12 @@ class Client /** * 构造方法. */ - public function __construct(array $options = []) + public function __construct( + /** + * 配置项. + */ + private readonly array $options = []) { - $this->options = $options; if (!isset($options['socketFile'])) { throw new \InvalidArgumentException('You must set the "socketFile" option'); diff --git a/src/Cron/CronManager.php b/src/Cron/CronManager.php index 2342a5e263..6fe42cbe5e 100644 --- a/src/Cron/CronManager.php +++ b/src/Cron/CronManager.php @@ -177,7 +177,7 @@ public function getTaskCallable(string $cronId, string $class, ?string &$cronTyp switch ($cronType) { case CronTaskType::CRON_PROCESS: - return static function (string $id, $data) use ($class) { + return static function (string $id, $data) use ($class): void { /** @var \Imi\Cron\Contract\ICronTask $handler */ $handler = App::getBean($class); $handler->run($id, $data); diff --git a/src/Cron/CronTask.php b/src/Cron/CronTask.php index cf4e69f6d5..691b4e8d08 100644 --- a/src/Cron/CronTask.php +++ b/src/Cron/CronTask.php @@ -9,18 +9,6 @@ */ class CronTask { - /** - * 任务唯一ID. - */ - private string $id = ''; - - /** - * 任务类型. - * - * \Imi\Cron\Consts\CronTaskType 类常量 - */ - private string $type = ''; - /** * 任务执行回调,可以是callable类型,也可以是 task、process 名. * @@ -35,70 +23,62 @@ class CronTask */ private array $cronRules = []; - /** - * 数据. - * - * @var mixed - */ - private $data; - - /** - * 定时任务唯一性设置 - * 当前实例唯一: current - * 所有实例唯一: all - * 不唯一: null. - */ - private ?string $unique = null; - - /** - * 用于锁的 `Redis` 连接池名. - */ - private ?string $redisPool = null; - - /** - * 获取锁超时时间,单位:秒. - */ - private float $lockWaitTimeout = 0; - - /** - * 最大运行执行时间,单位:秒。该值与分布式锁超时时间共享. - */ - private float $maxExecutionTime = 0; - /** * 获取上一次运行时间. */ private int $lastRunTime = -1; - /** - * 每次启动服务强制执行. - */ - private bool $force = false; - - /** - * 是否记录成功日志. - */ - private bool $successLog = true; - /** * 构造方法. * * @param callable|string $task * @param mixed $data */ - public function __construct(string $id, string $type, $task, array $cronRules, $data, float $maxExecutionTime = 3, ?string $unique = null, ?string $redisPool = null, float $lockWaitTimeout = 3, bool $force = false, bool $successLog = true) + public function __construct( + /** + * 任务唯一ID. + */ + private readonly string $id, + /** + * 任务类型. + * + * \Imi\Cron\Consts\CronTaskType 类常量 + */ + private readonly string $type, $task, array $cronRules, + /** + * 数据. + */ + private $data, + /** + * 最大运行执行时间,单位:秒。该值与分布式锁超时时间共享. + */ + private readonly float $maxExecutionTime = 3, + /** + * 定时任务唯一性设置 + * 当前实例唯一: current + * 所有实例唯一: all + * 不唯一: null. + */ + private readonly ?string $unique = null, + /** + * 用于锁的 `Redis` 连接池名. + */ + private readonly ?string $redisPool = null, + /** + * 获取锁超时时间,单位:秒. + */ + private readonly float $lockWaitTimeout = 3, + /** + * 每次启动服务强制执行. + */ + private readonly bool $force = false, + /** + * 是否记录成功日志. + */ + private readonly bool $successLog = true) { - $this->id = $id; - $this->type = $type; $this->task = $task; $this->cronRules = $this->parseCronRule($cronRules); - $this->data = $data; - $this->unique = $unique; - $this->redisPool = $redisPool; - $this->lockWaitTimeout = $lockWaitTimeout; - $this->maxExecutionTime = $maxExecutionTime; - $this->force = $force; - $this->successLog = $successLog; } /** diff --git a/src/Cron/Message/CommonMsg.php b/src/Cron/Message/CommonMsg.php index d5f5e11861..21387c440c 100644 --- a/src/Cron/Message/CommonMsg.php +++ b/src/Cron/Message/CommonMsg.php @@ -6,21 +6,17 @@ class CommonMsg implements IMessage { - /** - * 从socket获取的返回信息. - * - * @var mixed - */ - protected $response = []; - /** * 初始化. * * @param mixed $response */ - public function __construct($response = []) - { - $this->response = $response; + public function __construct( + /** + * 从socket获取的返回信息. + */ + protected $response = [] + ) { } /** diff --git a/src/Cron/Message/Result.php b/src/Cron/Message/Result.php index d9460e5af9..363cd8ba68 100644 --- a/src/Cron/Message/Result.php +++ b/src/Cron/Message/Result.php @@ -11,16 +11,6 @@ class Result implements IMessage { - /** - * 动作. - */ - public string $action = ''; - - /** - * 定时任务ID. - */ - public string $id = ''; - /** * 进程类型. */ @@ -31,34 +21,30 @@ class Result implements IMessage */ public ?string $processId = null; - /** - * 是否成功 - */ - public bool $success = false; - - /** - * 消息. - */ - public string $message = ''; - - public function __construct(string $action, string $id, bool $success, string $message) + public function __construct( + /** + * 动作. + */ + public string $action, + /** + * 定时任务ID. + */ + public string $id, + /** + * 是否成功 + */ + public bool $success, + /** + * 消息. + */ + public string $message) { - $this->action = $action; - $this->id = $id; - $this->success = $success; - $this->message = $message; $this->processType = App::get(ProcessAppContexts::PROCESS_TYPE); - switch ($this->processType) + $this->processId = match ($this->processType) { - case ProcessType::WORKER: - case ProcessType::TASK_WORKER: - $this->processId = (string) Worker::getWorkerId(); - break; - case ProcessType::PROCESS: - $this->processId = App::get(ProcessAppContexts::PROCESS_NAME) . '#' . Worker::getWorkerId(); - break; - default: - throw new \InvalidArgumentException(sprintf('Invalid process type %s', $this->processType)); - } + ProcessType::WORKER, ProcessType::TASK_WORKER => (string) Worker::getWorkerId(), + ProcessType::PROCESS => App::get(ProcessAppContexts::PROCESS_NAME) . '#' . Worker::getWorkerId(), + default => throw new \InvalidArgumentException(sprintf('Invalid process type %s', $this->processType)), + }; } } diff --git a/src/Db/Db.php b/src/Db/Db.php index 126aaa0cf9..8a1d9b0cdf 100644 --- a/src/Db/Db.php +++ b/src/Db/Db.php @@ -102,7 +102,7 @@ public static function getInstance(?string $poolName = null, int $queryType = Qu App::set($requestContextKey, $db); if (($heartbeatInterval = $config['heartbeatInterval'] ?? 0) > 0) { - Timer::tick((int) ($heartbeatInterval * 1000), static function () use ($requestContextKey) { + Timer::tick((int) ($heartbeatInterval * 1000), static function () use ($requestContextKey): void { /** @var IDb|null $db */ $db = App::get($requestContextKey); if (!$db) diff --git a/src/Db/Drivers/Base.php b/src/Db/Drivers/Base.php index 57983cfddc..099d01640f 100644 --- a/src/Db/Drivers/Base.php +++ b/src/Db/Drivers/Base.php @@ -11,14 +11,12 @@ abstract class Base implements IDb { use THashCode; - /** - * 连接配置. - */ - protected array $option = []; - - public function __construct(array $option = []) - { - $this->option = $option; + public function __construct( + /** + * 连接配置. + */ + protected array $option = [] + ) { } /** diff --git a/src/Db/Mysql/Drivers/Mysqli/Statement.php b/src/Db/Mysql/Drivers/Mysqli/Statement.php index 14985a132a..70fcf1dc4b 100644 --- a/src/Db/Mysql/Drivers/Mysqli/Statement.php +++ b/src/Db/Mysql/Drivers/Mysqli/Statement.php @@ -16,8 +16,6 @@ */ class Statement extends MysqlBaseStatement implements IMysqlStatement { - protected ?\mysqli_stmt $statement = null; - /** * @var \mysqli_result|false */ @@ -28,33 +26,26 @@ class Statement extends MysqlBaseStatement implements IMysqlStatement */ protected array $data = []; - /** - * 数据库操作对象 - */ - protected ?IMysqlDb $db = null; - - /** - * 最后执行过的SQL语句. - */ - protected string $lastSql = ''; - /** * 绑定数据. */ protected array $bindValues = []; - /** - * SQL 参数映射. - */ - protected ?array $sqlParamsMap = null; - - public function __construct(IMysqlDb $db, ?\mysqli_stmt $statement, ?\mysqli_result $result, string $originSql, ?array $sqlParamsMap = null) + public function __construct( + /** + * 数据库操作对象 + */ + protected ?IMysqlDb $db, protected ?\mysqli_stmt $statement, ?\mysqli_result $result, + /** + * 最后执行过的SQL语句. + */ + protected string $lastSql, + /** + * SQL 参数映射. + */ + protected ?array $sqlParamsMap = null) { - $this->db = $db; - $this->statement = $statement; $this->result = $result; - $this->lastSql = $originSql; - $this->sqlParamsMap = $sqlParamsMap; } /** @@ -200,19 +191,15 @@ public function execute(array $inputParameters = null): bool public function fetch(int $fetchStyle = \PDO::FETCH_ASSOC, int $cursorOrientation = \PDO::FETCH_ORI_NEXT, int $cursorOffset = 0) { $result = $this->result; - switch ($fetchStyle) + + return match ($fetchStyle) { - case \PDO::FETCH_ASSOC: - return $result->fetch_assoc(); - case \PDO::FETCH_BOTH: - return $result->fetch_array(); - case \PDO::FETCH_NUM: - return $result->fetch_array(\MYSQLI_NUM); - case \PDO::FETCH_OBJ: - return $result->fetch_object(); - default: - throw new DbException(sprintf('Not support fetchStyle %s', $fetchStyle)); - } + \PDO::FETCH_ASSOC => $result->fetch_assoc(), + \PDO::FETCH_BOTH => $result->fetch_array(), + \PDO::FETCH_NUM => $result->fetch_array(\MYSQLI_NUM), + \PDO::FETCH_OBJ => $result->fetch_object(), + default => throw new DbException(sprintf('Not support fetchStyle %s', $fetchStyle)), + }; } /** diff --git a/src/Db/Mysql/Drivers/PdoMysql/Driver.php b/src/Db/Mysql/Drivers/PdoMysql/Driver.php index 3ae057ca4f..4eb9fdca4a 100644 --- a/src/Db/Mysql/Drivers/PdoMysql/Driver.php +++ b/src/Db/Mysql/Drivers/PdoMysql/Driver.php @@ -33,12 +33,8 @@ public function __construct(array $option = []) protected function buildDSN(): string { $option = $this->option; - if (isset($option['dsn'])) - { - return $option['dsn']; - } - return 'mysql:' + return $option['dsn'] ?? 'mysql:' . 'host=' . ($option['host'] ?? '127.0.0.1') . ';port=' . ($option['port'] ?? '3306') . ';dbname=' . ($option['database'] ?? '') diff --git a/src/Db/Mysql/Query/FullText/MysqlFullTextOptions.php b/src/Db/Mysql/Query/FullText/MysqlFullTextOptions.php index daa0ad9c81..39fe57cf0b 100644 --- a/src/Db/Mysql/Query/FullText/MysqlFullTextOptions.php +++ b/src/Db/Mysql/Query/FullText/MysqlFullTextOptions.php @@ -9,14 +9,12 @@ class MysqlFullTextOptions extends BaseFullTextOptions { - /** - * 搜索修饰符. - */ - protected string $searchModifier = ''; - - public function __construct(string $searchModifier = '') - { - $this->searchModifier = $searchModifier; + public function __construct( + /** + * 搜索修饰符. + */ + protected string $searchModifier = '' + ) { } /** diff --git a/src/Db/Mysql/Query/Pagination/BigTablePagination.php b/src/Db/Mysql/Query/Pagination/BigTablePagination.php index a71867a97b..b6d20a02da 100644 --- a/src/Db/Mysql/Query/Pagination/BigTablePagination.php +++ b/src/Db/Mysql/Query/Pagination/BigTablePagination.php @@ -12,17 +12,8 @@ class BigTablePagination { - protected IQuery $query; - - protected string $idField = ''; - - protected bool $cleanWhere = true; - - public function __construct(IQuery $query, string $idField = 'id', bool $cleanWhere = true) + public function __construct(protected IQuery $query, protected string $idField = 'id', protected bool $cleanWhere = true) { - $this->query = $query; - $this->idField = $idField; - $this->cleanWhere = $cleanWhere; } public function getQuery(): IQuery diff --git a/src/Db/Pool/DbResource.php b/src/Db/Pool/DbResource.php index 93731e2944..87c983a5a8 100644 --- a/src/Db/Pool/DbResource.php +++ b/src/Db/Pool/DbResource.php @@ -13,15 +13,13 @@ */ class DbResource extends BasePoolResource { - /** - * db对象 - */ - private ?IDb $db = null; - - public function __construct(\Imi\Pool\Interfaces\IPool $pool, IDb $db) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * db对象 + */ + private ?IDb $db) { parent::__construct($pool); - $this->db = $db; } /** diff --git a/src/Db/Query/Builder/BaseBuilder.php b/src/Db/Query/Builder/BaseBuilder.php index 2538517b8c..16f3f8590a 100644 --- a/src/Db/Query/Builder/BaseBuilder.php +++ b/src/Db/Query/Builder/BaseBuilder.php @@ -8,11 +8,6 @@ abstract class BaseBuilder implements IBuilder { - /** - * IQuery 类. - */ - protected ?IQuery $query = null; - /** * 绑定参数. */ @@ -30,9 +25,12 @@ public static function buildSql(IQuery $query, ...$args): string return $builder->build(...$args); } - public function __construct(IQuery $query) - { - $this->query = $query; + public function __construct( + /** + * IQuery 类. + */ + protected ?IQuery $query + ) { } /** diff --git a/src/Db/Query/Database.php b/src/Db/Query/Database.php index 75bf83d082..47a5fff044 100644 --- a/src/Db/Query/Database.php +++ b/src/Db/Query/Database.php @@ -12,20 +12,16 @@ class Database implements IDatabase { use TRaw; - /** - * 数据库名. - */ - protected ?string $database = null; - - /** - * 别名. - */ - protected ?string $alias = null; - - public function __construct(?string $database = null, ?string $alias = null) - { - $this->database = $database; - $this->alias = $alias; + public function __construct( + /** + * 数据库名. + */ + protected ?string $database = null, + /** + * 别名. + */ + protected ?string $alias = null + ) { } /** diff --git a/src/Db/Query/Field.php b/src/Db/Query/Field.php index befc88b945..8be7c6402d 100644 --- a/src/Db/Query/Field.php +++ b/src/Db/Query/Field.php @@ -9,21 +9,19 @@ class Field extends Table implements IField { - /** - * 字段名. - */ - protected ?string $field = null; - /** * JSON 关键词配置. */ protected ?array $jsonKeywords = null; - public function __construct(?string $database = null, ?string $table = null, ?string $field = null, ?string $alias = null, string $prefix = '') + public function __construct(?string $database = null, ?string $table = null, + /** + * 字段名. + */ + protected ?string $field = null, ?string $alias = null, string $prefix = '') { $this->database = $database; $this->table = $table; - $this->field = $field; $this->alias = $alias; $this->prefix = $prefix; } diff --git a/src/Db/Query/Interfaces/IQuery.php b/src/Db/Query/Interfaces/IQuery.php index 8d7f0237cb..eedfb692f5 100644 --- a/src/Db/Query/Interfaces/IQuery.php +++ b/src/Db/Query/Interfaces/IQuery.php @@ -99,11 +99,9 @@ public function distinct(bool $isDistinct = true): self; /** * 指定查询字段. * - * @param string ...$fields 查询字段 - * * @return static */ - public function field(string ...$fields): self; + public function field(mixed ...$fields): self; /** * 指定查询字段,使用SQL原生语句. diff --git a/src/Db/Query/Join.php b/src/Db/Query/Join.php index 456448d02f..2429822dd0 100644 --- a/src/Db/Query/Join.php +++ b/src/Db/Query/Join.php @@ -18,32 +18,27 @@ class Join implements IJoin */ protected ?Table $table = null; - /** - * 在 join b on a.id=b.id 中的 a.id. - */ - protected ?string $left = null; - - /** - * 在 join b on a.id=b.id 中的 =. - */ - protected ?string $operation = null; - - /** - * join b on a.id=b.id 中的 b.id. - */ - protected ?string $right = null; - - /** - * where条件. - */ - protected ?IBaseWhere $where = null; - - /** - * join类型,默认inner. - */ - protected string $type = 'inner'; - - public function __construct(IQuery $query, ?string $table = null, ?string $left = null, ?string $operation = null, ?string $right = null, ?string $tableAlias = null, ?IBaseWhere $where = null, string $type = 'inner') + public function __construct(IQuery $query, ?string $table = null, + /** + * 在 join b on a.id=b.id 中的 a.id. + */ + protected ?string $left = null, + /** + * 在 join b on a.id=b.id 中的 =. + */ + protected ?string $operation = null, + /** + * join b on a.id=b.id 中的 b.id. + */ + protected ?string $right = null, ?string $tableAlias = null, + /** + * where条件. + */ + protected ?IBaseWhere $where = null, + /** + * join类型,默认inner. + */ + protected string $type = 'inner') { $this->table = $thisTable = new Table(); if (null !== $table) @@ -54,11 +49,6 @@ public function __construct(IQuery $query, ?string $table = null, ?string $left { $thisTable->setAlias($tableAlias); } - $this->left = $left; - $this->operation = $operation; - $this->right = $right; - $this->where = $where; - $this->type = $type; } /** diff --git a/src/Db/Query/Order.php b/src/Db/Query/Order.php index 42e486cbdf..05cef3188c 100644 --- a/src/Db/Query/Order.php +++ b/src/Db/Query/Order.php @@ -12,20 +12,16 @@ class Order implements IOrder { use TRaw; - /** - * 字段名. - */ - protected string $fieldName = ''; - - /** - * 排序方向:asc/desc. - */ - protected string $direction = ''; - - public function __construct(string $fieldName = '', string $direction = 'asc') - { - $this->fieldName = $fieldName; - $this->direction = $direction; + public function __construct( + /** + * 字段名. + */ + protected string $fieldName = '', + /** + * 排序方向:asc/desc. + */ + protected string $direction = 'asc' + ) { } /** diff --git a/src/Db/Query/PaginateResult.php b/src/Db/Query/PaginateResult.php index 0a0626924e..93c3ed17c0 100644 --- a/src/Db/Query/PaginateResult.php +++ b/src/Db/Query/PaginateResult.php @@ -11,51 +11,39 @@ class PaginateResult implements IPaginateResult { - /** - * 数据库查询结构. - */ - protected ?IResult $result = null; - /** * 数组数据. */ protected ?array $arrayData = null; - /** - * 页码 - */ - protected int $page = 0; - - /** - * 查询几条记录. - */ - protected int $limit = 0; - - /** - * 记录总数. - */ - protected ?int $total = null; - - /** - * 总页数. - */ - protected ?int $pageCount = null; - - /** - * 自定义选项. - */ - protected array $options = []; - protected ?array $data = null; - public function __construct(IResult $result, int $page, int $limit, ?int $total, ?int $pageCount, array $options) - { - $this->result = $result; - $this->page = $page; - $this->limit = $limit; - $this->total = $total; - $this->options = $options; - $this->pageCount = $pageCount; + public function __construct( + /** + * 数据库查询结构. + */ + protected ?IResult $result, + /** + * 页码 + */ + protected int $page, + /** + * 查询几条记录. + */ + protected int $limit, + /** + * 记录总数. + */ + protected ?int $total, + /** + * 总页数. + */ + protected ?int $pageCount, + /** + * 自定义选项. + */ + protected array $options + ) { } /** diff --git a/src/Db/Query/Query.php b/src/Db/Query/Query.php index f43eccdb3c..e6b0184049 100644 --- a/src/Db/Query/Query.php +++ b/src/Db/Query/Query.php @@ -54,23 +54,6 @@ abstract class Query implements IQuery */ protected array $binds = []; - /** - * 数据库操作对象 - */ - protected ?IDb $db = null; - - /** - * 连接池名称. - */ - protected ?string $poolName = null; - - /** - * 查询结果类的类名,为null则为数组. - * - * @var class-string|null - */ - protected ?string $modelClass = null; - /** * 查询类型. */ @@ -124,12 +107,23 @@ abstract class Query implements IQuery */ protected array $beforeBuildSqlCallbacks = []; - public function __construct(?IDb $db = null, ?string $modelClass = null, ?string $poolName = null, ?int $queryType = null, ?string $prefix = null) + public function __construct( + /** + * 数据库操作对象 + */ + protected ?IDb $db = null, + /** + * 查询结果类的类名,为null则为数组. + * + * @var class-string|null + */ + protected ?string $modelClass = null, + /** + * 连接池名称. + */ + protected ?string $poolName = null, ?int $queryType = null, ?string $prefix = null) { - $this->db = $db; $this->isInitDb = (bool) $db; - $this->poolName = $poolName; - $this->modelClass = $modelClass; $this->queryType = $queryType ?? QueryType::WRITE; $this->isInitQueryType = null !== $queryType; if (null === $prefix) @@ -296,7 +290,7 @@ public function distinct(bool $isDistinct = true): self /** * {@inheritDoc} */ - public function field(...$fields): self + public function field(mixed ...$fields): self { $option = $this->option; if (!isset($fields[1]) && \is_array($fields[0])) @@ -909,9 +903,9 @@ public function buildSelectSql(): string $sql = (new $builderClass($this))->build(); if ($alias) { - // @phpstan-ignore-next-line $originBinds = $binds; $binds = $this->binds; + // @phpstan-ignore-next-line todo 此处 $binds 为无效判断,已经利用 $alias 在前一个 if 中置空了。 if ($binds) { $this->binds = array_merge($originBinds, $binds); @@ -1404,7 +1398,7 @@ public function fullText($fieldNames, string $searchText, ?IFullTextOptions $opt $orderDirection = $options->getOrderDirection(); if (null !== $orderDirection) { - $this->beforeBuildSqlCallbacks[] = function () use ($scoreFieldName, $options, $orderDirection) { + $this->beforeBuildSqlCallbacks[] = function () use ($scoreFieldName, $options, $orderDirection): void { if (null === $scoreFieldName || '' === $scoreFieldName) { $this->orderRaw('(' . $options->toScoreSql($this) . ') ' . $orderDirection); diff --git a/src/Db/Query/Result.php b/src/Db/Query/Result.php index 280a6efe52..efddc980b7 100644 --- a/src/Db/Query/Result.php +++ b/src/Db/Query/Result.php @@ -27,11 +27,6 @@ class Result implements IResult */ protected bool $isSuccess = false; - /** - * 查询结果类的类名,为null则为数组. - */ - protected ?string $modelClass = null; - /** * 记录列表. */ @@ -40,9 +35,12 @@ class Result implements IResult /** * @param \Imi\Db\Interfaces\IStatement|bool $statement */ - public function __construct($statement, ?string $modelClass = null, ?bool $success = null) + public function __construct($statement, + /** + * 查询结果类的类名,为null则为数组. + */ + protected ?string $modelClass = null, ?bool $success = null) { - $this->modelClass = $modelClass; if ($statement instanceof IStatement) { $this->statement = $statement; diff --git a/src/Db/Query/Result/ChunkByOffsetResult.php b/src/Db/Query/Result/ChunkByOffsetResult.php index 6522ad81cf..60db2f7f07 100644 --- a/src/Db/Query/Result/ChunkByOffsetResult.php +++ b/src/Db/Query/Result/ChunkByOffsetResult.php @@ -9,14 +9,8 @@ class ChunkByOffsetResult extends BaseChunkResult { - private ?IQuery $query = null; - - private int $limit = 0; - - public function __construct(IQuery $query, int $limit) + public function __construct(private readonly ?IQuery $query, private readonly int $limit) { - $this->query = $query; - $this->limit = $limit; } /** diff --git a/src/Db/Query/Result/ChunkResult.php b/src/Db/Query/Result/ChunkResult.php index 55d0599341..0d78d1dd9d 100644 --- a/src/Db/Query/Result/ChunkResult.php +++ b/src/Db/Query/Result/ChunkResult.php @@ -9,22 +9,10 @@ class ChunkResult extends BaseChunkResult { - private ?IQuery $query = null; - - private int $limit = 0; - - private string $column = ''; - - private string $alias = ''; - private string $orderBy = ''; - public function __construct(IQuery $query, int $limit, string $column, string $alias, string $orderBy) + public function __construct(private readonly ?IQuery $query, private readonly int $limit, private readonly string $column, private readonly string $alias, string $orderBy) { - $this->query = $query; - $this->limit = $limit; - $this->column = $column; - $this->alias = $alias; $this->orderBy = strtolower($orderBy); } diff --git a/src/Db/Query/Result/CursorResult.php b/src/Db/Query/Result/CursorResult.php index 5cafe869ea..5e9c6f032c 100644 --- a/src/Db/Query/Result/CursorResult.php +++ b/src/Db/Query/Result/CursorResult.php @@ -21,17 +21,15 @@ class CursorResult implements \IteratorAggregate */ protected bool $isSuccess = false; - /** - * 查询结果类的类名,为null则为数组. - */ - protected ?string $modelClass = null; - /** * @param \Imi\Db\Interfaces\IStatement|bool $statement */ - public function __construct($statement, ?string $modelClass = null) + public function __construct($statement, + /** + * 查询结果类的类名,为null则为数组. + */ + protected ?string $modelClass = null) { - $this->modelClass = $modelClass; if ($statement instanceof IStatement) { $this->statement = $statement; diff --git a/src/Db/Query/Table.php b/src/Db/Query/Table.php index 1bd5e4dc3e..87f5900078 100644 --- a/src/Db/Query/Table.php +++ b/src/Db/Query/Table.php @@ -12,32 +12,24 @@ class Table implements ITable { use TRaw; - /** - * 数据库名. - */ - protected ?string $database = null; - - /** - * 表前缀. - */ - protected string $prefix = ''; - - /** - * 表名. - */ - protected ?string $table = null; - - /** - * 别名. - */ - protected ?string $alias = null; - - public function __construct(?string $database = null, ?string $table = null, ?string $alias = null, string $prefix = '') - { - $this->database = $database; - $this->table = $table; - $this->alias = $alias; - $this->prefix = $prefix; + public function __construct( + /** + * 数据库名. + */ + protected ?string $database = null, + /** + * 表名. + */ + protected ?string $table = null, + /** + * 别名. + */ + protected ?string $alias = null, + /** + * 表前缀. + */ + protected string $prefix = '' + ) { } /** diff --git a/src/Db/Query/Where/Where.php b/src/Db/Query/Where/Where.php index e82b22b576..07c2929fe3 100644 --- a/src/Db/Query/Where/Where.php +++ b/src/Db/Query/Where/Where.php @@ -14,31 +14,23 @@ class Where extends BaseWhere implements IWhere { use TRaw; - /** - * 字段名. - */ - protected ?string $fieldName = null; - - /** - * 比较符. - */ - protected ?string $operation = null; - - /** - * 值 - * - * @var mixed - */ - protected $value; - /** * @param mixed $value */ - public function __construct(?string $fieldName = null, ?string $operation = null, $value = null, string $logicalOperator = LogicalOperator::AND) + public function __construct( + /** + * 字段名. + */ + protected ?string $fieldName = null, + /** + * 比较符. + */ + protected ?string $operation = null, + /** + * 值 + */ + protected $value = null, string $logicalOperator = LogicalOperator::AND) { - $this->fieldName = $fieldName; - $this->operation = $operation; - $this->value = $value; $this->logicalOperator = $logicalOperator; } diff --git a/src/Db/Query/Where/WhereFullText.php b/src/Db/Query/Where/WhereFullText.php index c13b91204c..050a41bfe5 100644 --- a/src/Db/Query/Where/WhereFullText.php +++ b/src/Db/Query/Where/WhereFullText.php @@ -13,11 +13,8 @@ class WhereFullText extends BaseWhere implements IWhereFullText { use TRaw; - protected ?IFullTextOptions $options = null; - - public function __construct(?IFullTextOptions $options = null, string $logicalOperator = 'AND') + public function __construct(protected ?IFullTextOptions $options = null, string $logicalOperator = 'AND') { - $this->options = $options; $this->logicalOperator = $logicalOperator; } diff --git a/src/Db/Query/WhereCollector.php b/src/Db/Query/WhereCollector.php index 8412f922cd..795fb6761d 100644 --- a/src/Db/Query/WhereCollector.php +++ b/src/Db/Query/WhereCollector.php @@ -21,11 +21,8 @@ class WhereCollector implements IWhereCollector */ protected array $where = []; - protected IQuery $query; - - public function __construct(IQuery $query) + public function __construct(protected IQuery $query) { - $this->query = $query; } /** diff --git a/src/Db/Query/WrapField.php b/src/Db/Query/WrapField.php index f3f1f039cb..416ea0fd1d 100644 --- a/src/Db/Query/WrapField.php +++ b/src/Db/Query/WrapField.php @@ -9,17 +9,8 @@ class WrapField extends Field implements IWrapField { - protected array $subFields = []; - - protected string $wrapLeft = ''; - - protected string $wrapRight = ''; - - public function __construct(string $wrapLeft, array $subFields, string $wrapRight, ?string $alias = null) + public function __construct(protected string $wrapLeft, protected array $subFields, protected string $wrapRight, ?string $alias = null) { - $this->wrapLeft = $wrapLeft; - $this->subFields = $subFields; - $this->wrapRight = $wrapRight; $this->alias = $alias; } diff --git a/src/Env.php b/src/Env.php index 37f0c07cd5..e24bd82f5f 100644 --- a/src/Env.php +++ b/src/Env.php @@ -27,7 +27,7 @@ public static function get(?string $varname = null, $default = null) { return $result; } - $lower = strtolower($result); + $lower = strtolower((string) $result); if ('null' === $lower) { return null; @@ -69,10 +69,10 @@ public static function get(?string $varname = null, $default = null) } break; case 'array': - $value = json_decode($result, true); + $value = json_decode((string) $result, true); if (\JSON_ERROR_NONE !== json_last_error()) { - $value = explode(',', $result); + $value = explode(',', (string) $result); // @phpstan-ignore-next-line if (false === $value) { @@ -93,7 +93,7 @@ public static function str(string $varname, ?string $default = null): ?string { return $default; } - if ('null' === strtolower($result)) + if ('null' === strtolower((string) $result)) { return null; } @@ -108,7 +108,7 @@ public static function int(string $varname, ?int $default = 0): ?int { return $default; } - if ('null' === strtolower($result)) + if ('null' === strtolower((string) $result)) { return null; } @@ -128,7 +128,7 @@ public static function float(string $varname, ?float $default = 0): ?float { return $default; } - if ('null' === strtolower($result)) + if ('null' === strtolower((string) $result)) { return null; } @@ -153,7 +153,7 @@ public static function bool(string $varname, ?bool $default = null): ?bool { return $default; } - $lower = strtolower($result); + $lower = strtolower((string) $result); if ('null' === $lower) { return null; @@ -184,13 +184,13 @@ public static function json(?string $varname = null, $default = null, ?bool $ass } try { - $value = json_decode($result, $associative, $depth, $flags); + $value = json_decode((string) $result, $associative, $depth, $flags); if (!$value && \JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException(sprintf('Invalid json value %s', $result)); } } - catch (\JsonException $je) + catch (\JsonException) { throw new \InvalidArgumentException(sprintf('Invalid json value %s', $result)); } @@ -209,12 +209,12 @@ public static function list(?string $varname = null, ?array $default = null, str { return $default; } - if ('null' === strtolower($result)) + if ('null' === strtolower((string) $result)) { return null; } // @phpstan-ignore-next-line - if ('' === $result || false === ($value = explode($separator, $result, $limit))) + if ('' === $result || false === ($value = explode($separator, (string) $result, $limit))) { throw new \InvalidArgumentException(sprintf('Invalid list value %s', $result)); } diff --git a/src/Event/EventItem.php b/src/Event/EventItem.php index afdc6d7201..d3f6773337 100644 --- a/src/Event/EventItem.php +++ b/src/Event/EventItem.php @@ -18,21 +18,17 @@ class EventItem */ public $callback; - /** - * 优先级 - * 越大越先执行. - */ - public int $priority = 0; - - /** - * 是否为一次性事件. - */ - public bool $oneTime = false; - - public function __construct(callable $callback, int $priority = 0, bool $oneTime = false) + public function __construct(callable $callback, + /** + * 优先级 + * 越大越先执行. + */ + public int $priority = 0, + /** + * 是否为一次性事件. + */ + public bool $oneTime = false) { $this->callback = $callback; - $this->priority = $priority; - $this->oneTime = $oneTime; } } diff --git a/src/Event/EventParam.php b/src/Event/EventParam.php index c0c33d7e48..14b79768be 100644 --- a/src/Event/EventParam.php +++ b/src/Event/EventParam.php @@ -7,34 +7,28 @@ #[\AllowDynamicProperties] class EventParam { - /** - * 事件名称. - */ - protected string $__eventName = ''; - - /** - * 触发该事件的对象 - */ - protected ?object $__target = null; - - /** - * 数据. - */ - protected array $__data = []; - /** * 阻止事件继续传播. */ protected bool $__stopPropagation = false; - public function __construct(string $eventName, array $data = [], ?object $target = null) + public function __construct( + /** + * 事件名称. + */ + protected string $__eventName, + /** + * 数据. + */ + protected array $__data = [], + /** + * 触发该事件的对象 + */ + protected ?object $__target = null) { - $this->__eventName = $eventName; - $this->__target = $target; - $this->__data = $data; - if ($data) + if ($__data) { - foreach ($data as $key => &$value) + foreach ($__data as $key => &$value) { $this->{$key} = &$value; } diff --git a/src/Event/TEvent.php b/src/Event/TEvent.php index 60b94c4e75..07f49e498b 100644 --- a/src/Event/TEvent.php +++ b/src/Event/TEvent.php @@ -48,7 +48,7 @@ public function on($name, $callback, int $priority = 0): void if (\is_string($callback) && class_exists($callback)) { $callbackClass = $callback; - $callback = static function ($param) use ($callback) { + $callback = static function ($param) use ($callback): void { $obj = BeanFactory::newInstance($callback); $obj->handle($param); }; @@ -84,7 +84,7 @@ public function one($name, $callback, int $priority = 0): void if (\is_string($callback) && class_exists($callback)) { $callbackClass = $callback; - $callback = static function ($param) use ($callback) { + $callback = static function ($param) use ($callback): void { $obj = BeanFactory::newInstance($callback); $obj->handle($param); }; diff --git a/src/HotUpdate/Monitor/BaseMonitor.php b/src/HotUpdate/Monitor/BaseMonitor.php index 5a56969b12..20bf343bb4 100644 --- a/src/HotUpdate/Monitor/BaseMonitor.php +++ b/src/HotUpdate/Monitor/BaseMonitor.php @@ -6,26 +6,14 @@ abstract class BaseMonitor implements IMonitor { - /** - * 包含的路径. - */ - protected array $includePaths = []; - - /** - * 排除的路径. - */ - protected array $excludePaths = []; - /** * 构造方法. * * @param array $includePaths 包含的路径 * @param array $excludePaths 排除的路径 */ - public function __construct(array $includePaths, array $excludePaths = []) + public function __construct(protected array $includePaths, protected array $excludePaths = []) { - $this->includePaths = $includePaths; - $this->excludePaths = $excludePaths; $this->init(); } diff --git a/src/HotUpdate/Monitor/FileMTime.php b/src/HotUpdate/Monitor/FileMTime.php index e262e489fd..b68a6c3544 100644 --- a/src/HotUpdate/Monitor/FileMTime.php +++ b/src/HotUpdate/Monitor/FileMTime.php @@ -31,7 +31,7 @@ protected function init(): void { $includePaths = &$this->includePaths; - $excludePaths = array_map([Imi::class, 'parseRule'], $this->excludePaths); + $excludePaths = array_map(Imi::parseRule(...), $this->excludePaths); $this->excludeRule = $excludeRule = '/^(?!((' . implode(')|(', $excludePaths) . ')))/'; @@ -42,7 +42,7 @@ protected function init(): void foreach ($enumResult as $file) { $fullPath = $file->getFullPath(); - if ('' !== $excludeRule && !preg_match($excludeRule, $fullPath)) + if ('' !== $excludeRule && !preg_match($excludeRule, (string) $fullPath)) { $file->setContinue(false); continue; @@ -93,7 +93,7 @@ public function isChanged(): bool foreach ($enumResult as $file) { $fullPath = $file->getFullPath(); - if ('' !== $excludeRule && !preg_match($excludeRule, $fullPath)) + if ('' !== $excludeRule && !preg_match($excludeRule, (string) $fullPath)) { $file->setContinue(false); continue; diff --git a/src/HotUpdate/Monitor/Inotify.php b/src/HotUpdate/Monitor/Inotify.php index 180783c378..60f314b0ae 100644 --- a/src/HotUpdate/Monitor/Inotify.php +++ b/src/HotUpdate/Monitor/Inotify.php @@ -50,7 +50,7 @@ protected function init(): void $this->handler = $handler = inotify_init(); stream_set_blocking($handler, false); - $excludePaths = array_map([Imi::class, 'parseRule'], $this->excludePaths); + $excludePaths = array_map(Imi::parseRule(...), $this->excludePaths); $this->excludeRule = $excludeRule = '/^(?!((' . implode(')|(', $excludePaths) . ')))/'; $paths = &$this->paths; @@ -72,7 +72,7 @@ protected function init(): void { continue; } - if ('' !== $excludeRule && !preg_match($excludeRule, $fullPath)) + if ('' !== $excludeRule && !preg_match($excludeRule, (string) $fullPath)) { $file->setContinue(false); continue; diff --git a/src/Lock/Aop/TLockableParser.php b/src/Lock/Aop/TLockableParser.php index 4702b54b60..cc2f1ee7ef 100644 --- a/src/Lock/Aop/TLockableParser.php +++ b/src/Lock/Aop/TLockableParser.php @@ -106,7 +106,7 @@ public function parseLockable($object, $method, $args, $lockable, $taskCallable, }; } - if (!$locker->lock(static function () use ($taskCallable, &$result) { + if (!$locker->lock(static function () use ($taskCallable, &$result): void { // 执行原方法 $result = $taskCallable(); }, $afterLockCallable)) diff --git a/src/Lock/Handler/BaseLock.php b/src/Lock/Handler/BaseLock.php index 121e1f5abc..58d3909adf 100644 --- a/src/Lock/Handler/BaseLock.php +++ b/src/Lock/Handler/BaseLock.php @@ -10,11 +10,6 @@ abstract class BaseLock implements ILockHandler { - /** - * 锁的唯一 ID. - */ - protected string $id = ''; - /** * 是否已加锁 */ @@ -50,9 +45,12 @@ abstract class BaseLock implements ILockHandler */ protected bool $unlockException = false; - public function __construct(string $id, array $options = []) + public function __construct( + /** + * 锁的唯一 ID. + */ + protected string $id, array $options = []) { - $this->id = $id; if ($options) { foreach ($options as $k => $v) diff --git a/src/Log/ErrorLog.php b/src/Log/ErrorLog.php index 56219de648..77ffdc84a1 100644 --- a/src/Log/ErrorLog.php +++ b/src/Log/ErrorLog.php @@ -37,8 +37,8 @@ public function register(): void error_reporting($this->level); register_shutdown_function([$this, 'onShutdown']); // @phpstan-ignore-next-line - set_error_handler([$this, 'onError'], $this->catchLevel); - set_exception_handler([$this, 'onException']); + set_error_handler($this->onError(...), $this->catchLevel); + set_exception_handler($this->onException(...)); } /** @@ -50,33 +50,13 @@ public function onError(int $errno, string $errstr, string $errfile, int $errlin { throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); } - switch ($errno) + $method = match ($errno) { - case \E_ERROR: - case \E_PARSE: - case \E_CORE_ERROR: - case \E_COMPILE_ERROR: - case \E_USER_ERROR: - case \E_RECOVERABLE_ERROR: - $method = 'error'; - break; - case \E_WARNING: - case \E_CORE_WARNING: - case \E_COMPILE_WARNING: - case \E_USER_WARNING: - $method = 'warning'; - break; - case \E_NOTICE: - case \E_USER_NOTICE: - $method = 'notice'; - break; - case \E_STRICT: - case \E_DEPRECATED: - case \E_USER_DEPRECATED: - default: - $method = 'info'; - break; - } + \E_ERROR, \E_PARSE, \E_CORE_ERROR, \E_COMPILE_ERROR, \E_USER_ERROR, \E_RECOVERABLE_ERROR => 'error', + \E_WARNING, \E_CORE_WARNING, \E_COMPILE_WARNING, \E_USER_WARNING => 'warning', + \E_NOTICE, \E_USER_NOTICE => 'notice', + default => 'info', + }; Log::$method($errstr); } diff --git a/src/Log/Formatter/ConsoleLineFormatter.php b/src/Log/Formatter/ConsoleLineFormatter.php index 63531dcdf9..ab1931f66b 100644 --- a/src/Log/Formatter/ConsoleLineFormatter.php +++ b/src/Log/Formatter/ConsoleLineFormatter.php @@ -96,14 +96,14 @@ public function format(LogRecord $record): string switch ($var) { case 'level_name': - $style = $this->levelStyles[strtolower($vars['level_name'])] ?? null; + $style = $this->levelStyles[strtolower((string) $vars['level_name'])] ?? null; if ($style) { $replace = $style . $replace . ''; } break; case 'message': - $style = $this->messageStyles[strtolower($vars['level_name'])] ?? null; + $style = $this->messageStyles[strtolower((string) $vars['level_name'])] ?? null; if ($style) { $replace = $style . $replace . ''; diff --git a/src/Main/BaseMain.php b/src/Main/BaseMain.php index be829071b1..6f7a194ebe 100644 --- a/src/Main/BaseMain.php +++ b/src/Main/BaseMain.php @@ -21,19 +21,17 @@ abstract class BaseMain implements IMain */ protected ?string $namespace = null; - /** - * 模块名称. - */ - protected string $moduleName = ''; - /** * 模块配置. */ protected ?array $config = null; - public function __construct(string $moduleName) + public function __construct( + /** + * 模块名称. + */ + protected string $moduleName) { - $this->moduleName = $moduleName; $this->__init(); } diff --git a/src/Model/Cli/Model/ModelGenerate.php b/src/Model/Cli/Model/ModelGenerate.php index daad899c3c..a8700393e5 100644 --- a/src/Model/Cli/Model/ModelGenerate.php +++ b/src/Model/Cli/Model/ModelGenerate.php @@ -237,7 +237,7 @@ public function generate(string $namespace, string $baseClass, ?string $database { $ddl = $ddlEncode($rawDDL); } - if ($usePrefix = ('' !== $tablePrefix && str_starts_with($table, $tablePrefix))) + if ($usePrefix = ('' !== $tablePrefix && str_starts_with((string) $table, (string) $tablePrefix))) { $tableName = Text::ltrimText($table, $tablePrefix); } @@ -326,7 +326,7 @@ private function getClassName(string $table, array $prefixs): string { foreach ($prefixs as $prefix) { - $prefixLen = \strlen($prefix); + $prefixLen = \strlen((string) $prefix); if (substr($table, 0, $prefixLen) === $prefix) { $table = substr($table, $prefixLen); @@ -361,12 +361,12 @@ private function parseFields(array $fields, array $pks, ?array &$data, array $ty 'defaultValue' => $this->parseFieldDefaultValue($typeName, $field['Default']), 'isPrimaryKey' => $isPk, 'primaryKeyIndex' => $primaryKeyIndex = ($pks[$field['Field']]['Seq_in_index'] ?? 0) - 1, - 'isAutoIncrement' => str_contains($field['Extra'], 'auto_increment'), + 'isAutoIncrement' => str_contains((string) $field['Extra'], 'auto_increment'), 'comment' => $field['Comment'], 'typeDefinition' => $typeDefinitions[$field['Field']], 'ref' => 'json' === $typeName, 'unsigned' => $unsigned, - 'virtual' => str_contains($field['Extra'], 'VIRTUAL GENERATED'), + 'virtual' => str_contains((string) $field['Extra'], 'VIRTUAL GENERATED'), ]; if ($isPk) { @@ -469,7 +469,7 @@ private function parseFieldDefaultValue(string $type, $default) case 'year': return (int) $default; case 'bit': - return (bool) str_replace(['b', '\''], '', $default); + return (bool) str_replace(['b', '\''], '', (string) $default); case 'double': case 'float': return (float) $default; @@ -491,7 +491,7 @@ private function parseFieldDefaultValue(string $type, $default) return null; } - return explode(',', $default); + return explode(',', (string) $default); default: return null; } @@ -506,6 +506,6 @@ public function getDDL(IQuery $query, string $table, string $database): string $row = $result->get(); $sql = $row['Create Table'] ?? $row['Create View'] ?? ''; - return preg_replace('/ AUTO_INCREMENT=\d+ /', ' ', $sql, 1); + return preg_replace('/ AUTO_INCREMENT=\d+ /', ' ', (string) $sql, 1); } } diff --git a/src/Model/Key/KeyRule.php b/src/Model/Key/KeyRule.php index ed82f6dcee..0923905ca3 100644 --- a/src/Model/Key/KeyRule.php +++ b/src/Model/Key/KeyRule.php @@ -6,21 +6,17 @@ class KeyRule { - /** - * 规则. - */ - public string $rule = ''; - - /** - * 参数名数组. - * - * @var string[] - */ - public array $paramNames = []; - - public function __construct(string $rule, array $paramNames) - { - $this->rule = $rule; - $this->paramNames = $paramNames; + public function __construct( + /** + * 规则. + */ + public string $rule, + /** + * 参数名数组. + * + * @var string[] + */ + public array $paramNames + ) { } } diff --git a/src/Model/Meta.php b/src/Model/Meta.php index dd6342dbe3..9a8cbe07a8 100644 --- a/src/Model/Meta.php +++ b/src/Model/Meta.php @@ -161,11 +161,6 @@ class Meta */ private array $sqlColumns = []; - /** - * 是否为继承父类的模型. - */ - private bool $inherit = false; - /** * 真实的模型类名. */ @@ -188,9 +183,12 @@ class Meta */ private bool $incrUpdate = false; - public function __construct(string $modelClass, bool $inherit = false) + public function __construct(string $modelClass, + /** + * 是否为继承父类的模型. + */ + private readonly bool $inherit = false) { - $this->inherit = $inherit; if ($inherit) { $realModelClass = get_parent_class($modelClass); diff --git a/src/Model/Model.php b/src/Model/Model.php index b08dd6b5e7..eda7e30e13 100644 --- a/src/Model/Model.php +++ b/src/Model/Model.php @@ -986,24 +986,16 @@ protected static function parseDateTime(?string $columnType, $timeAccuracy, ?flo { $microTime ??= microtime(true); - switch ($columnType) + return match ($columnType) { - case 'date': - return date('Y-m-d', (int) $microTime); - case 'time': - return date('H:i:s', (int) $microTime); - case 'datetime': - case 'timestamp': - return date('Y-m-d H:i:s', (int) $microTime); - case 'int': - return (int) $microTime; - case 'bigint': - return (int) ($microTime * (true === $timeAccuracy ? 1000 : $timeAccuracy)); - case 'year': - return (int) date('Y', (int) $microTime); - default: - return null; - } + 'date' => date('Y-m-d', (int) $microTime), + 'time' => date('H:i:s', (int) $microTime), + 'datetime', 'timestamp' => date('Y-m-d H:i:s', (int) $microTime), + 'int' => (int) $microTime, + 'bigint' => (int) ($microTime * (true === $timeAccuracy ? 1000 : $timeAccuracy)), + 'year' => (int) date('Y', (int) $microTime), + default => null, + }; } /** diff --git a/src/Model/RedisModel.php b/src/Model/RedisModel.php index 9c9e0f4ea5..6aa6010a27 100644 --- a/src/Model/RedisModel.php +++ b/src/Model/RedisModel.php @@ -449,17 +449,14 @@ public function delete(): bool { /** @var \Imi\Model\Annotation\RedisEntity $redisEntity */ $redisEntity = static::__getRedisEntity(static::__getRealClassName()); - switch ($redisEntity->storage) + + return match ($redisEntity->storage) { - case RedisStorageMode::STRING: - return static::__getRedis($this)->del($this->__getKey()) > 0; - case RedisStorageMode::HASH: - return static::__getRedis($this)->hDel($this->__getKey(), $this->__getMember()) > 0; - case RedisStorageMode::HASH_OBJECT: - return static::__getRedis($this)->del($this->__getKey()) > 0; - default: - throw new \InvalidArgumentException(sprintf('Invalid RedisEntity->storage %s', $redisEntity->storage)); - } + RedisStorageMode::STRING => static::__getRedis($this)->del($this->__getKey()) > 0, + RedisStorageMode::HASH => static::__getRedis($this)->hDel($this->__getKey(), $this->__getMember()) > 0, + RedisStorageMode::HASH_OBJECT => static::__getRedis($this)->del($this->__getKey()) > 0, + default => throw new \InvalidArgumentException(sprintf('Invalid RedisEntity->storage %s', $redisEntity->storage)), + }; } /** diff --git a/src/Model/Relation/Delete.php b/src/Model/Relation/Delete.php index 267455e1da..bee8462163 100644 --- a/src/Model/Relation/Delete.php +++ b/src/Model/Relation/Delete.php @@ -139,7 +139,7 @@ public static function parseByOneToMany(Model $model, string $propertyName, \Imi 'annotation' => $annotation, 'struct' => $struct, ]); - $rightModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $rightField) { + $rightModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $rightField): void { $query->where($rightField, '=', $model[$leftField]); }); Event::trigger($eventName . '.AFTER', [ @@ -169,7 +169,7 @@ public static function parseByManyToMany(Model $model, string $propertyName, \Im 'annotation' => $annotation, 'struct' => $struct, ]); - $middleModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $middleLeftField) { + $middleModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $middleLeftField): void { $query->where($middleLeftField, '=', $model[$leftField]); }); Event::trigger($eventName . '.AFTER', [ @@ -286,7 +286,7 @@ public static function parseByPolymorphicOneToMany(Model $model, string $propert 'struct' => $struct, ]); - $rightModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $rightField, $annotation) { + $rightModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $rightField, $annotation): void { $query->where($annotation->type, '=', $annotation->typeValue)->where($rightField, '=', $model[$leftField]); }); Event::trigger($eventName . '.AFTER', [ @@ -317,7 +317,7 @@ public static function parseByPolymorphicManyToMany(Model $model, string $proper 'struct' => $struct, ]); - $middleModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $middleLeftField, $annotation) { + $middleModel::deleteBatch(static function (IModelQuery $query) use ($model, $leftField, $middleLeftField, $annotation): void { $query->where($annotation->type, '=', $annotation->typeValue)->where($middleLeftField, '=', $model[$leftField]); }); Event::trigger($eventName . '.AFTER', [ diff --git a/src/Model/Relation/Query.php b/src/Model/Relation/Query.php index e622ef60c1..f12653724e 100644 --- a/src/Model/Relation/Query.php +++ b/src/Model/Relation/Query.php @@ -1007,9 +1007,9 @@ public static function appendMany(ArrayList $manyList, array $dataList, string $ $tmpRow[$keysMap[$key]] = $value; } } - elseif (str_starts_with($key, $table)) + elseif (str_starts_with((string) $key, $table)) { - $keysMap[$key] = $realKey = substr($key, $tableLength); + $keysMap[$key] = $realKey = substr((string) $key, $tableLength); $tmpRow[$realKey] = $value; } else diff --git a/src/Model/Relation/TRelation.php b/src/Model/Relation/TRelation.php index 8be6bdc2d2..258cbbf1ce 100644 --- a/src/Model/Relation/TRelation.php +++ b/src/Model/Relation/TRelation.php @@ -17,13 +17,12 @@ protected static function parsePoolName($poolName, string $parentModel, string $ { return $poolName; } - switch ($poolName) + + return match ($poolName) { - case RelationPoolName::PARENT: - return $parentModel::__getMeta()->getDbPoolName(); - case RelationPoolName::RELATION: - return $relationModel::__getMeta()->getDbPoolName(); - } - throw new \InvalidArgumentException(sprintf('Invalid poolName %s', $poolName)); + RelationPoolName::PARENT => $parentModel::__getMeta()->getDbPoolName(), + RelationPoolName::RELATION => $relationModel::__getMeta()->getDbPoolName(), + default => throw new \InvalidArgumentException(sprintf('Invalid poolName %s', $poolName)), + }; } } diff --git a/src/Model/Relation/Update.php b/src/Model/Relation/Update.php index 94dfeba137..790bf7ba8d 100644 --- a/src/Model/Relation/Update.php +++ b/src/Model/Relation/Update.php @@ -203,7 +203,7 @@ public static function parseByOneToMany(Model $model, string $propertyName, \Imi if ($deleteIds) { // 批量删除 - $rightModel::deleteBatch(static function (IModelQuery $query) use ($pk, $deleteIds) { + $rightModel::deleteBatch(static function (IModelQuery $query) use ($pk, $deleteIds): void { $query->whereIn($pk, $deleteIds); }); } @@ -294,7 +294,7 @@ public static function parseByManyToMany(Model $model, string $propertyName, \Im if ($deleteIds) { // 批量删除 - $middleModel::deleteBatch(static function (IModelQuery $query) use ($middleLeftField, $middleRightField, $deleteIds, $modelLeftValue) { + $middleModel::deleteBatch(static function (IModelQuery $query) use ($middleLeftField, $middleRightField, $deleteIds, $modelLeftValue): void { $query->where($middleLeftField, '=', $modelLeftValue)->whereIn($middleRightField, $deleteIds); }); } @@ -522,7 +522,7 @@ public static function parseByPolymorphicOneToMany(Model $model, string $propert if ($deleteIds) { // 批量删除 - $rightModel::deleteBatch(static function (IModelQuery $query) use ($pk, $deleteIds) { + $rightModel::deleteBatch(static function (IModelQuery $query) use ($pk, $deleteIds): void { $query->whereIn($pk, $deleteIds); }); } @@ -614,7 +614,7 @@ public static function parseByPolymorphicManyToMany(Model $model, string $proper if ($deleteIds) { // 批量删除 - $middleModel::deleteBatch(static function (IModelQuery $query) use ($middleLeftField, $middleRightField, $deleteIds, $annotation, $modelLeftValue) { + $middleModel::deleteBatch(static function (IModelQuery $query) use ($middleLeftField, $middleRightField, $deleteIds, $annotation, $modelLeftValue): void { $query->where($annotation->type, '=', $annotation->typeValue)->where($middleLeftField, '=', $modelLeftValue)->whereIn($middleRightField, $deleteIds); }); } diff --git a/src/Model/SoftDelete/Traits/TSoftDelete.php b/src/Model/SoftDelete/Traits/TSoftDelete.php index 86e429e6b9..5c7ec98706 100644 --- a/src/Model/SoftDelete/Traits/TSoftDelete.php +++ b/src/Model/SoftDelete/Traits/TSoftDelete.php @@ -166,7 +166,7 @@ public function delete(): IResult */ public function hardDelete(): IResult { - $this->one(ModelEvents::BEFORE_DELETE, static function (BeforeDeleteEventParam $e) { + $this->one(ModelEvents::BEFORE_DELETE, static function (BeforeDeleteEventParam $e): void { $e->query->getOption()->where = []; }); diff --git a/src/Pool/BasePool.php b/src/Pool/BasePool.php index f4f729667e..427a6611f3 100644 --- a/src/Pool/BasePool.php +++ b/src/Pool/BasePool.php @@ -11,11 +11,6 @@ abstract class BasePool implements IPool { - /** - * 池子名称. - */ - protected string $name = ''; - /** * 池子存储. * @@ -55,9 +50,12 @@ abstract class BasePool implements IPool /** * @param mixed $resourceConfig */ - public function __construct(string $name, Interfaces\IPoolConfig $config = null, $resourceConfig = null) + public function __construct( + /** + * 池子名称. + */ + protected string $name, Interfaces\IPoolConfig $config = null, $resourceConfig = null) { - $this->name = $name; if (null !== $config) { $this->config = $config; diff --git a/src/Pool/BasePoolResource.php b/src/Pool/BasePoolResource.php index a446907e9e..a7ba36726f 100644 --- a/src/Pool/BasePoolResource.php +++ b/src/Pool/BasePoolResource.php @@ -12,14 +12,12 @@ abstract class BasePoolResource implements IPoolResource { use THashCode; - /** - * 池子实例. - */ - private ?IPool $pool = null; - - public function __construct(IPool $pool) - { - $this->pool = $pool; + public function __construct( + /** + * 池子实例. + */ + private readonly ?IPool $pool + ) { } /** diff --git a/src/Pool/PoolItem.php b/src/Pool/PoolItem.php index 78b2327664..fa6150c4bf 100644 --- a/src/Pool/PoolItem.php +++ b/src/Pool/PoolItem.php @@ -11,11 +11,6 @@ */ class PoolItem { - /** - * 资源对象 - */ - protected ?IPoolResource $resource = null; - /** * 被使用的次数. */ @@ -41,9 +36,12 @@ class PoolItem */ protected float $lastReleaseTime = 0; - public function __construct(IPoolResource $resource) + public function __construct( + /** + * 资源对象 + */ + protected ?IPoolResource $resource) { - $this->resource = $resource; $this->createTime = microtime(true); } diff --git a/src/Pool/TUriResourceConfig.php b/src/Pool/TUriResourceConfig.php index f0c8933ef1..549ed5f78f 100644 --- a/src/Pool/TUriResourceConfig.php +++ b/src/Pool/TUriResourceConfig.php @@ -16,7 +16,7 @@ protected function initUriResourceConfig(): void { continue; } - $list = explode(';', $config); + $list = explode(';', (string) $config); $config = []; foreach ($list as $uri) { diff --git a/src/Redis/RedisHandler.php b/src/Redis/RedisHandler.php index 4af7c52e4c..f28c0f946d 100644 --- a/src/Redis/RedisHandler.php +++ b/src/Redis/RedisHandler.php @@ -238,13 +238,6 @@ */ class RedisHandler { - /** - * redis 对象 - * - * @var \Redis|\RedisCluster - */ - private $redis; - private bool $isUnix = false; /** @@ -272,9 +265,12 @@ class RedisHandler /** * @param \Redis|\RedisCluster $redis */ - public function __construct($redis) + public function __construct( + /** + * redis 对象 + */ + private $redis) { - $this->redis = $redis; if (!$this->isCluster() && $redis->isConnected()) { $this->host = $redis->getHost(); diff --git a/src/Redis/RedisManager.php b/src/Redis/RedisManager.php index 4b262fbf23..c6f4e959dc 100644 --- a/src/Redis/RedisManager.php +++ b/src/Redis/RedisManager.php @@ -92,7 +92,7 @@ public static function getInstance(?string $poolName = null): ?RedisHandler App::set($requestContextKey, $redis); if (($heartbeatInterval = $config['heartbeatInterval'] ?? 0) > 0) { - Timer::tick((int) ($heartbeatInterval * 1000), static function () use ($requestContextKey) { + Timer::tick((int) ($heartbeatInterval * 1000), static function () use ($requestContextKey): void { /** @var RedisHandler|null $redis */ $redis = App::get($requestContextKey); if (!$redis) @@ -126,7 +126,7 @@ public static function heartbeat(RedisHandler $redis): void $redis->reconnect(); } } - catch (\Throwable $th) + catch (\Throwable) { $redis->reconnect(); } @@ -173,7 +173,7 @@ public static function initRedisConnection(RedisHandler $redis, array $config): if (!$redis->isCluster()) { $host = $config['host'] ?? '127.0.0.1'; - if (str_contains($host, '/')) + if (str_contains((string) $host, '/')) { // unix socket $redis->connect($host); diff --git a/src/Redis/RedisResource.php b/src/Redis/RedisResource.php index 8c4e769c1b..d4a6979751 100644 --- a/src/Redis/RedisResource.php +++ b/src/Redis/RedisResource.php @@ -9,17 +9,16 @@ class RedisResource extends BasePoolResource { - /** - * Redis 对象 - */ - private ?RedisHandler $redis = null; - /** * 连接配置. */ private array $config = []; - public function __construct(\Imi\Pool\Interfaces\IPool $pool, RedisHandler $redis, array $config) + public function __construct(\Imi\Pool\Interfaces\IPool $pool, + /** + * Redis 对象 + */ + private ?RedisHandler $redis, array $config) { parent::__construct($pool); @@ -31,8 +30,6 @@ public function __construct(\Imi\Pool\Interfaces\IPool $pool, RedisHandler $redi { $config['db'] = (int) $config['db']; } - - $this->redis = $redis; $this->config = $config; } diff --git a/src/Redis/Traits/TRedisPool.php b/src/Redis/Traits/TRedisPool.php index c9bd9ff757..902fc4b25b 100644 --- a/src/Redis/Traits/TRedisPool.php +++ b/src/Redis/Traits/TRedisPool.php @@ -39,7 +39,7 @@ protected function createResource(): \Imi\Pool\Interfaces\IPoolResource } else { - [$host, $port] = explode(':', $node); + [$host, $port] = explode(':', (string) $node); } $redisSentinel = new \RedisSentinel($host, $port, (float) ($config['timeout'] ?? 0), $config['persistent'] ?? false, (int) ($config['retryInterval'] ?? 0), (float) ($config['readTimeout'] ?? 0)); $masterArray = $redisSentinel->master($master); diff --git a/src/Server/ConnectionContext/StoreHandler/Local.php b/src/Server/ConnectionContext/StoreHandler/Local.php index 2bbce9f2aa..5ac6ae2448 100644 --- a/src/Server/ConnectionContext/StoreHandler/Local.php +++ b/src/Server/ConnectionContext/StoreHandler/Local.php @@ -49,7 +49,7 @@ public function __init(): void { if ($this->gcInteval > 0) { - Timer::tick((int) ($this->gcInteval * 1000), [$this, 'gc']); + Timer::tick((int) ($this->gcInteval * 1000), $this->gc(...)); } } @@ -86,7 +86,7 @@ public function destroy(string $key): void */ public function delayDestroy(string $key, int $ttl): void { - Timer::after($ttl * 1000, function () use ($key) { + Timer::after($ttl * 1000, function () use ($key): void { $this->destroy($key); }); } diff --git a/src/Server/ConnectionContext/StoreHandler/Redis.php b/src/Server/ConnectionContext/StoreHandler/Redis.php index dac04c38b5..1bc3540a20 100644 --- a/src/Server/ConnectionContext/StoreHandler/Redis.php +++ b/src/Server/ConnectionContext/StoreHandler/Redis.php @@ -95,7 +95,7 @@ public function __init(): void if (0 === $workerId) { - $this->useRedis(function (RedisHandler $redis) use ($masterPID) { + $this->useRedis(function (RedisHandler $redis) use ($masterPID): void { $this->initRedis($redis, $masterPID); $this->startPing($redis); }); @@ -147,8 +147,8 @@ private function startPing(RedisHandler $redis): void if ($this->ping($redis)) { // 心跳定时器 - $this->timerId = Timer::tick($this->heartbeatTimespan * 1000, [$this, 'pingTimer']); - Event::on('IMI.MAIN_SERVER.WORKER.EXIT', function () { + $this->timerId = Timer::tick($this->heartbeatTimespan * 1000, $this->pingTimer(...)); + Event::on('IMI.MAIN_SERVER.WORKER.EXIT', function (): void { if ($this->timerId) { Timer::del($this->timerId); @@ -163,7 +163,7 @@ private function startPing(RedisHandler $redis): void */ public function pingTimer(): void { - $this->useRedis(function (RedisHandler $redis) { + $this->useRedis(function (RedisHandler $redis): void { $this->ping($redis); }); } @@ -230,7 +230,7 @@ public function save(string $key, array $data): void { $data = ($this->dataEncode)($data); } - $this->useRedis(function (RedisHandler $redis) use ($key, $data) { + $this->useRedis(function (RedisHandler $redis) use ($key, $data): void { $redis->hSet($this->getStoreKey(), $key, $data); }); } @@ -240,7 +240,7 @@ public function save(string $key, array $data): void */ public function destroy(string $key): void { - $this->useRedis(function (RedisHandler $redis) use ($key) { + $this->useRedis(function (RedisHandler $redis) use ($key): void { $redis->hDel($this->getStoreKey(), $key); }); } @@ -325,12 +325,12 @@ public function unlock(): bool */ public function bind(string $flag, $clientId): void { - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); }); - $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId) { + $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId): void { $redis->hSet($this->key . ':binder', $flag, $clientId); }); } @@ -343,7 +343,7 @@ public function bindNx(string $flag, $clientId): bool $result = $this->useRedis(fn (RedisHandler $redis) => $redis->hSetNx($this->key . ':binder', $flag, $clientId)); if ($result) { - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); @@ -358,9 +358,9 @@ public function bindNx(string $flag, $clientId): bool */ public function unbind(string $flag, $clientId, ?int $keepTime = null): void { - $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId, $keepTime) { + $this->useRedis(function (RedisHandler $redis) use ($flag, $clientId, $keepTime): void { $key = $this->key . ':binder'; - $this->lock((string) $clientId, function () use ($flag, $clientId) { + $this->lock((string) $clientId, function () use ($flag, $clientId): void { $data = $this->read((string) $clientId); $data['__flag'] = $flag; $this->save((string) $clientId, $data); @@ -429,12 +429,12 @@ public function getOldClientIdByFlag(string $flag): ?int private function startDestroyTimer(): void { - Timer::tick(1000, function () { + Timer::tick(1000, function (): void { if ($keys = $this->destroyKeys) { $this->destroyKeys = []; $storeKey = $this->getStoreKey(); - $this->useRedis(static function (RedisHandler $redis) use ($keys, $storeKey) { + $this->useRedis(static function (RedisHandler $redis) use ($keys, $storeKey): void { foreach (array_chunk($keys, 1000) as $keysChunk) { $redis->hDel($storeKey, ...$keysChunk); diff --git a/src/Server/Contract/BaseServer.php b/src/Server/Contract/BaseServer.php index 07362fa0be..fac869f384 100644 --- a/src/Server/Contract/BaseServer.php +++ b/src/Server/Contract/BaseServer.php @@ -16,16 +16,6 @@ abstract class BaseServer implements IServer { use TEvent; - /** - * 服务器名称. - */ - protected string $name = ''; - - /** - * 服务器配置. - */ - protected array $config = []; - /** * 容器. */ @@ -34,11 +24,17 @@ abstract class BaseServer implements IServer /** * 构造方法. */ - public function __construct(string $name, array $config) + public function __construct( + /** + * 服务器名称. + */ + protected string $name, + /** + * 服务器配置. + */ + protected array $config) { $this->container = $container = App::getContainer()->newSubContainer(); - $this->name = $name; - $this->config = $config; $beans = $config['beans'] ?? []; if ($beans) { diff --git a/src/Server/Group/Group.php b/src/Server/Group/Group.php index 4454753639..5c428c0cbe 100644 --- a/src/Server/Group/Group.php +++ b/src/Server/Group/Group.php @@ -24,21 +24,6 @@ */ class Group { - /** - * 服务器对象 - */ - protected IServer $server; - - /** - * 组中最大允许的客户端数量. - */ - protected int $maxClients = 0; - - /** - * 组名. - */ - protected string $groupName = ''; - /** * 分组处理器. */ @@ -54,11 +39,20 @@ class Group */ protected bool $status = true; - public function __construct(IServer $server, string $groupName, int $maxClients = -1) - { - $this->server = $server; - $this->groupName = $groupName; - $this->maxClients = $maxClients; + public function __construct( + /** + * 服务器对象 + */ + protected IServer $server, + /** + * 组名. + */ + protected string $groupName, + /** + * 组中最大允许的客户端数量. + */ + protected int $maxClients = -1 + ) { } /** diff --git a/src/Server/Group/Handler/Redis.php b/src/Server/Group/Handler/Redis.php index 8fe4ad7626..9b65ec6e10 100644 --- a/src/Server/Group/Handler/Redis.php +++ b/src/Server/Group/Handler/Redis.php @@ -75,7 +75,7 @@ public function __init(): void $this->masterPID = $masterPID = Worker::getMasterPid(); if (0 === $workerId) { - $this->useRedis(function (RedisHandler $redis) use ($masterPID) { + $this->useRedis(function (RedisHandler $redis) use ($masterPID): void { $this->initRedis($redis, $masterPID); $this->startPing($redis); }); @@ -129,8 +129,8 @@ private function startPing(RedisHandler $redis): void if ($this->ping($redis)) { // 心跳定时器 - $this->timerId = Timer::tick($this->heartbeatTimespan * 1000, [$this, 'pingTimer']); - Event::on('IMI.MAIN_SERVER.WORKER.EXIT', function () { + $this->timerId = Timer::tick($this->heartbeatTimespan * 1000, $this->pingTimer(...)); + Event::on('IMI.MAIN_SERVER.WORKER.EXIT', function (): void { if ($this->timerId) { Timer::del($this->timerId); @@ -145,7 +145,7 @@ private function startPing(RedisHandler $redis): void */ public function pingTimer(): void { - $this->useRedis(function (RedisHandler $redis) { + $this->useRedis(function (RedisHandler $redis): void { $this->ping($redis); }); } @@ -190,7 +190,7 @@ public function createGroup(string $groupName, int $maxClients = -1): void $groups = &$this->groups; if (!isset($groups[$groupName])) { - $this->useRedis(function (RedisHandler $redis) use ($groupName) { + $this->useRedis(function (RedisHandler $redis) use ($groupName): void { $redis->sAdd($this->getGroupsKey(), $groupName); }); $groups[$groupName] = [ @@ -205,7 +205,7 @@ public function createGroup(string $groupName, int $maxClients = -1): void public function closeGroup(string $groupName): void { $key = $this->getGroupNameKey($groupName); - $this->useRedis(function (RedisHandler $redis) use ($key, $groupName) { + $this->useRedis(function (RedisHandler $redis) use ($key, $groupName): void { $redis->multi(); $redis->del($key); $redis->srem($this->getGroupsKey(), $groupName); @@ -293,7 +293,7 @@ public function count(string $groupName): int */ public function clear(): void { - $this->useRedis(function (RedisHandler $redis) { + $this->useRedis(function (RedisHandler $redis): void { $keys = []; $count = 0; foreach ($redis->scanEach($this->getGroupNameKey('*')) as $key) diff --git a/src/Server/Http/Error/ExecuteTimeoutHandler.php b/src/Server/Http/Error/ExecuteTimeoutHandler.php index a348c85f65..1648334e87 100644 --- a/src/Server/Http/Error/ExecuteTimeoutHandler.php +++ b/src/Server/Http/Error/ExecuteTimeoutHandler.php @@ -20,7 +20,7 @@ class ExecuteTimeoutHandler implements IExecuteTimeoutHandler /** * {@inheritDoc} */ - public function handle(IHttpRequest $request, IHttpResponse $response) + public function handle(IHttpRequest $request, IHttpResponse $response): void { $response->setStatus(StatusCode::INTERNAL_SERVER_ERROR)->setBody(new MemoryStream('

Request execute timeout

'))->send(); } diff --git a/src/Server/Http/Message/Emitter/SseMessageEvent.php b/src/Server/Http/Message/Emitter/SseMessageEvent.php index ee32ce00cc..db472e99ed 100644 --- a/src/Server/Http/Message/Emitter/SseMessageEvent.php +++ b/src/Server/Http/Message/Emitter/SseMessageEvent.php @@ -6,28 +6,8 @@ class SseMessageEvent implements \Stringable { - public ?string $data = null; - - public ?string $event = null; - - public ?string $id = null; - - public ?int $retry = null; - - public ?string $comment = null; - - public function __construct( - ?string $data = null, - ?string $event = null, - ?string $id = null, - ?int $retry = null, - ?string $comment = null - ) { - $this->id = $id; - $this->event = $event; - $this->data = $data; - $this->retry = $retry; - $this->comment = $comment; + public function __construct(public ?string $data = null, public ?string $event = null, public ?string $id = null, public ?int $retry = null, public ?string $comment = null) + { } public function __toString(): string diff --git a/src/Server/Http/Message/UploadedFile.php b/src/Server/Http/Message/UploadedFile.php index 1ba98936b1..0d58a924ab 100644 --- a/src/Server/Http/Message/UploadedFile.php +++ b/src/Server/Http/Message/UploadedFile.php @@ -10,31 +10,11 @@ class UploadedFile implements UploadedFileInterface { - /** - * 文件在客户端时的文件名. - */ - protected string $fileName = ''; - - /** - * 文件mime类型. - */ - protected string $mediaType = ''; - /** * 临时文件名. */ protected ?string $tmpFileName = null; - /** - * 文件大小,单位:字节 - */ - protected int $size = 0; - - /** - * 错误码 - */ - protected int $error = 0; - /** * 文件流 */ @@ -48,10 +28,24 @@ class UploadedFile implements UploadedFileInterface /** * @param string|StreamInterface $tmpFileName */ - public function __construct(string $fileName, string $mediaType, $tmpFileName, int $size, int $error) + public function __construct( + /** + * 文件在客户端时的文件名. + */ + protected string $fileName, + /** + * 文件mime类型. + */ + protected string $mediaType, $tmpFileName, + /** + * 文件大小,单位:字节 + */ + protected int $size, + /** + * 错误码 + */ + protected int $error) { - $this->fileName = $fileName; - $this->mediaType = $mediaType; if ($tmpFileName instanceof StreamInterface) { $this->stream = $tmpFileName; @@ -60,8 +54,6 @@ public function __construct(string $fileName, string $mediaType, $tmpFileName, i { $this->tmpFileName = $tmpFileName; } - $this->size = $size; - $this->error = $error; } /** diff --git a/src/Server/Http/RequestHandler.php b/src/Server/Http/RequestHandler.php index 0b0138e6a3..f59f9158cb 100644 --- a/src/Server/Http/RequestHandler.php +++ b/src/Server/Http/RequestHandler.php @@ -11,13 +11,6 @@ class RequestHandler implements RequestHandlerInterface { - /** - * 中间件数组. - * - * @var string[] - */ - protected array $middlewares = []; - /** * 当前执行第几个. */ @@ -28,9 +21,12 @@ class RequestHandler implements RequestHandlerInterface * * @param string[] $middlewares 中间件数组 */ - public function __construct(array $middlewares) - { - $this->middlewares = $middlewares; + public function __construct( + /** + * 中间件数组. + */ + protected array $middlewares + ) { } /** diff --git a/src/Server/Http/Route/Annotation/Route.php b/src/Server/Http/Route/Annotation/Route.php index 780f047a88..65dfa4c3eb 100644 --- a/src/Server/Http/Route/Annotation/Route.php +++ b/src/Server/Http/Route/Annotation/Route.php @@ -37,7 +37,7 @@ class Route extends Base implements \Stringable */ protected ?string $defaultFieldName = 'url'; - public function __toString() + public function __toString(): string { return http_build_query($this->toArray()); } diff --git a/src/Server/Http/Route/HttpRoute.php b/src/Server/Http/Route/HttpRoute.php index 224e324a18..9c2d6b0793 100644 --- a/src/Server/Http/Route/HttpRoute.php +++ b/src/Server/Http/Route/HttpRoute.php @@ -55,27 +55,27 @@ public function addRule(string $path, $callable, RouteAnnotation $annotation = n $checkCallables = []; if (null !== $annotation->paramsGet) { - $checkCallables[] = [self::class, 'checkParamsGet']; + $checkCallables[] = self::checkParamsGet(...); } if (null !== $annotation->paramsPost) { - $checkCallables[] = [self::class, 'checkParamsPost']; + $checkCallables[] = self::checkParamsPost(...); } if (null !== $annotation->paramsBody) { - $checkCallables[] = [self::class, 'checkParamsBody']; + $checkCallables[] = self::checkParamsBody(...); } if (null !== $annotation->header) { - $checkCallables[] = [self::class, 'checkHeader']; + $checkCallables[] = self::checkHeader(...); } if (null !== $annotation->requestMime) { - $checkCallables[] = [self::class, 'checkRequestMime']; + $checkCallables[] = self::checkRequestMime(...); } if (null !== $annotation->domain) { - $checkCallables[] = [self::class, 'checkDomain']; + $checkCallables[] = self::checkDomain(...); } if (null === $annotation) { diff --git a/src/Server/Http/Route/RouteItem.php b/src/Server/Http/Route/RouteItem.php index 688fbeb8a7..87d82470c2 100644 --- a/src/Server/Http/Route/RouteItem.php +++ b/src/Server/Http/Route/RouteItem.php @@ -11,11 +11,6 @@ class RouteItem { - /** - * 注解. - */ - public ?Route $annotation = null; - /** * 回调. * @@ -33,27 +28,24 @@ class RouteItem */ public ?WSConfig $wsConfig = null; - /** - * 其它配置项. - */ - public array $options = []; - - /** - * 视图注解. - */ - public ?View $view = null; - - /** - * 视图配置注解. - */ - public ?BaseViewOption $viewOption = null; - - public function __construct(Route $annotation, callable $callable, View $view, ?BaseViewOption $viewOption = null, array $options = []) + public function __construct( + /** + * 注解. + */ + public ?Route $annotation, callable $callable, + /** + * 视图注解. + */ + public ?View $view, + /** + * 视图配置注解. + */ + public ?BaseViewOption $viewOption = null, + /** + * 其它配置项. + */ + public array $options = []) { - $this->annotation = $annotation; $this->callable = $callable; - $this->view = $view; - $this->viewOption = $viewOption; - $this->options = $options; } } diff --git a/src/Server/Http/Route/RouteResult.php b/src/Server/Http/Route/RouteResult.php index f2b8103e53..cca607fda1 100644 --- a/src/Server/Http/Route/RouteResult.php +++ b/src/Server/Http/Route/RouteResult.php @@ -6,21 +6,6 @@ class RouteResult { - /** - * 路由ID. - */ - public int $id = 0; - - /** - * 路由配置项. - */ - public ?RouteItem $routeItem = null; - - /** - * 参数. - */ - public array $params = []; - /** * 回调. * @@ -28,11 +13,20 @@ class RouteResult */ public $callable; - public function __construct(int $id, RouteItem $routeItem, array $params) + public function __construct( + /** + * 路由ID. + */ + public int $id, + /** + * 路由配置项. + */ + public ?RouteItem $routeItem, + /** + * 参数. + */ + public array $params) { - $this->id = $id; - $this->routeItem = $routeItem; - $this->params = $params; $this->callable = $routeItem->callable; } } diff --git a/src/Server/Http/Route/Router.php b/src/Server/Http/Route/Router.php index 02c0b0cb2b..e6901f3097 100644 --- a/src/Server/Http/Route/Router.php +++ b/src/Server/Http/Route/Router.php @@ -102,7 +102,7 @@ public function dispatchRoutes(ServerRequestInterface $request, array $routes, b if ($route[self::ROUTE_CASE_INSENSITIVE]) { // @phpstan-ignore-next-line - if (0 !== strcasecmp($requestPath, $route[self::ROUTE_PATH])) + if (0 !== strcasecmp($requestPath, (string) $route[self::ROUTE_PATH])) { continue; } diff --git a/src/Server/Http/Struct/ActionMethodItem.php b/src/Server/Http/Struct/ActionMethodItem.php index 9b3ada2627..3c8f39a256 100644 --- a/src/Server/Http/Struct/ActionMethodItem.php +++ b/src/Server/Http/Struct/ActionMethodItem.php @@ -6,28 +6,6 @@ class ActionMethodItem { - /** - * 参数名. - */ - protected string $name = ''; - - /** - * 是否有默认值 - */ - protected bool $hasDefault = false; - - /** - * 默认值 - * - * @var mixed - */ - protected $default = null; - - /** - * 是否允许为 null. - */ - protected bool $allowNull = false; - /** * 类型. */ @@ -36,12 +14,24 @@ class ActionMethodItem /** * @param mixed $default */ - public function __construct(string $name, bool $hasDefault, $default, bool $allowNull, ?\ReflectionType $type) + public function __construct( + /** + * 参数名. + */ + protected string $name, + /** + * 是否有默认值 + */ + protected bool $hasDefault, + /** + * 默认值 + */ + protected $default, + /** + * 是否允许为 null. + */ + protected bool $allowNull, ?\ReflectionType $type) { - $this->name = $name; - $this->hasDefault = $hasDefault; - $this->default = $default; - $this->allowNull = $allowNull; if ($type instanceof \ReflectionNamedType) { $this->type = $type->getName(); diff --git a/src/Server/Http/SuperGlobals/Server.php b/src/Server/Http/SuperGlobals/Server.php index 95eacd0466..3cd180f973 100644 --- a/src/Server/Http/SuperGlobals/Server.php +++ b/src/Server/Http/SuperGlobals/Server.php @@ -9,14 +9,12 @@ class Server implements \ArrayAccess, \JsonSerializable { - /** - * 默认的 $_SERVER 变量. - */ - private array $defaultServer = []; - - public function __construct(array $defaultServer) - { - $this->defaultServer = $defaultServer; + public function __construct( + /** + * 默认的 $_SERVER 变量. + */ + private array $defaultServer + ) { } /** diff --git a/src/Server/Session/Handler/Redis.php b/src/Server/Session/Handler/Redis.php index fc988b908d..224f2bc0e6 100644 --- a/src/Server/Session/Handler/Redis.php +++ b/src/Server/Session/Handler/Redis.php @@ -37,7 +37,7 @@ public function __init(): void */ public function destroy(string $sessionId): void { - ImiRedis::use(function (\Imi\Redis\RedisHandler $redis) use ($sessionId) { + ImiRedis::use(function (\Imi\Redis\RedisHandler $redis) use ($sessionId): void { $redis->del($this->getKey($sessionId)); }, $this->poolName, true); } @@ -63,7 +63,7 @@ public function read(string $sessionId): string */ public function write(string $sessionId, string $sessionData, int $maxLifeTime): void { - ImiRedis::use(function (\Imi\Redis\RedisHandler $redis) use ($sessionId, $sessionData, $maxLifeTime) { + ImiRedis::use(function (\Imi\Redis\RedisHandler $redis) use ($sessionId, $sessionData, $maxLifeTime): void { $redis->set($this->getKey($sessionId), $sessionData, $maxLifeTime); }, $this->poolName, true); } diff --git a/src/Server/Session/SessionConfig.php b/src/Server/Session/SessionConfig.php index 13477354cd..cc0940ec9b 100644 --- a/src/Server/Session/SessionConfig.php +++ b/src/Server/Session/SessionConfig.php @@ -12,41 +12,33 @@ */ class SessionConfig { - /** - * session名称. - */ - public string $name = ''; - /** * @ServerInject("SessionCookie") */ public SessionCookie $cookie; - /** - * 每次请求完成后触发垃圾回收的概率,默认为1% - * 可取值0~1.0,概率为0%~100%. - */ - public float $gcProbability = 0; - - /** - * 最大存活时间,默认30天,单位秒. - */ - public int $maxLifeTime = 0; - - /** - * Session 前缀 - */ - public ?string $prefix = null; - - public function __construct(string $name = 'imisid', ?SessionCookie $cookie = null, float $gcProbability = 0.01, int $maxLifeTime = 86400 * 30, ?string $prefix = null) + public function __construct( + /** + * session名称. + */ + public string $name = 'imisid', ?SessionCookie $cookie = null, + /** + * 每次请求完成后触发垃圾回收的概率,默认为1% + * 可取值0~1.0,概率为0%~100%. + */ + public float $gcProbability = 0.01, + /** + * 最大存活时间,默认30天,单位秒. + */ + public int $maxLifeTime = 86400 * 30, + /** + * Session 前缀 + */ + public ?string $prefix = null) { - $this->name = $name; if (null !== $cookie) { $this->cookie = $cookie; } - $this->gcProbability = $gcProbability; - $this->maxLifeTime = $maxLifeTime; - $this->prefix = $prefix; } } diff --git a/src/Server/Session/SessionCookie.php b/src/Server/Session/SessionCookie.php index 16a59ea40d..1e81838da6 100644 --- a/src/Server/Session/SessionCookie.php +++ b/src/Server/Session/SessionCookie.php @@ -11,42 +11,32 @@ */ class SessionCookie { - /** - * Cookie 的 生命周期,以秒为单位。 - */ - public int $lifetime = 0; - - /** - * 此 cookie 的有效路径。 on the domain where 设置为“/”表示对于本域上所有的路径此 cookie 都可用。 - */ - public string $path = ''; - - /** - * Cookie 的作用域。 例如:“www.php.net”。 如果要让 cookie 在所有的子域中都可用,此参数必须以点(.)开头,例如:“.php.net”。 - */ - public string $domain = ''; - - /** - * 设置为 TRUE 表示 cookie 仅在使用安全链接时可用。 - */ - public bool $secure = false; - - /** - * 设置为 TRUE 表示 PHP 发送 cookie 的时候会使用 httponly 标记。 - */ - public bool $httponly = false; - /** * 是否启用 Cookie. */ public bool $enable = true; - public function __construct(int $lifetime = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = false) - { - $this->lifetime = $lifetime; - $this->path = $path; - $this->domain = $domain; - $this->secure = $secure; - $this->httponly = $httponly; + public function __construct( + /** + * Cookie 的 生命周期,以秒为单位。 + */ + public int $lifetime = 0, + /** + * 此 cookie 的有效路径。 on the domain where 设置为“/”表示对于本域上所有的路径此 cookie 都可用。 + */ + public string $path = '/', + /** + * Cookie 的作用域。 例如:“www.php.net”。 如果要让 cookie 在所有的子域中都可用,此参数必须以点(.)开头,例如:“.php.net”。 + */ + public string $domain = '', + /** + * 设置为 TRUE 表示 cookie 仅在使用安全链接时可用。 + */ + public bool $secure = false, + /** + * 设置为 TRUE 表示 PHP 发送 cookie 的时候会使用 httponly 标记。 + */ + public bool $httponly = false + ) { } } diff --git a/src/Server/TcpServer/Message/ReceiveData.php b/src/Server/TcpServer/Message/ReceiveData.php index 49e675e612..50143553ef 100644 --- a/src/Server/TcpServer/Message/ReceiveData.php +++ b/src/Server/TcpServer/Message/ReceiveData.php @@ -10,18 +10,6 @@ class ReceiveData implements IReceiveData { - /** - * 客户端连接的标识符. - * - * @var int|string - */ - protected $clientId = 0; - - /** - * 接收到的数据. - */ - protected string $data = ''; - /** * 接收到的数据. * @@ -37,10 +25,16 @@ class ReceiveData implements IReceiveData /** * @param int|string $clientId */ - public function __construct($clientId, string $data) + public function __construct( + /** + * 客户端连接的标识符. + */ + protected $clientId, + /** + * 接收到的数据. + */ + protected string $data) { - $this->clientId = $clientId; - $this->data = $data; $this->formatData = RequestContext::getServerBean(DataParser::class)->decode($data); } diff --git a/src/Server/TcpServer/ReceiveHandler.php b/src/Server/TcpServer/ReceiveHandler.php index 26e0938118..82ce163344 100644 --- a/src/Server/TcpServer/ReceiveHandler.php +++ b/src/Server/TcpServer/ReceiveHandler.php @@ -9,13 +9,6 @@ class ReceiveHandler implements IReceiveHandler { - /** - * 中间件数组. - * - * @var string[]|\Imi\Server\TcpServer\Middleware\IMiddleware[] - */ - protected array $middlewares = []; - /** * 当前执行第几个. */ @@ -23,12 +16,13 @@ class ReceiveHandler implements IReceiveHandler /** * 构造方法. - * - * @param string[] $middlewares 中间件数组 */ - public function __construct(array $middlewares) - { - $this->middlewares = $middlewares; + public function __construct( + /** + * @var array 中间件数组 + */ + protected array $middlewares + ) { } /** diff --git a/src/Server/TcpServer/Route/Annotation/TcpRoute.php b/src/Server/TcpServer/Route/Annotation/TcpRoute.php index d0c671b0af..8adc307a63 100644 --- a/src/Server/TcpServer/Route/Annotation/TcpRoute.php +++ b/src/Server/TcpServer/Route/Annotation/TcpRoute.php @@ -26,7 +26,7 @@ class TcpRoute extends Base implements \Stringable */ protected ?string $defaultFieldName = 'condition'; - public function __toString() + public function __toString(): string { return http_build_query($this->toArray()); } diff --git a/src/Server/TcpServer/Route/RouteItem.php b/src/Server/TcpServer/Route/RouteItem.php index 8039b2786e..a7b08cc0d9 100644 --- a/src/Server/TcpServer/Route/RouteItem.php +++ b/src/Server/TcpServer/Route/RouteItem.php @@ -8,11 +8,6 @@ class RouteItem { - /** - * 注解. - */ - public ?TcpRoute $annotation = null; - /** * 回调. * @@ -25,15 +20,16 @@ class RouteItem */ public array $middlewares = []; - /** - * 其它配置项. - */ - public array $options = []; - - public function __construct(TcpRoute $annotation, callable $callable, array $options = []) + public function __construct( + /** + * 注解. + */ + public ?TcpRoute $annotation, callable $callable, + /** + * 其它配置项. + */ + public array $options = []) { - $this->annotation = $annotation; $this->callable = $callable; - $this->options = $options; } } diff --git a/src/Server/TcpServer/Route/RouteResult.php b/src/Server/TcpServer/Route/RouteResult.php index 28bd4fffb2..b2b5eedb54 100644 --- a/src/Server/TcpServer/Route/RouteResult.php +++ b/src/Server/TcpServer/Route/RouteResult.php @@ -6,16 +6,6 @@ class RouteResult { - /** - * 路由配置项. - */ - public RouteItem $routeItem; - - /** - * 参数. - */ - public array $params = []; - /** * 回调. * @@ -23,10 +13,16 @@ class RouteResult */ public $callable; - public function __construct(RouteItem $routeItem, array $params = []) + public function __construct( + /** + * 路由配置项. + */ + public RouteItem $routeItem, + /** + * 参数. + */ + public array $params = []) { - $this->routeItem = $routeItem; - $this->params = $params; $this->callable = $routeItem->callable; } } diff --git a/src/Server/UdpServer/Message/PacketData.php b/src/Server/UdpServer/Message/PacketData.php index 8c25db4946..f564b0bdde 100644 --- a/src/Server/UdpServer/Message/PacketData.php +++ b/src/Server/UdpServer/Message/PacketData.php @@ -15,11 +15,6 @@ class PacketData implements IPacketData */ protected ?IPEndPoint $clientAddress = null; - /** - * 数据内容. - */ - protected string $data = ''; - /** * 接收到的数据. * @@ -27,10 +22,13 @@ class PacketData implements IPacketData */ protected $formatData; - public function __construct(string $remoteIp, int $remotePort, string $data) + public function __construct(string $remoteIp, int $remotePort, + /** + * 数据内容. + */ + protected string $data) { $this->clientAddress = new IPEndPoint($remoteIp, $remotePort); - $this->data = $data; $this->formatData = RequestContext::getServerBean(DataParser::class)->decode($data); } diff --git a/src/Server/UdpServer/PacketHandler.php b/src/Server/UdpServer/PacketHandler.php index cf5524541d..f2c823b616 100644 --- a/src/Server/UdpServer/PacketHandler.php +++ b/src/Server/UdpServer/PacketHandler.php @@ -9,13 +9,6 @@ class PacketHandler implements IPacketHandler { - /** - * 中间件数组. - * - * @var string[]|\Imi\Server\UdpServer\Middleware\IMiddleware[] - */ - protected array $middlewares = []; - /** * 当前执行第几个. */ @@ -23,12 +16,13 @@ class PacketHandler implements IPacketHandler /** * 构造方法. - * - * @param string[] $middlewares 中间件数组 */ - public function __construct(array $middlewares) - { - $this->middlewares = $middlewares; + public function __construct( + /** + * @var array 中间件数组 + */ + protected array $middlewares + ) { } /** diff --git a/src/Server/UdpServer/Route/Annotation/UdpRoute.php b/src/Server/UdpServer/Route/Annotation/UdpRoute.php index 7c954bc667..bf1a7cef3b 100644 --- a/src/Server/UdpServer/Route/Annotation/UdpRoute.php +++ b/src/Server/UdpServer/Route/Annotation/UdpRoute.php @@ -26,7 +26,7 @@ class UdpRoute extends Base implements \Stringable */ protected ?string $defaultFieldName = 'condition'; - public function __toString() + public function __toString(): string { return http_build_query($this->toArray()); } diff --git a/src/Server/UdpServer/Route/RouteItem.php b/src/Server/UdpServer/Route/RouteItem.php index 2e5c8bfa2d..b75f62f367 100644 --- a/src/Server/UdpServer/Route/RouteItem.php +++ b/src/Server/UdpServer/Route/RouteItem.php @@ -8,11 +8,6 @@ class RouteItem { - /** - * 注解. - */ - public ?UdpRoute $annotation = null; - /** * 回调. * @@ -25,15 +20,16 @@ class RouteItem */ public array $middlewares = []; - /** - * 其它配置项. - */ - public array $options = []; - - public function __construct(UdpRoute $annotation, callable $callable, array $options = []) + public function __construct( + /** + * 注解. + */ + public ?UdpRoute $annotation, callable $callable, + /** + * 其它配置项. + */ + public array $options = []) { - $this->annotation = $annotation; $this->callable = $callable; - $this->options = $options; } } diff --git a/src/Server/UdpServer/Route/RouteResult.php b/src/Server/UdpServer/Route/RouteResult.php index 37e33fc590..6731ea7db2 100644 --- a/src/Server/UdpServer/Route/RouteResult.php +++ b/src/Server/UdpServer/Route/RouteResult.php @@ -6,16 +6,6 @@ class RouteResult { - /** - * 路由配置项. - */ - public RouteItem $routeItem; - - /** - * 参数. - */ - public array $params = []; - /** * 回调. * @@ -23,10 +13,16 @@ class RouteResult */ public $callable; - public function __construct(RouteItem $routeItem, array $params = []) + public function __construct( + /** + * 路由配置项. + */ + public RouteItem $routeItem, + /** + * 参数. + */ + public array $params = []) { - $this->routeItem = $routeItem; - $this->params = $params; $this->callable = $routeItem->callable; } } diff --git a/src/Server/View/Engine/Php.php b/src/Server/View/Engine/Php.php index f8b0771db3..294c255414 100644 --- a/src/Server/View/Engine/Php.php +++ b/src/Server/View/Engine/Php.php @@ -20,7 +20,7 @@ public function render(IHttpResponse $response, string $fileName, array $data = { return $response; } - $closure = static function (string $__renderFileName, $__renderData) { + $closure = static function (string $__renderFileName, $__renderData): void { if (\is_array($__renderData)) { extract($__renderData); diff --git a/src/Server/WebSocket/Message/Frame.php b/src/Server/WebSocket/Message/Frame.php index 20206b8eac..ccf8b59bbe 100644 --- a/src/Server/WebSocket/Message/Frame.php +++ b/src/Server/WebSocket/Message/Frame.php @@ -10,30 +10,6 @@ class Frame implements IFrame { - /** - * 客户端的socket id. - * - * @var int|string - */ - protected $clientId; - - /** - * 数据内容,可以是文本内容也可以是二进制数据,可以通过opcode的值来判断. - */ - protected string $data = ''; - - /** - * WebSocket的OpCode类型,可以参考WebSocket协议标准文档 - * WEBSOCKET_OPCODE_TEXT = 0x1 ,文本数据 - * WEBSOCKET_OPCODE_BINARY = 0x2 ,二进制数据. - */ - protected int $opcode = 0; - - /** - * 表示数据帧是否完整. - */ - protected bool $finish = false; - /** * 格式化后的数据. * @@ -49,12 +25,26 @@ class Frame implements IFrame /** * @param int|string $clientId */ - public function __construct(string $data, $clientId, int $opcode = 1, bool $finish = true) + public function __construct( + /** + * 数据内容,可以是文本内容也可以是二进制数据,可以通过opcode的值来判断. + */ + protected string $data, + /** + * 客户端的socket id. + */ + protected $clientId, + /** + * WebSocket的OpCode类型,可以参考WebSocket协议标准文档 + * WEBSOCKET_OPCODE_TEXT = 0x1 ,文本数据 + * WEBSOCKET_OPCODE_BINARY = 0x2 ,二进制数据. + */ + protected int $opcode = 1, + /** + * 表示数据帧是否完整. + */ + protected bool $finish = true) { - $this->data = $data; - $this->clientId = $clientId; - $this->opcode = $opcode; - $this->finish = $finish; $this->formatData = RequestContext::getServerBean(DataParser::class)->decode($data); } diff --git a/src/Server/WebSocket/MessageHandler.php b/src/Server/WebSocket/MessageHandler.php index aed1e9d8c0..bcdbd03a8f 100644 --- a/src/Server/WebSocket/MessageHandler.php +++ b/src/Server/WebSocket/MessageHandler.php @@ -9,13 +9,6 @@ class MessageHandler implements IMessageHandler { - /** - * 中间件数组. - * - * @var string[]|\Psr\Http\Server\MiddlewareInterface[] - */ - protected array $middlewares = []; - /** * 当前执行第几个. */ @@ -23,12 +16,13 @@ class MessageHandler implements IMessageHandler /** * 构造方法. - * - * @param string[] $middlewares 中间件数组 */ - public function __construct(array $middlewares) - { - $this->middlewares = $middlewares; + public function __construct( + /** + * @var array 中间件数组 + */ + protected array $middlewares + ) { } /** diff --git a/src/Server/WebSocket/Route/Annotation/WSRoute.php b/src/Server/WebSocket/Route/Annotation/WSRoute.php index a73985ccc0..306b593a38 100644 --- a/src/Server/WebSocket/Route/Annotation/WSRoute.php +++ b/src/Server/WebSocket/Route/Annotation/WSRoute.php @@ -27,7 +27,7 @@ class WSRoute extends Base implements \Stringable */ protected ?string $defaultFieldName = 'condition'; - public function __toString() + public function __toString(): string { return http_build_query($this->toArray()); } diff --git a/src/Server/WebSocket/Route/RouteItem.php b/src/Server/WebSocket/Route/RouteItem.php index b0c9cf31eb..a2e1c246d3 100644 --- a/src/Server/WebSocket/Route/RouteItem.php +++ b/src/Server/WebSocket/Route/RouteItem.php @@ -8,11 +8,6 @@ class RouteItem { - /** - * 注解. - */ - public ?WSRoute $annotation = null; - /** * 回调. * @@ -25,15 +20,16 @@ class RouteItem */ public array $middlewares = []; - /** - * 其它配置项. - */ - public array $options = []; - - public function __construct(WSRoute $annotation, callable $callable, array $options = []) + public function __construct( + /** + * 注解. + */ + public ?WSRoute $annotation, callable $callable, + /** + * 其它配置项. + */ + public array $options = []) { - $this->annotation = $annotation; $this->callable = $callable; - $this->options = $options; } } diff --git a/src/Server/WebSocket/Route/RouteResult.php b/src/Server/WebSocket/Route/RouteResult.php index 83f619cbeb..f41eeaac10 100644 --- a/src/Server/WebSocket/Route/RouteResult.php +++ b/src/Server/WebSocket/Route/RouteResult.php @@ -6,16 +6,6 @@ class RouteResult { - /** - * 路由配置项. - */ - public ?RouteItem $routeItem = null; - - /** - * 参数. - */ - public array $params = []; - /** * 回调. * @@ -23,10 +13,16 @@ class RouteResult */ public $callable; - public function __construct(RouteItem $routeItem, array $params = []) + public function __construct( + /** + * 路由配置项. + */ + public ?RouteItem $routeItem, + /** + * 参数. + */ + public array $params = []) { - $this->routeItem = $routeItem; - $this->params = $params; $this->callable = $routeItem->callable; } } diff --git a/src/Util/ArrayData.php b/src/Util/ArrayData.php index e7e0acbc69..45caf45b85 100644 --- a/src/Util/ArrayData.php +++ b/src/Util/ArrayData.php @@ -9,14 +9,12 @@ */ class ArrayData implements \ArrayAccess, \Countable { - /** - * 数据. - */ - protected array $__data = []; - - public function __construct(array $data) - { - $this->__data = $data; + public function __construct( + /** + * 数据. + */ + protected array $__data + ) { } /** @@ -249,7 +247,7 @@ public function __isset($key): bool /** * @param mixed $key */ - public function __unset($key) + public function __unset($key): void { $this->remove($key); } diff --git a/src/Util/ArrayList.php b/src/Util/ArrayList.php index 927cfc7090..1d8010969b 100644 --- a/src/Util/ArrayList.php +++ b/src/Util/ArrayList.php @@ -11,19 +11,17 @@ */ class ArrayList implements \Iterator, \ArrayAccess, IArrayable, \JsonSerializable, \Countable { - /** - * 限定的数组列表成员类型. - */ - private string $itemType = ''; - /** * 数组列表. */ private array $list = []; - public function __construct(string $itemType, array $list = []) + public function __construct( + /** + * 限定的数组列表成员类型. + */ + private readonly string $itemType, array $list = []) { - $this->itemType = $itemType; if ($list) { foreach ($list as $item) @@ -71,7 +69,7 @@ public function offsetSet($offset, $value): void if (!$value instanceof $this->itemType) { $type = \gettype($value); - throw new \InvalidArgumentException('ArrayList item must be an instance of ' . $this->itemType . ', ' . ('object' === $type ? \get_class($value) : $type) . ' given'); + throw new \InvalidArgumentException('ArrayList item must be an instance of ' . $this->itemType . ', ' . ('object' === $type ? $value::class : $type) . ' given'); } if (null === $offset) { diff --git a/src/Util/ClassObject.php b/src/Util/ClassObject.php index 1c2b9ef5d9..d5ae7ab542 100644 --- a/src/Util/ClassObject.php +++ b/src/Util/ClassObject.php @@ -22,7 +22,7 @@ public static function isAnymous($object): bool { if (!\is_string($object)) { - $object = \get_class($object); + $object = $object::class; } return str_contains($object, 'class@anonymous'); diff --git a/src/Util/DelayBeanCallable.php b/src/Util/DelayBeanCallable.php index 2fdf2ad583..34c2fe6eb3 100644 --- a/src/Util/DelayBeanCallable.php +++ b/src/Util/DelayBeanCallable.php @@ -10,21 +10,12 @@ class DelayBeanCallable { - private string $beanName = ''; - - private string $methodName = ''; - - private array $constructArgs = []; - private ?bool $returnsReference = null; private ?object $instance = null; - public function __construct(string $beanName, string $methodName, array $constructArgs = []) + public function __construct(private readonly string $beanName, private readonly string $methodName, private readonly array $constructArgs = []) { - $this->beanName = $beanName; - $this->methodName = $methodName; - $this->constructArgs = $constructArgs; } public function getBeanName(): string diff --git a/src/Util/DelayClassCallable.php b/src/Util/DelayClassCallable.php index c845cf621d..6a7719aa60 100644 --- a/src/Util/DelayClassCallable.php +++ b/src/Util/DelayClassCallable.php @@ -9,21 +9,12 @@ class DelayClassCallable { - private string $className = ''; - - private string $methodName = ''; - - private array $constructArgs = []; - private ?bool $returnsReference = null; private ?object $instance = null; - public function __construct(string $className, string $methodName, array $constructArgs = []) + public function __construct(private readonly string $className, private readonly string $methodName, private readonly array $constructArgs = []) { - $this->className = $className; - $this->methodName = $methodName; - $this->constructArgs = $constructArgs; } public function getClassName(): string diff --git a/src/Util/DelayServerBeanCallable.php b/src/Util/DelayServerBeanCallable.php index 2523f9fd11..a9b5998fd5 100644 --- a/src/Util/DelayServerBeanCallable.php +++ b/src/Util/DelayServerBeanCallable.php @@ -15,12 +15,6 @@ class DelayServerBeanCallable private ?IServer $serverInstance = null; - private string $beanName = ''; - - private string $methodName = ''; - - private array $constructArgs = []; - private ?bool $returnsReference = null; private ?object $instance = null; @@ -28,7 +22,7 @@ class DelayServerBeanCallable /** * @param string|IServer $server */ - public function __construct($server, string $beanName, string $methodName, array $constructArgs = []) + public function __construct($server, private readonly string $beanName, private readonly string $methodName, private readonly array $constructArgs = []) { if (\is_string($server)) { @@ -40,9 +34,6 @@ public function __construct($server, string $beanName, string $methodName, array $this->server = $server->getName(); $this->serverInstance = $server; } - $this->beanName = $beanName; - $this->methodName = $methodName; - $this->constructArgs = $constructArgs; } public function getBeanName(): string diff --git a/src/Util/File.php b/src/Util/File.php index bd2631272d..cd04b61a13 100644 --- a/src/Util/File.php +++ b/src/Util/File.php @@ -79,7 +79,7 @@ public static function enumFile(string $dirPath, ?string $pattern = null, array && \Swoole\Coroutine::getCid() > -1) { $channel = new \Swoole\Coroutine\Channel(16); - Coroutine::create(static function () use ($channel, $dirPath, $pattern, $extensionNames) { + Coroutine::create(static function () use ($channel, $dirPath, $pattern, $extensionNames): void { if (false === static::enumFileSwoole($channel, $dirPath, $pattern, $extensionNames)) { $channel->push(false); @@ -234,7 +234,7 @@ public static function readAll($fp): string * @param string $dir 目录路径 * @param int $mode 目录的权限 */ - public static function createDir(string $dir, int $mode = 0775): bool + public static function createDir(string $dir, int $mode = 0o775): bool { if ('' === $dir) { @@ -260,7 +260,7 @@ public static function createDir(string $dir, int $mode = 0775): bool * @param string $file 文件路径 * @param int $mode 文件的权限 */ - public static function createFile(string $file, string $content = '', int $mode = 0775): bool + public static function createFile(string $file, string $content = '', int $mode = 0o775): bool { if ('' === $file) { @@ -307,7 +307,7 @@ public static function isEmptyDir(string $dir): bool } } } - catch (\ErrorException $_) + catch (\ErrorException) { // 兼容警告转异常 return true; diff --git a/src/Util/File/FileEnumItem.php b/src/Util/File/FileEnumItem.php index afa9ede590..c56f6268b2 100644 --- a/src/Util/File/FileEnumItem.php +++ b/src/Util/File/FileEnumItem.php @@ -8,16 +8,6 @@ class FileEnumItem implements \Stringable { - /** - * 路径. - */ - private string $path = ''; - - /** - * 文件名. - */ - private string $fileName = ''; - /** * 完整路径. */ @@ -28,10 +18,16 @@ class FileEnumItem implements \Stringable */ private bool $continue = true; - public function __construct(string $path, string $fileName) + public function __construct( + /** + * 路径. + */ + private readonly string $path, + /** + * 文件名. + */ + private readonly string $fileName) { - $this->path = $path; - $this->fileName = $fileName; $this->fullPath = File::path($path, $fileName); } diff --git a/src/Util/FilterableList.php b/src/Util/FilterableList.php index 12595da098..f6232b99aa 100644 --- a/src/Util/FilterableList.php +++ b/src/Util/FilterableList.php @@ -11,31 +11,27 @@ */ class FilterableList implements \Iterator, \ArrayAccess, IArrayable, \JsonSerializable, \Countable { - /** - * 模式 - * allow-白名单 - * deny-黑名单. - */ - private string $mode = ''; - - /** - * 字段名数组. - * - * 为null则不过滤 - * - * @var string[]|null - */ - private ?array $fields = null; - /** * 数组列表. */ private array $list = []; - public function __construct(array $list = [], ?array $fields = null, string $mode = 'allow') + public function __construct(array $list = [], + /** + * 字段名数组. + * + * 为null则不过滤 + * + * @var string[]|null + */ + private readonly ?array $fields = null, + /** + * 模式 + * allow-白名单 + * deny-黑名单. + */ + private readonly string $mode = 'allow') { - $this->mode = $mode; - $this->fields = $fields; $this->list = $this->parseList($list); } diff --git a/src/Util/Imi.php b/src/Util/Imi.php index b2044edf47..049f8a2097 100644 --- a/src/Util/Imi.php +++ b/src/Util/Imi.php @@ -107,16 +107,13 @@ public static function checkCompareRule(string $rule, callable $valueCallback): elseif (preg_match('/([^!<=]+)(!=|<>|=)(.+)/', $rule, $matches) > 0) { $value = $valueCallback($matches[1]); - switch ($matches[2]) + + return match ($matches[2]) { - case '!=': - case '<>': - return null !== $value && $value != $matches[3]; - case '=': - return $value == $matches[3]; - default: - return false; // @codeCoverageIgnore - } + '!=', '<>' => null !== $value && $value != $matches[3], + '=' => $value == $matches[3], + default => false, + }; } else { @@ -249,7 +246,7 @@ public static function getNamespacePath(string $namespace, bool $returnFirst = f if (str_starts_with($namespace, $mainNamespace)) { $namespaceSubPath = substr($namespace, $len); - $refClass = ReflectionContainer::getClassReflection(\get_class($main)); + $refClass = ReflectionContainer::getClassReflection($main::class); $path = \dirname($refClass->getFileName()); $result = File::path($path, str_replace('\\', \DIRECTORY_SEPARATOR, $namespaceSubPath)); if (is_dir($result)) @@ -313,7 +310,7 @@ public static function getNamespacePaths(string $namespace): array if (str_starts_with($namespace, $mainNamespace)) { $namespaceSubPath = substr($namespace, $len); - $refClass = ReflectionContainer::getClassReflection(\get_class($main)); + $refClass = ReflectionContainer::getClassReflection($main::class); $path = \dirname($refClass->getFileName()); $resultPaths[] = File::path($path, str_replace('\\', \DIRECTORY_SEPARATOR, $namespaceSubPath)); } @@ -356,7 +353,7 @@ public static function getClassPropertyValue(string $className, string $property */ public static function getImiCmd(string $commandName, array $arguments = [], array $options = []): string { - $cmd = '"' . \PHP_BINARY . '" ' . escapeshellarg(App::get(ProcessAppContexts::SCRIPT_NAME) ?? realpath($_SERVER['SCRIPT_FILENAME'])) . ' ' . escapeshellarg($commandName); + $cmd = '"' . \PHP_BINARY . '" ' . escapeshellarg((string) (App::get(ProcessAppContexts::SCRIPT_NAME) ?? realpath($_SERVER['SCRIPT_FILENAME']))) . ' ' . escapeshellarg($commandName); $options['app-namespace'] ??= App::getNamespace(); if ($arguments) { @@ -489,7 +486,7 @@ public static function buildRuntime(?string $cacheName = null): void } if (!is_dir($cacheName)) { - mkdir($cacheName, 0775, true); + mkdir($cacheName, 0o775, true); } $data = []; $data['imiVersion'] = App::getImiVersion(); @@ -590,7 +587,7 @@ public static function eval(string $code, ?string $fileName = null, bool $delete $tmpPath = self::getCurrentModeRuntimePath('tmp'); if (!is_dir($tmpPath)) { - mkdir($tmpPath, 0755, true); + mkdir($tmpPath, 0o755, true); } } } @@ -672,7 +669,7 @@ public static function getLinuxVersion(): string break; } } - $result = trim($name, '"'); + $result = trim((string) $name, '"'); if (isset($matches['version'])) { $version = ''; @@ -685,7 +682,7 @@ public static function getLinuxVersion(): string } if ('' !== $version) { - $result .= ' ' . trim($version, '"'); + $result .= ' ' . trim((string) $version, '"'); } } diff --git a/src/Util/Pagination.php b/src/Util/Pagination.php index d177694394..182c33ee96 100644 --- a/src/Util/Pagination.php +++ b/src/Util/Pagination.php @@ -9,16 +9,6 @@ */ class Pagination { - /** - * 当前页码 - */ - private int $page = 0; - - /** - * 每页显示数量. - */ - private int $count = 0; - /** * 偏移量. */ @@ -29,10 +19,16 @@ class Pagination */ private int $limitEndOffset = 0; - public function __construct(int $page, int $count) + public function __construct( + /** + * 当前页码 + */ + private int $page, + /** + * 每页显示数量. + */ + private int $count) { - $this->page = $page; - $this->count = $count; $this->calc(); } diff --git a/src/Util/Random.php b/src/Util/Random.php index cc2325313d..27eefb307b 100644 --- a/src/Util/Random.php +++ b/src/Util/Random.php @@ -26,7 +26,7 @@ public static function int(int $min = \PHP_INT_MIN, int $max = \PHP_INT_MAX): in */ public static function float(float $min = \PHP_INT_MIN, float $max = \PHP_INT_MAX, ?int $precision = null): float { - $result = $min + mt_rand() / mt_getrandmax() * ($max - $min); + $result = $min + random_int(0, mt_getrandmax()) / mt_getrandmax() * ($max - $min); if (null !== $precision) { return round($result, $precision); @@ -50,12 +50,12 @@ public static function number(float $min = \PHP_INT_MIN, float $max = \PHP_INT_M */ public static function text(string $chars, int $min, ?int $max = null): string { - $length = mt_rand($min, $max ?? $min); + $length = random_int($min, $max ?? $min); $charLength = mb_strlen($chars); $result = ''; for ($i = 0; $i < $length; ++$i) { - $result .= mb_substr($chars, mt_rand(1, $charLength) - 1, 1); + $result .= mb_substr($chars, random_int(1, $charLength) - 1, 1); } return $result; @@ -66,12 +66,12 @@ public static function text(string $chars, int $min, ?int $max = null): string */ public static function bytes(string $bytes, int $min, ?int $max = null): string { - $length = mt_rand($min, $max ?? $min); + $length = random_int($min, $max ?? $min); $charLength = \strlen($bytes); $result = str_repeat(' ', $length); for ($i = 0; $i < $length; ++$i) { - $result[$i] = $bytes[mt_rand(1, $charLength) - 1]; + $result[$i] = $bytes[random_int(1, $charLength) - 1]; } return $result; diff --git a/src/Util/Socket/IPEndPoint.php b/src/Util/Socket/IPEndPoint.php index 6df3904576..f2cec83d43 100644 --- a/src/Util/Socket/IPEndPoint.php +++ b/src/Util/Socket/IPEndPoint.php @@ -9,20 +9,16 @@ */ class IPEndPoint implements \Stringable { - /** - * 地址 - */ - private string $address = ''; - - /** - * 端口. - */ - private int $port = 0; - - public function __construct(string $address, int $port) - { - $this->address = $address; - $this->port = $port; + public function __construct( + /** + * 地址 + */ + private readonly string $address, + /** + * 端口. + */ + private readonly int $port + ) { } public function __toString(): string diff --git a/src/Util/Stream/FileStream.php b/src/Util/Stream/FileStream.php index 0e03c07076..0a8721d085 100644 --- a/src/Util/Stream/FileStream.php +++ b/src/Util/Stream/FileStream.php @@ -21,15 +21,14 @@ class FileStream implements StreamInterface, \Stringable */ protected $stream = null; - /** - * 流访问类型. - */ - protected string $mode = ''; - /** * @param string|resource|Uri $uri */ - public function __construct($uri, string $mode = StreamMode::READ_WRITE) + public function __construct($uri, + /** + * 流访问类型. + */ + protected string $mode = StreamMode::READ_WRITE) { if (\is_string($uri)) { @@ -48,7 +47,6 @@ public function __construct($uri, string $mode = StreamMode::READ_WRITE) { $uri = $this->uri; } - $this->mode = $mode; if (!$this->stream) { $this->stream = fopen($uri->__toString(), $mode); @@ -76,10 +74,10 @@ public function __toString(): string { $this->rewind(); - return stream_get_contents($this->stream); + return (string) stream_get_contents($this->stream); } // @codeCoverageIgnoreStart - catch (\Throwable $th) + catch (\Throwable) { return ''; } diff --git a/src/Util/Stream/MemoryStream.php b/src/Util/Stream/MemoryStream.php index b55d15f47d..ce8b6e9863 100644 --- a/src/Util/Stream/MemoryStream.php +++ b/src/Util/Stream/MemoryStream.php @@ -9,11 +9,6 @@ class MemoryStream implements StreamInterface, \Stringable { - /** - * 内容. - */ - protected string $content = ''; - /** * 大小. */ @@ -24,9 +19,12 @@ class MemoryStream implements StreamInterface, \Stringable */ protected int $position = 0; - public function __construct(string $content = '') + public function __construct( + /** + * 内容. + */ + protected string $content = '') { - $this->content = $content; $this->size = \strlen($content); } diff --git a/src/Util/Traits/TServerAnnotationParser.php b/src/Util/Traits/TServerAnnotationParser.php index b96d4be758..8f6c250406 100644 --- a/src/Util/Traits/TServerAnnotationParser.php +++ b/src/Util/Traits/TServerAnnotationParser.php @@ -46,7 +46,7 @@ public function getByServer(string $serverName): array $class = $option->getClass(); foreach ($namespaces as $namespace) { - if (str_starts_with($class, $namespace)) + if (str_starts_with($class, (string) $namespace)) { $result[$class] = $option; continue 2; diff --git a/src/Validate/ValidatorHelper.php b/src/Validate/ValidatorHelper.php index 3835a37ca5..7b3e5f96cf 100644 --- a/src/Validate/ValidatorHelper.php +++ b/src/Validate/ValidatorHelper.php @@ -346,27 +346,18 @@ public static function unequal($value, $num): bool */ public static function compare($valueLeft, string $operation, $valueRight): bool { - switch ($operation) + return match ($operation) { - case '==': - return $valueLeft == $valueRight; - case '!=': - return $valueLeft != $valueRight; - case '===': - return $valueLeft === $valueRight; - case '!==': - return $valueLeft !== $valueRight; - case '<': - return $valueLeft < $valueRight; - case '<=': - return $valueLeft <= $valueRight; - case '>': - return $valueLeft > $valueRight; - case '>=': - return $valueLeft >= $valueRight; - default: - throw new \InvalidArgumentException(sprintf('Unsupport operation %s', $operation)); - } + '==' => $valueLeft == $valueRight, + '!=' => $valueLeft != $valueRight, + '===' => $valueLeft === $valueRight, + '!==' => $valueLeft !== $valueRight, + '<' => $valueLeft < $valueRight, + '<=' => $valueLeft <= $valueRight, + '>' => $valueLeft > $valueRight, + '>=' => $valueLeft >= $valueRight, + default => throw new \InvalidArgumentException(sprintf('Unsupport operation %s', $operation)), + }; } /** diff --git a/src/functions.php b/src/functions.php index 9112ebe934..aa2a8a0257 100644 --- a/src/functions.php +++ b/src/functions.php @@ -127,7 +127,7 @@ function ttyExec($commands, ?float $timeout = null, ?Process &$process = null): } else { - $process->run(static function ($type, $buffer) { + $process->run(static function ($type, $buffer): void { echo $buffer; }); } diff --git a/tests/unit/Component/Bean/ReferenceBeanAspect.php b/tests/unit/Component/Bean/ReferenceBeanAspect.php index d18aff8fae..4907931166 100644 --- a/tests/unit/Component/Bean/ReferenceBeanAspect.php +++ b/tests/unit/Component/Bean/ReferenceBeanAspect.php @@ -83,10 +83,8 @@ public function &around(AroundJoinPoint $joinPoint) * "Imi\Test\Component\Bean\ReferenceBean::*" * } * ) - * - * @return void */ - public function afterReturning(AfterReturningJoinPoint $joinPoint) + public function afterReturning(AfterReturningJoinPoint $joinPoint): void { Log::info(sprintf('afterReturning ReferenceBean::%s()', $joinPoint->getMethod())); } @@ -99,10 +97,8 @@ public function afterReturning(AfterReturningJoinPoint $joinPoint) * "Imi\Test\Component\Bean\ReferenceBean::*" * } * ) - * - * @return void */ - public function afterThrowing(AfterThrowingJoinPoint $joinPoint) + public function afterThrowing(AfterThrowingJoinPoint $joinPoint): void { Log::info(sprintf('afterThrowing ReferenceBean::%s()', $joinPoint->getMethod())); } diff --git a/tests/unit/Component/Db/Classes/TestTransaction.php b/tests/unit/Component/Db/Classes/TestTransaction.php index 8c73a8e524..97b69bb553 100644 --- a/tests/unit/Component/Db/Classes/TestTransaction.php +++ b/tests/unit/Component/Db/Classes/TestTransaction.php @@ -121,9 +121,9 @@ public function rollbackPartAll(): void private function __listen(): void { $transaction = Db::getInstance()->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); } } diff --git a/tests/unit/Component/PHPUnitHook.php b/tests/unit/Component/PHPUnitHook.php index 65560deb35..9ea9cf5d45 100644 --- a/tests/unit/Component/PHPUnitHook.php +++ b/tests/unit/Component/PHPUnitHook.php @@ -17,9 +17,9 @@ class PHPUnitHook implements BeforeFirstTestHook { public function executeBeforeFirstTest(): void { - Event::on('IMI.APP_RUN', static function (EventParam $param) { + Event::on('IMI.APP_RUN', static function (EventParam $param): void { $param->stopPropagation(); - PoolManager::use('maindb', static function (IPoolResource $resource, IDb $db) { + PoolManager::use('maindb', static function (IPoolResource $resource, IDb $db): void { $truncateList = [ 'tb_article', 'tb_article2', @@ -47,7 +47,7 @@ public function executeBeforeFirstTest(): void }, 1); try { - App::run('Imi\Test\Component', CliApp::class, static function () { + App::run('Imi\Test\Component', CliApp::class, static function (): void { }); } catch (\Throwable $th) diff --git a/tests/unit/Component/Tests/BaseCacheTest.php b/tests/unit/Component/Tests/BaseCacheTest.php index 95eb406e2b..97a7a65866 100644 --- a/tests/unit/Component/Tests/BaseCacheTest.php +++ b/tests/unit/Component/Tests/BaseCacheTest.php @@ -29,7 +29,7 @@ public function testSetTTL(): void { $this->markTestSkipped('Handler does not support TTL'); } - $this->go(function () { + $this->go(function (): void { Assert::assertTrue(CacheManager::set($this->cacheName, 'imi', 'nb', 1)); Assert::assertEquals('nb', CacheManager::get($this->cacheName, 'imi')); sleep(2); @@ -58,7 +58,7 @@ public function testSetMultipleTTL(): void { $this->markTestSkipped('Handler does not support TTL'); } - $this->go(function () { + $this->go(function (): void { $values = [ 'k1' => 'v1', 'k2' => 'v2', diff --git a/tests/unit/Component/Tests/BaseLockTest.php b/tests/unit/Component/Tests/BaseLockTest.php index 713ded4011..f6aa2cefbd 100644 --- a/tests/unit/Component/Tests/BaseLockTest.php +++ b/tests/unit/Component/Tests/BaseLockTest.php @@ -71,7 +71,7 @@ public function testLockCallable(): void foreach ([null, $this->lockId] as $lockId) { Assert::assertFalse(Lock::isLocked($this->lockConfigId, $lockId)); - $result = Lock::lock($this->lockConfigId, function () use ($lockId) { + $result = Lock::lock($this->lockConfigId, function () use ($lockId): void { Assert::assertTrue(Lock::isLocked($this->lockConfigId, $lockId)); Assert::assertEquals(RequestContext::getCurrentFlag(), Lock::getInstance($this->lockConfigId, $lockId)->getLockFlag()); }, null, $lockId); @@ -87,7 +87,7 @@ public function testTryLockCallable(): void { Assert::assertFalse(Lock::isLocked($this->lockConfigId, $lockId)); Assert::assertEquals('', Lock::getInstance($this->lockConfigId, $lockId)->getLockFlag()); - $result = Lock::tryLock($this->lockConfigId, function () use ($lockId) { + $result = Lock::tryLock($this->lockConfigId, function () use ($lockId): void { Assert::assertTrue(Lock::isLocked($this->lockConfigId, $lockId)); Assert::assertEquals(RequestContext::getCurrentFlag(), Lock::getInstance($this->lockConfigId, $lockId)->getLockFlag()); }, $lockId); @@ -104,7 +104,7 @@ public function testCancelLockCallabale(): void { Assert::assertFalse(Lock::isLocked($this->lockConfigId, $lockId)); Assert::assertEquals('', Lock::getInstance($this->lockConfigId, $lockId)->getLockFlag()); - $result = Lock::lock($this->lockConfigId, static function () { + $result = Lock::lock($this->lockConfigId, static function (): void { Assert::assertTrue(false); }, function () use ($lockId) { Assert::assertEquals(RequestContext::getCurrentFlag(), Lock::getInstance($this->lockConfigId, $lockId)->getLockFlag()); diff --git a/tests/unit/Component/Tests/Db/DbBaseTest.php b/tests/unit/Component/Tests/Db/DbBaseTest.php index 3a8a23c54e..e25852eb47 100644 --- a/tests/unit/Component/Tests/Db/DbBaseTest.php +++ b/tests/unit/Component/Tests/Db/DbBaseTest.php @@ -301,7 +301,7 @@ public function testTransactionRollback(): void public function testTransUseCommit(): void { $id = null; - Db::transUse(static function (IDb $db) use (&$id) { + Db::transUse(static function (IDb $db) use (&$id): void { Assert::assertTrue($db->inTransaction()); $result = $db->exec("insert into tb_article(title,content,time)values('title', 'content', '2019-06-21')"); Assert::assertEquals(1, $result); @@ -328,7 +328,7 @@ public function testTransUseRollback(): void $id = null; try { - Db::transUse(static function (IDb $db) use (&$id) { + Db::transUse(static function (IDb $db) use (&$id): void { Assert::assertTrue($db->inTransaction()); $result = $db->exec("insert into tb_article(title,content,time)values('title', 'content', '2019-06-21')"); Assert::assertEquals(1, $result); @@ -355,7 +355,7 @@ public function testTransactionRollbackRollbackEvent(): void Assert::assertTrue($db->inTransaction()); $this->assertEquals(1, $db->getTransactionLevels()); $r1 = false; - $db->getTransaction()->onTransactionRollback(static function () use (&$r1) { + $db->getTransaction()->onTransactionRollback(static function () use (&$r1): void { $r1 = true; }); @@ -376,7 +376,7 @@ public function testTransactionRollbackCommitEvent(): void Assert::assertTrue($db->inTransaction()); $this->assertEquals(1, $db->getTransactionLevels()); $r1 = false; - $db->getTransaction()->onTransactionCommit(static function () use (&$r1) { + $db->getTransaction()->onTransactionCommit(static function () use (&$r1): void { $r1 = true; }); $db->commit(); diff --git a/tests/unit/Component/Tests/Db/QueryCurdBaseTest.php b/tests/unit/Component/Tests/Db/QueryCurdBaseTest.php index 62687c573f..5e68117a75 100644 --- a/tests/unit/Component/Tests/Db/QueryCurdBaseTest.php +++ b/tests/unit/Component/Tests/Db/QueryCurdBaseTest.php @@ -559,7 +559,7 @@ public function testWhereBrackets(array $args): void // Where 收集器 $query = Db::query($this->poolName); - $result = $query->from($this->tableArticle)->whereBrackets(static function (IQuery $query, IWhereCollector $where) use ($id) { + $result = $query->from($this->tableArticle)->whereBrackets(static function (IQuery $query, IWhereCollector $where) use ($id): void { $where->where('id', '=', $id)->orWhereRaw('1=2'); })->select(); $record = $result->get(); @@ -573,7 +573,7 @@ public function testWhereBrackets(array $args): void Assert::assertEquals('select * from `tb_article` where (`id` = :p1 or 1=2)', $result->getSql()); $query = Db::query($this->poolName); - $sql = $query->from($this->tableArticle)->whereBrackets(static function (IQuery $query, IWhereCollector $where) { + $sql = $query->from($this->tableArticle)->whereBrackets(static function (IQuery $query, IWhereCollector $where): void { $where->where('where', '=', 1) ->orWhere('orWhere', '=', 2) ->whereBetween('whereBetween', 1, 2) diff --git a/tests/unit/Component/Tests/Db/TransactionTest.php b/tests/unit/Component/Tests/Db/TransactionTest.php index 86a8a2e449..139337865c 100644 --- a/tests/unit/Component/Tests/Db/TransactionTest.php +++ b/tests/unit/Component/Tests/Db/TransactionTest.php @@ -23,9 +23,9 @@ public function testNestingCommit(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); try { @@ -41,15 +41,15 @@ public function testNestingCommit(): void } $this->assertEmptyEvents($transaction); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); // 在事务中,不自动提交事务 $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); try @@ -76,9 +76,9 @@ public function testNestingCommit2(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); try { @@ -94,15 +94,15 @@ public function testNestingCommit2(): void } $this->assertEmptyEvents($transaction); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); // 在事务中,不自动提交事务 $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); try @@ -128,14 +128,14 @@ public function testNestingRollback(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); @@ -175,14 +175,14 @@ public function testNestingRollback2(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); @@ -229,14 +229,14 @@ public function testRequirementCommit2(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); try @@ -262,14 +262,14 @@ public function testRequirementRollback(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); @@ -310,9 +310,9 @@ public function testAutoCommit(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); try { @@ -328,15 +328,15 @@ public function testAutoCommit(): void } $this->assertEmptyEvents($transaction); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); // 在事务中,不自动提交事务 $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); try @@ -362,9 +362,9 @@ public function testAutoRollback(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); try @@ -403,14 +403,14 @@ public function testRollbackPart1(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); @@ -450,14 +450,14 @@ public function testRollbackPartAll(): void $object = $this->getObject(); $db = Db::getInstance(); $transaction = $db->getTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $db->beginTransaction(); - $transaction->onTransactionCommit(static function () { + $transaction->onTransactionCommit(static function (): void { }); - $transaction->onTransactionRollback(static function () { + $transaction->onTransactionRollback(static function (): void { }); $this->assertEquals(1, $transaction->getTransactionLevels()); diff --git a/tests/unit/Component/Tests/EventTest.php b/tests/unit/Component/Tests/EventTest.php index c74e3612bf..9f8926e416 100644 --- a/tests/unit/Component/Tests/EventTest.php +++ b/tests/unit/Component/Tests/EventTest.php @@ -16,7 +16,7 @@ class EventTest extends BaseTest { public function testNormal(): void { - Event::on('IMITEST.EVENT.A', function (EventParam $e) { + Event::on('IMITEST.EVENT.A', function (EventParam $e): void { Assert::assertEquals('IMITEST.EVENT.A', $e->getEventName()); Assert::assertEquals($this, $e->getTarget()); $data = $e->getData(); @@ -34,7 +34,7 @@ public function testNormal(): void public function testOne(): void { - Event::one('IMITEST.EVENT.B', function (EventParam $e) { + Event::one('IMITEST.EVENT.B', function (EventParam $e): void { Assert::assertEquals('IMITEST.EVENT.B', $e->getEventName()); Assert::assertEquals($this, $e->getTarget()); $data = $e->getData(); @@ -59,11 +59,11 @@ public function testOne(): void public function testOff(): void { - $callable1 = static function (EventParam $e) { + $callable1 = static function (EventParam $e): void { Assert::assertTrue(false); }; - $callable2 = static function (EventParam $e) { + $callable2 = static function (EventParam $e): void { Assert::assertTrue(false); }; Event::on('IMITEST.EVENT.C', $callable1); @@ -100,7 +100,7 @@ public function testClassListener1(): void public function testClassListener2(): void { $testClass = new \Imi\Test\Component\Event\Classes\TestClass(); - $testClass->on('test2', static function (EventParam $e) use ($testClass) { + $testClass->on('test2', static function (EventParam $e) use ($testClass): void { Assert::assertEquals('test2', $e->getEventName()); Assert::assertEquals($testClass, $e->getTarget()); $data = $e->getData(); @@ -114,7 +114,7 @@ public function testClassListener2(): void public function testClassListenerOff(): void { $testClass = new \Imi\Test\Component\Event\Classes\TestClass(); - $callable = static function (EventParam $e) { + $callable = static function (EventParam $e): void { Assert::assertTrue(false); }; $testClass->on('test3', $callable); diff --git a/tests/unit/Component/Tests/HotUpdate/BaseMonitorTest.php b/tests/unit/Component/Tests/HotUpdate/BaseMonitorTest.php index f4d736ebde..0c5b05653c 100644 --- a/tests/unit/Component/Tests/HotUpdate/BaseMonitorTest.php +++ b/tests/unit/Component/Tests/HotUpdate/BaseMonitorTest.php @@ -33,7 +33,7 @@ public function test(): void $this->assertEquals([$file], $monitor->getChangedFiles()); $this->assertFalse($monitor->isChanged()); - mkdir($excludePath, 0777, true); + mkdir($excludePath, 0o777, true); $this->assertFalse($monitor->isChanged()); $file = $excludePath . \DIRECTORY_SEPARATOR . 'test1.txt'; diff --git a/tests/unit/Component/Tests/ModelRelationTest.php b/tests/unit/Component/Tests/ModelRelationTest.php index d155f44c0c..c466ea2474 100644 --- a/tests/unit/Component/Tests/ModelRelationTest.php +++ b/tests/unit/Component/Tests/ModelRelationTest.php @@ -114,7 +114,7 @@ public function testOneToOne(array $args): array $this->assertEquals(Article::convertListToArray([$record1, $record2]), Article::convertListToArray($list)); // with callable $callableAnnotation = null; - $list = Article::query()->with(['ex' => static function (\Imi\Model\Contract\IModelQuery $query, OneToOne $annotation) use (&$callableAnnotation) { + $list = Article::query()->with(['ex' => static function (\Imi\Model\Contract\IModelQuery $query, OneToOne $annotation) use (&$callableAnnotation): void { $callableAnnotation = $annotation; }])->whereIn('id', $articleIds)->select()->getArray(); $this->assertEquals(Article::convertListToArray([$record1, $record2]), Article::convertListToArray($list)); diff --git a/tests/unit/Component/Tests/ModelTest.php b/tests/unit/Component/Tests/ModelTest.php index 084c8aa59f..2aa25e3a7a 100644 --- a/tests/unit/Component/Tests/ModelTest.php +++ b/tests/unit/Component/Tests/ModelTest.php @@ -835,7 +835,7 @@ public function testFork(): void public function testNotBean(): void { $record = Article2::newInstance(); - $this->assertEquals(Article2::class, \get_class($record)); + $this->assertEquals(Article2::class, $record::class); $record->memberId = 1024; $record->title = __CLASS__; $record->content = __FUNCTION__; @@ -844,7 +844,7 @@ public function testNotBean(): void $record = Article2::find($record->id); $this->assertNotNull($record); - $this->assertEquals(Article2::class, \get_class($record)); + $this->assertEquals(Article2::class, $record::class); } public function testReferenceProperty(): void diff --git a/tests/unit/Component/Tests/RedisManagerTest.php b/tests/unit/Component/Tests/RedisManagerTest.php index 8d3a07a18f..2c07554603 100644 --- a/tests/unit/Component/Tests/RedisManagerTest.php +++ b/tests/unit/Component/Tests/RedisManagerTest.php @@ -69,7 +69,7 @@ public function testNewInstance(): void public function testInstance(): void { $pool = PoolManager::getInstance('redis_manager_test'); - $this->go(function () use ($pool) { + $this->go(function () use ($pool): void { Assert::assertEquals(1, $pool->getCount()); Assert::assertEquals(1, $pool->getFree()); diff --git a/tests/unit/Component/Tests/Util/DateTimeTest.php b/tests/unit/Component/Tests/Util/DateTimeTest.php index 1ac19b2d17..52ea0d2b52 100644 --- a/tests/unit/Component/Tests/Util/DateTimeTest.php +++ b/tests/unit/Component/Tests/Util/DateTimeTest.php @@ -17,7 +17,7 @@ class DateTimeTest extends BaseTest */ public function testGetSecondsByInterval(): void { - $this->go(function () { + $this->go(function (): void { $di = new \DateInterval('PT1S'); $sec = DateTime::getSecondsByInterval($di); $this->assertTrue($sec <= 1); diff --git a/tests/unit/Component/test.php b/tests/unit/Component/test.php index 19bcbd22f7..d12a067881 100644 --- a/tests/unit/Component/test.php +++ b/tests/unit/Component/test.php @@ -7,6 +7,6 @@ require \dirname(__DIR__, 3) . '/vendor/autoload.php'; -App::runApp(__DIR__, CliApp::class, static function () { +App::runApp(__DIR__, CliApp::class, static function (): void { echo 'Test quick start', \PHP_EOL; });