Collection.php 1.9 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
<?php

namespace Dotdigitalgroup\Email\Model\ResourceModel\Rules;

class Collection extends
 \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * @var string
     */
    protected $_idFieldName = 'id';

    /**
     * Initialize resource collection.
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init(
            \Dotdigitalgroup\Email\Model\Rules::class,
            \Dotdigitalgroup\Email\Model\ResourceModel\Rules::class
        );
    }

    /**
     * Reset collection.
     *
     * @return $this
     */
    public function reset()
    {
        $this->_reset();

        return $this;
    }

    /**
     * Check if rule already exist for website.
     *
     * @param int $websiteId
     * @param string $type
     * @param bool $ruleId
     *
     * @return bool
     */
    public function hasCollectionAnyItemsByWebsiteAndType($websiteId, $type, $ruleId = false)
    {
        $collection = $this->addFieldToFilter('type', ['eq' => $type])
            ->addFieldToFilter('website_ids', ['finset' => $websiteId]);

        if ($ruleId) {
            $collection->addFieldToFilter('id', ['neq' => $ruleId]);
        }
        $collection->setPageSize(1);

        if ($collection->getSize()) {
            return false;
        }

        return true;
    }

    /**
     * Get rule for website.
     *
     * @param string $type
     * @param int|array $websiteId
     *
     * @return array|\Magento\Framework\DataObject
     */
    public function getActiveRuleByWebsiteAndType($type, $websiteId)
    {
        $collection = $this->addFieldToFilter('type', ['eq' => $type])
            ->addFieldToFilter('status', ['eq' => 1])
            ->addFieldToFilter('website_ids', ['finset' => $websiteId])
            ->setPageSize(1);

        if ($collection->getSize()) {
            return $collection->getFirstItem();
        }

        return [];
    }
}