Skip to content
Snippets Groups Projects
Select Git revision
  • 83f57709ed4078a2c7c941be69a92924967af356
  • main default protected
  • devel
  • 1.0.0
4 results

ConditionInterface.php

Blame
  • EmailSender.php 2.19 KiB
    <?php
    
    namespace WPDesk\Library\WPEmail\Emails;
    
    use WPDesk\Library\WPEmail\Abstracts\EmailGettersInterface;
    
    class EmailSender {
    
        /**
         * @var EmailGettersInterface[]
         */
        private $emails = [];
    
        /**
         * @var string
         */
        private $from;
    
        /**
         * @var string
         */
        private $from_name;
    
        /**
         * @param $from
         * @param $from_name
         */
        public function __construct( $from = '', $from_name = '' ) {
            $this->from      = $from;
            $this->from_name = $from_name;
        }
    
        public function add_email( Email $email ) {
            $this->emails[ $email->get_id() ] = $email;
        }
    
        public function get_emails(): array {
            return $this->emails;
        }
    
        /**
         * WordPress callback for setting the from email
         *
         * @param string $email
         *
         * @return string
         */
        public function from( $email ) {
            if ( ! empty( $this->from ) && is_email( $this->from ) ) {
                $email = $this->from;
            }
    
            return $email;
        }
    
        /**
         * WordPress callback for setting the from name
         *
         * @param string $name
         *
         * @return string
         */
        public function from_name( $name ) {
            if ( ! empty( $this->from_name ) ) {
                $name = html_entity_decode( sanitize_text_field( $this->from_name ) );
            }
    
            return $name;
        }
    
        /**
         * Add filters before fire wp_mail.
         *
         * @return void
         */
        private function before_wp_mail() {
            add_filter( 'wp_mail_from', array( $this, 'from' ) );
            add_filter( 'wp_mail_from_name', array( $this, 'from_name' ) );
        }
    
        public function send() {
            foreach ( $this->get_emails() as $email ) {
                $this->before_wp_mail();
                wp_mail(
                    $email->get_recipients(), $email->get_subject(), $email->render(), $email->get_headers(), $email->get_attachments()
                );
                $this->after_wp_mail();
            }
        }
    
        /**
         * Remove filters after fire wp_mail.
         *
         * @return void
         */
        private function after_wp_mail() {
            remove_filter( 'wp_mail_from', array( $this, 'from' ) );
            remove_filter( 'wp_mail_from_name', array( $this, 'from_name' ) );
        }
    
    }