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

    protected $columnName = '';

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

    /**
     * Receive update from subject
     * @param ISubject $subject
     * @param string $key
     * @return boolean
     * @access public
     */
    public function update( ISubject $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;
    }

}
