<commit_before><?php
namespace CkTools\Model\Behavior;

use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\Utility\Hash;

/**
 * Sortable behavior
 */
class SortableBehavior extends Behavior
{

    /**
     * Stores the original value of sortField in beforeSave for later comparisons.
     *
     * @var string|int
     */
    private $__originalSortValue;

    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [
        // Table field which stores the sort order
        'sortField' => 'sort',
        // Conditions which must match to include sortable records
        'scope' => [],
        // Array of columns which must be equal between records to sort inside
        'columnScope' => [],
        // If restoreSorting is called, this will be used to order the records
        'defaultOrder' => []
    ];

    /**
     * Restores the sorting based on defaultOrder
     *
     * @return void
     */
    public function restoreSorting(array $scope = [])
    {
        $records = $this->_table->find()
            ->select($this->_table->primaryKey(), $this->config('sortField'))
            ->order($this->config('defaultOrder'));
        if (!empty($scope)) {
            $records->where($scope);
        }

        foreach ($records as $n => $entity) {
            $sort = ($n + 1);
            $this->_table->updateAll([
                $this->config('sortField') => $sort
            ], [
                $this->_table->primaryKey() => $entity->get($this->_table->primaryKey())
            ]);
        }
    }

    /**
     * beforeSave Event
     *
     * @param Event $event Event
     * @param Entity $entity Record
     * @return void
     */
    public function beforeSave(Event $event, Entity $entity)
    {
        $this->__originalSortValue = $entity->getOriginal($this->config('sortField'));
    }

    /**
     * afterSave Event
     *
     * @param Event $event Event
     * @param Entity $entity Record
     * @return void
     */
    public function afterSave(Event $event, Entity $entity)
    {
        $fields = array_merge([
            $this->_table->primaryKey(),
            $this->config('sortField')
        ], $this->config('columnScope'));
        $savedEntity = $this->_table->get($entity->get($this->_table->primaryKey()), [
            'fields' => $fields
        ]);
        $scope = $this->config('scope');

        foreach ($this->config('columnScope') as $column) {
            $scope[$column] = $savedEntity->get($column);
        }
        $entitySort = $savedEntity->{$this->config('sortField')};
        $entityId = $entity->get($this->_table->primaryKey());

        if (empty($entitySort)) {
            $nextSortValue = $this->getNextSortValue($scope);
            $this->_table->updateAll([
                $this->config('sortField') => $nextSortValue
            ], [
                $this->_table->primaryKey() => $entityId
            ]);
        } else {
            if ($entitySort < $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} <" . $this->__originalSortValue;
                $currentScope[] = "{$this->config('sortField')} >=" . $entitySort;
                $currentScope[] = $this->_table->primaryKey() . '!=' . $entity->id;

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' + 1')
                ]);
                $query->execute();

            } elseif ($entitySort > $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} >" . $this->__originalSortValue;
                $currentScope[] = "{$this->config('sortField')} <=" . $entitySort;
                $currentScope[] = $this->_table->primaryKey() . '!=' . $entity->id;

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' - 1')
                ]);
                $query->execute();
                
            } elseif ($entitySort == $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} >=" . $entitySort;
                $currentScope[] = $this->_table->primaryKey() . '!=' . $entity->id;

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' + 1')
                ]);
                $query->execute();
            }<commit_msg>fix sortablebehavior for non-integer primary keys<commit_after><?php
namespace CkTools\Model\Behavior;

use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\Utility\Hash;

/**
 * Sortable behavior
 */
class SortableBehavior extends Behavior
{

    /**
     * Stores the original value of sortField in beforeSave for later comparisons.
     *
     * @var string|int
     */
    private $__originalSortValue;

    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [
        // Table field which stores the sort order
        'sortField' => 'sort',
        // Conditions which must match to include sortable records
        'scope' => [],
        // Array of columns which must be equal between records to sort inside
        'columnScope' => [],
        // If restoreSorting is called, this will be used to order the records
        'defaultOrder' => []
    ];

    /**
     * Restores the sorting based on defaultOrder
     *
     * @return void
     */
    public function restoreSorting(array $scope = [])
    {
        $records = $this->_table->find()
            ->select($this->_table->primaryKey(), $this->config('sortField'))
            ->order($this->config('defaultOrder'));
        if (!empty($scope)) {
            $records->where($scope);
        }

        foreach ($records as $n => $entity) {
            $sort = ($n + 1);
            $this->_table->updateAll([
                $this->config('sortField') => $sort
            ], [
                $this->_table->primaryKey() => $entity->get($this->_table->primaryKey())
            ]);
        }
    }

    /**
     * beforeSave Event
     *
     * @param Event $event Event
     * @param Entity $entity Record
     * @return void
     */
    public function beforeSave(Event $event, Entity $entity)
    {
        $this->__originalSortValue = $entity->getOriginal($this->config('sortField'));
    }

    /**
     * afterSave Event
     *
     * @param Event $event Event
     * @param Entity $entity Record
     * @return void
     */
    public function afterSave(Event $event, Entity $entity)
    {
        $fields = array_merge([
            $this->_table->primaryKey(),
            $this->config('sortField')
        ], $this->config('columnScope'));
        $savedEntity = $this->_table->get($entity->get($this->_table->primaryKey()), [
            'fields' => $fields
        ]);
        $scope = $this->config('scope');

        foreach ($this->config('columnScope') as $column) {
            $scope[$column] = $savedEntity->get($column);
        }
        $entitySort = $savedEntity->{$this->config('sortField')};
        $entityId = $entity->get($this->_table->primaryKey());

        if (empty($entitySort)) {
            $nextSortValue = $this->getNextSortValue($scope);
            $this->_table->updateAll([
                $this->config('sortField') => $nextSortValue
            ], [
                $this->_table->primaryKey() => $entityId
            ]);
        } else {
            if ($entitySort < $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} <" . $this->__originalSortValue;
                $currentScope[] = "{$this->config('sortField')} >=" . $entitySort;
                $currentScope[] = [
                    $this->_table->primaryKey() . ' !=' => $entity->id
                ];

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' + 1')
                ]);
                $query->execute();

            } elseif ($entitySort > $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} >" . $this->__originalSortValue;
                $currentScope[] = "{$this->config('sortField')} <=" . $entitySort;
                $currentScope[] = [
                    $this->_table->primaryKey() . ' !=' => $entity->id
                ];

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' - 1')
                ]);
                $query->execute();
                
            } elseif ($entitySort == $this->__originalSortValue) {
                $currentScope = $scope;
                $currentScope[] = "{$this->config('sortField')} >=" . $entitySort;
                $currentScope[] = [
                    $this->_table->primaryKey() . ' !=' => $entity->id
                ];

                $query = $this->_table->query()->update();
                $query->where($currentScope);
                $query->set([
                    $this->config('sortField') => $query->newExpr($this->config('sortField') . ' + 1')
                ]);
                $query->execute();
            }
{'fraction_non_alphanumeric': 0.1696268209938136, 'fraction_numerical': 0.0007982438635002994, 'mean_word_length': 1.819409282700422, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 218, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6257320', 'n_tokens_mistral': 2754, 'n_tokens_neox': 2647, 'n_words': 503}