<commit_before><?php
/**
 * Created by PhpStorm.
 * User: Sjaak
 * Date: 2-6-14
 * Time: 12:16
 */

/**
 * FAQ
 *
 * I'm getting an error like 'Trying to get property of non-object'
 * - You probably didn't give the form the option 'enctype' => 'multipart/form-data'.
 *
 * The image is distorted after upload.
 * - Maybe the owner model is used under a scenario. This scenario should declare the crop attributes
 *      ('<file>_x', '<file>_y', '<file>_w', '<file>_h') in the attribute list.
 *
 * I'm getting an error message: one of the crop dimensions appears to be 0. aspectRatio is a string.
 * - The owner model may be used under a scenario. This scenario should declare the aspect ratio attribute ('aspect') in the attribute list.
 */

namespace sjaakp\illustrated;

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\validators\FileValidator;
use yii\validators\SafeValidator;
use yii\web\UploadedFile;
use yii\helpers\Html;
use yii\helpers\FileHelper;
use yii\imagine\Image;
use Imagine\Image\Box;
use Imagine\Image\Point;

class Illustrated extends Behavior  {

    /**
     * @var string
     * Name of the file input attribute in the model.
     */
    public $fileAttribute = 'file';

    /**
     * @var string
     * Name of the attribute in the model where the img file name of the resulting cropped image is stored.
     */
    public $imgAttribute = 'img';

    /**
     * @var null|string
     * If null (default): $cropSize is strict, and the crop size is not stored in model.
     * If string: name of the attribute in the model where size is stored. Lower crop size than $cropSize may be accepted.
     */
    public $sizeAttribute;

    /**
     * @var float|string
     * If float: the fixed aspect ratio of the image; it is not saved in the database.
     * If string: name of aspect attribute in the model. The variable aspect ratio is saved in the database.
     * Default: 1.0.
     */
    public $aspectRatio = 1.0;

    /**
     * @var int
     * Size of the largest side of the cropped image, in pixels.
     * For portrait format (aspect ratio < 1.0) it is the height, for landscape format the width.
     * Default: 240.
     */
    public $cropSize = 240;

    /**
     * @var int
     * Number of size variants of the cropped image. Each variant has half the size of the previous one.
     * Example: if $cropSize = 1280, and $sizeSteps = 5, variants will be saved with
     *      sizes 1280, 640, 320, 160, and 80 pixels, each in it's own subdirectory.
     * If $sizeSteps = 0 (default), only one cropped image is saved, with size $cropSize.
     */
    public $sizeSteps = 0;

    /**
     * @var null|string
     * Directory where cropped images are saved.
     * If null (default), the directory will be '@webroot/<$illustrationDirectory>/<table name>', where table name is
     *  the table name of the model.
     */
    public $directory;

    /**
     * @var string
     * Name of subdirectory under '@webroot' where cropped images are stored.
     */
    public $illustrationDirectory = 'illustrations';

    /**
     * @var string
     * Error message for images that are too small to crop. Parameters: original file name, width, and height.
     */
    public $tooSmallMsg = 'Image "%s" is too small (%d×%d).';

    /**
     * @var array
     * Extra parameters for the validation of the file attribute. By default, only the file types and max files are tested.
     *      You may add things like maximum file size here. See yii\validators\FileValidator.
     */
    public $fileValidation = [];


    protected $_file;
    protected $_image;
    protected $_cropAttributeNames;
    protected $_x;
    protected $_y;
    protected $_w;
    protected $_h;

    // Magic functions to handle file attributes and crop attributes.
    public function __get($name)    {
        if ($name == $this->fileAttribute) return $this->_file;
        $s = array_search($name, $this->_cropAttributeNames);
        if ($s !== false) return $this->$s;
        return parent::__get($name);
    }

    public function __set($name, $value)    {
        if ($name == $this->fileAttribute) $this->_file = $value;
        else    {
            $s = array_search($name, $this->_cropAttributeNames);
            if ($s !== false) $this->$s = $value;
            else parent::__set($name, $value);
        }
    }

