<?php
namespace NMS;

class bg_emailsperhour
{
    private $limit;

    public function __construct( $limit )
    {
        $this->limit = (int) $limit;
    }

    protected function get_file( $key )
    {
        $fn = 'eph'.md5(__CLASS__.$key).'.dat';
        return TMP_CACHE_LOCATION.'/'.$fn;
    }

    protected function get( $key )
    {
        $fn = $this->get_file( $key );
        $n = 0;
        if( is_file( $fn ) ) return (int) file_get_contents( $fn );
    }

    protected function set( $key, $val )
    {
        $val = (int) $val;
        $val = max(0,$val);
        $fn = $this->get_file( $key );
        if( $val == 0 ) {
            if( is_file( $fn ) ) unlink( $fn );
        } else {
            file_put_contents( $fn, $val );
        }
    }

    public function under_email_limit()
    {
        $key = date('YzH');
        $n = $this->get( $key );
        return ( $this->limit < 1 || $n < $this->limit ) ? TRUE : FALSE;
    }

    public function record_email()
    {
        $key = date('YzH');
        $n = $this->get( $key );
        $this->set( $key, $n+1 );
    }
} // end of class