<?php

class Block extends AppModel {

	/** @inheritdoc */
	public $belongsTo = [
		'Content'
	];

	/** @inheritdoc */
	public function beforeSave($options = []) {
		if (empty($this->data[$this->alias]['id']) && empty($this->data[$this->alias]['content'])) {
			unset($this->data[$this->alias]);
		}
		if (isset($this->data[$this->alias]['content']) && preg_match('|</head><body>(?P<body>.*)</body></html>|i', $this->data[$this->alias]['content'], $match)) {
			$this->data[$this->alias]['content'] = $match['body'];
		}
		return true;
	}

	/** @inheritdoc */
	public function afterSave($created, $options = []) {
		if (isset($this->data[$this->alias]['content']) && trim($this->data[$this->alias]['content']) == '') {
			$this->delete();
		}
	}

}