    public function canGetProperty($name, $checkVars = true)    {
        if ($name == $this->fileAttribute) return true;
        if (in_array($name, $this->_cropAttributeNames)) return true;
        return parent::canGetProperty($name, $checkVars);
    }

    public function canSetProperty($name, $checkVars = true)    {
        if ($name == $this->fileAttribute) return true;
        if (in_array($name, $this->_cropAttributeNames)) return true;
        return parent::canSetProperty($name, $checkVars);
    }


    public function events()    {
        return [
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
            ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
        ];
    }

    public function attach($owner)    {
        parent::attach($owner);

        // cache crop attribute names ('file_x' etc.).
        foreach([ '_x', '_y', '_w', '_h' ] as $d ) $this->_cropAttributeNames[$d] = $this->fileAttribute . $d;

        // determine safe attributes
        $safeAttr = array_values($this->_cropAttributeNames);
        if (! is_numeric($this->aspectRatio)) $safeAttr[] = $this->aspectRatio;

        // add validation rules to model
        $vals = $owner->getValidators();
        $vals[] = new FileValidator(array_merge($this->fileValidation, [
            'attributes' => [ $this->fileAttribute ],
            'types'=>'jpg, jpeg, gif, png',
            'skipOnEmpty' => true
        ]));
        $vals[] = new SafeValidator([
            'attributes' => $safeAttr
        ]);
    }

