Problems with "beforeFind" in complex queries

CakePHP 4.4.17
PHP 8.x
Mysql 8.x

In composer.json, the dependencies of cakephp are:

        "cache/adapter-common": "1.3.0",
        "cache/hierarchical-cache": "1.2.0",
        "cache/simple-cache-bridge": "1.2.0",
        "cakephp/cakephp": "4.4.17",
        "cakephp/migrations": "3.8.2",
        "cakephp/plugin-installer": "1.3.1",
        "doctrine/dbal": "^3.6.6",

Hi everyone.
In a very large project I need to add a new filter to all queries (automatically).
I by all queries also mean “*join”, subquery …

I thought about using the “beforeFind” which adds the filter with a “andWhere.”

During the first tests, I had some problems with the “->join(…)” because it wasn’t handled in beforeFind.
I manipulated with the “traverseParts” (Query class) and adding a condition to the join, so It works.

public function beforeFind(Event $event, Query $query, $options, $primary)
        $myValue = "test";
        $field = Configure::read('field_guid');
        $subject = $event->getSubject()->getAlias();
            function ($parts) use ($field, $myValue) {
                foreach ($parts as $key => $part) {
                    $conditions = $part['conditions'];
                    if (!empty($conditions)){
                        $conditions->add([sprintf('%s.%s',$key,$field) => $myValue]);
         $query->andWhere([sprintf('%s.%s',$subject,$field) => $myValue]);

It seemed to work but as I test complex queries (severals innjerJoinWith, subqueries or aggregation subqueries) the first problems surfaced.

For aggregate queries (count, sum, max), the orm generates sql errors due to the fact that for each Model involved, it adds all the fields in the select and therefore generates of “group By” errors

Other problems are with the distinct, for each innerJoinWith the ORM add the “_matchingData”.
This is strange, because this behavior should only happen with “contain” and “matching” (or at least I understood that).

These problems are due to the use of “beforeFind”. If I remove the event from the Tables, everything works again.

If instead I leave the event active but without doing anything (without the new filter) the changes to the queries occur causing same errors.

Can you help me to understand why? I had thought about using the map/reduce but I find myself shifting the computational cost from the DB to php.

I hope you help me because otherwise the solution is to rewrite all the queries. :frowning:

Thanks in advance.