Mmoreram\PHPFormatter\Sorter\UseSorter::sort PHP Method

sort() public method

Sort any piece of code given as parameter.
public sort ( string $data ) : false | string
$data string Data
return false | string Data processed or false if no use block has been found
    public function sort($data)
    {
        $regex = '/(\\s*(?:(?:\\s+use\\s+?[\\w\\\\\\,\\s]+?;)+)\\s+)/s';
        preg_match($regex, $data, $results);
        if (!isset($results[0])) {
            return false;
        }
        $result = $results[0];
        $blocks = explode(';', $result);
        $namespaces = [];
        foreach ($blocks as $block) {
            /**
             * Removing use literal.
             */
            $block = trim(preg_replace('/^\\s+use\\s+/', '', $block));
            $namespaces = array_merge($namespaces, explode(',', $block));
        }
        /**
         * Trim all results of blank spaces and line breaks.
         */
        $namespaces = array_map(function ($namespace) {
            return trim($namespace);
        }, $namespaces);
        /**
         * If any position becomes empty, removes.
         */
        $namespaces = array_filter($namespaces, function ($namespace) {
            return !empty($namespace);
        });
        /**
         * Grouping use statements by blocks defined in blocks variable.
         */
        $groups = $this->createGroups($namespaces);
        /*
         * Every block is sorted as desired
         */
        foreach ($groups as $groupKey => $group) {
            if (is_int($groupKey)) {
                $subGroupSorted = [];
                foreach ($group as $subGroupKey => $subGroup) {
                    $subGroupSorted = array_merge($subGroupSorted, $this->sortGroup($subGroup));
                }
                $groups[$groupKey] = $subGroupSorted;
            } else {
                $groups[$groupKey] = $this->sortGroup($group);
            }
            //  Remove empty groups (if configured) after the sorting has happened.
            //  @see https://github.com/mmoreram/php-formatter/issues/24
            if ($this->groupSkipEmpty && 0 === count($groups[$groupKey])) {
                unset($groups[$groupKey]);
            }
        }
        $doubleEOL = PHP_EOL . PHP_EOL;
        $processedResult = $doubleEOL . trim(implode($doubleEOL, array_map(function ($group) {
            return $this->renderGroup($group);
        }, $groups))) . $doubleEOL;
        return str_replace($result, $processedResult, $data);
    }