<?php
namespace models;

/**
 * Snippet model class
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2018-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Snippet extends \ActiveRecord {
    
    protected function validate() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->validateMaxLength( 'name', 100, $i18n->__( 'too_long_name', 100 ) );
        $this->validateNotEmpty( 'name', $i18n->__( 'name_cannot_be_empty' ) );
        if ( $this->isNewRecord() || $this->isAttributeChanged( 'name' ) ) {
            $this->validateUnique( 'name', $i18n->__( 'snippet_already_exists', $this->name ) );
        }   
        $this->validateInteger( 'position', $i18n->__( 'not_an_integer' ) );
    }

    protected function beforeSave() {
        $this->name = trim( $this->name );
    }

    public static function findLastModifiedSnippets( $limit = 5 ) {
        return Snippet::findMany( ['snippet_id', 'name', 'updated_at'], ['LIMIT'=> $limit, 'ORDER' => ['updated_at' => 'DESC']] );
    }

    public static function findLastCreatedSnippets( $limit = 5 ) {
        return Snippet::findMany( ['snippet_id', 'name', 'created_at'], ['LIMIT'=> $limit, 'ORDER' => ['created_at' => 'DESC']] );
    }
}