    public function beforeValidate($event)  {
        $upl = new UploadedFile();
        $this->_file = $upl->getInstance($this->owner, $this->fileAttribute);
        if (! $this->_file->hasError)   {

            $owner = $this->owner;

            // Determine aspect ratio
            if (is_numeric($this->aspectRatio))   {
                $asp = $this->aspectRatio;<commit_msg>Update Illustrated as "type" has been changed<commit_after><?php
/**
 * Created by PhpStorm.
 * User: Sjaak
 * Date: 2-6-14
 * Time: 12:16
 */

/**
 * FAQ
 *
 * I'm getting an error like 'Trying to get property of non-object'
 * - You probably didn't give the form the option 'enctype' => 'multipart/form-data'.
 *
 * The image is distorted after upload.
 * - Maybe the owner model is used under a scenario. This scenario should declare the crop attributes
 *      ('<file>_x', '<file>_y', '<file>_w', '<file>_h') in the attribute list.
 *
 * I'm getting an error message: one of the crop dimensions appears to be 0. aspectRatio is a string.
 * - The owner model may be used under a scenario. This scenario should declare the aspect ratio attribute ('aspect') in the attribute list.
 */

namespace sjaakp\illustrated;

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\validators\FileValidator;
use yii\validators\SafeValidator;
use yii\web\UploadedFile;
use yii\helpers\Html;
use yii\helpers\FileHelper;
use yii\imagine\Image;
use Imagine\Image\Box;
use Imagine\Image\Point;

class Illustrated extends Behavior  {

    /**
     * @var string
     * Name of the file input attribute in the model.
     */
    public $fileAttribute = 'file';

    /**
     * @var string
     * Name of the attribute in the model where the img file name of the resulting cropped image is stored.
     */
    public $imgAttribute = 'img';

    /**
     * @var null|string
     * If null (default): $cropSize is strict, and the crop size is not stored in model.
     * If string: name of the attribute in the model where size is stored. Lower crop size than $cropSize may be accepted.
     */
    public $sizeAttribute;

    /**
     * @var float|string
     * If float: the fixed aspect ratio of the image; it is not saved in the database.
     * If string: name of aspect attribute in the model. The variable aspect ratio is saved in the database.
     * Default: 1.0.
     */
    public $aspectRatio = 1.0;

    /**
     * @var int
     * Size of the largest side of the cropped image, in pixels.
     * For portrait format (aspect ratio < 1.0) it is the height, for landscape format the width.
     * Default: 240.
     */
    public $cropSize = 240;

    /**
     * @var int
     * Number of size variants of the cropped image. Each variant has half the size of the previous one.
     * Example: if $cropSize = 1280, and $sizeSteps = 5, variants will be saved with
     *      sizes 1280, 640, 320, 160, and 80 pixels, each in it's own subdirectory.
     * If $sizeSteps = 0 (default), only one cropped image is saved, with size $cropSize.
     */
    public $sizeSteps = 0;

    /**
     * @var null|string
     * Directory where cropped images are saved.
     * If null (default), the directory will be '@webroot/<$illustrationDirectory>/<table name>', where table name is
     *  the table name of the model.
     */
    public $directory;

    /**
     * @var string
     * Name of subdirectory under '@webroot' where cropped images are stored.
     */
    public $illustrationDirectory = 'illustrations';

    /**
     * @var string
     * Error message for images that are too small to crop. Parameters: original file name, width, and height.
     */
    public $tooSmallMsg = 'Image "%s" is too small (%d×%d).';

    /**
     * @var array
     * Extra parameters for the validation of the file attribute. By default, only the file types and max files are tested.
     *      You may add things like maximum file size here. See yii\validators\FileValidator.
     */
    public $fileValidation = [];


    protected $_file;
    protected $_image;
    protected $_cropAttributeNames;
    protected $_x;
    protected $_y;
    protected $_w;
    protected $_h;

    // Magic functions to handle file attributes and crop attributes.
    public function __get($name)    {
        if ($name == $this->fileAttribute) return $this->_file;
        $s = array_search($name, $this->_cropAttributeNames);
        if ($s !== false) return $this->$s;
        return parent::__get($name);
    }

    public function __set($name, $value)    {
        if ($name == $this->fileAttribute) $this->_file = $value;
        else    {
            $s = array_search($name, $this->_cropAttributeNames);
            if ($s !== false) $this->$s = $value;
            else parent::__set($name, $value);
        }
    }

    public function canGetProperty($name, $checkVars = true)    {
        if ($name == $this->fileAttribute) return true;
        if (in_array($name, $this->_cropAttributeNames)) return true;
        return parent::canGetProperty($name, $checkVars);
    }

    public function canSetProperty($name, $checkVars = true)    {
        if ($name == $this->fileAttribute) return true;
        if (in_array($name, $this->_cropAttributeNames)) return true;
        return parent::canSetProperty($name, $checkVars);
    }


    public function events()    {
        return [
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
            ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
        ];
    }

    public function attach($owner)    {
        parent::attach($owner);

        // cache crop attribute names ('file_x' etc.).
        foreach([ '_x', '_y', '_w', '_h' ] as $d ) $this->_cropAttributeNames[$d] = $this->fileAttribute . $d;

        // determine safe attributes
        $safeAttr = array_values($this->_cropAttributeNames);
        if (! is_numeric($this->aspectRatio)) $safeAttr[] = $this->aspectRatio;

        // add validation rules to model
        $vals = $owner->getValidators();
        $vals[] = new FileValidator(array_merge($this->fileValidation, [
            'attributes' => [ $this->fileAttribute ],
            'extensions'=>'jpg, jpeg, gif, png',
            'skipOnEmpty' => true
        ]));
        $vals[] = new SafeValidator([
            'attributes' => $safeAttr
        ]);
    }

    public function beforeValidate($event)  {
        $upl = new UploadedFile();
        $this->_file = $upl->getInstance($this->owner, $this->fileAttribute);
        if (! $this->_file->hasError)   {

            $owner = $this->owner;

            // Determine aspect ratio
            if (is_numeric($this->aspectRatio))   {
                $asp = $this->aspectRatio;
{'fraction_non_alphanumeric': 0.11938470957373537, 'fraction_numerical': 0.0065814647585520775, 'mean_word_length': 2.561733442354865, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 95, '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': '6367357', 'n_tokens_mistral': 3857, 'n_tokens_neox': 3721, 'n_words': 1275}