protected static function validateSortByField(string $data, array $fields, array $displayColumns, RepositoryInterface $table): string
    {
        /** @var \Cake\ORM\Table */
        $table = $table;
        // use sort field if is searchable
        if (in_array($data, $fields)) {
            return $data;
        }

        // set display field as sort field
        $data = $table->getDisplayField();

        // check if display field exists in the database table
        if ($table->getSchema()->getColumn($data)) {
            return $table->aliasField($data);
        }

        // use first display column which exists in the database table
        foreach ($displayColumns as $displayColumn) {
            // remove table prefix
            list(, $displayColumn) = explode('.', $displayColumn);
            if (!$table->getSchema()->getColumn($displayColumn)) {
                continue;
            }

            return $table->aliasField($displayColumn);
        }

        // use primary key as a last resort
        return $table->aliasField(current((array)$table->getPrimaryKey()));
    }