<?php
/**
 * 
 * @author Jérôme Brilland
 * @version 1.0.2
 * @copyright (c) 2018-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class ExtraColumnsObserver implements SplObserver {

    protected $columnName = '';

    /**
     * Class constructor
     * @param string $columnName
     * @access public
     */
    public function __construct( $columnName ) {
        $this->columnName = $columnName;
    }

    /**
     * Receive update from subject
     * @param SplSubject $subject
     * @param string $key
     * @return boolean
     * @access public
     */
    public function update( SplSubject $subject, $key = null ) {
        $columnName = $this->columnName;
        if ( 'after_find' == $key ) {
            if ( !empty( $subject->$columnName ) ) {
                foreach ( JSONHandler::decode( $subject->$columnName, true ) as $name => $value ) {
                    $subject->$name = $value;
                }
            }
        } else if ( ( 'insert' == $key ) || ( 'update' == $key ) ) {
            $columns = array_diff_key( $subject->getAttributes(), array_fill_keys( $subject->getColumnNames(), null ) );
            foreach ( $columns as $name => $value ) {
                unset( $subject->$name );
            }
            if ( count( $columns ) ) {
                $subject->$columnName = JSONHandler::encode( $columns );
            }
        }
        return true;
    }

}
