<?php

// +---------------------------------------------------------------------------+
// | This file is part of the Agavi package.                                   |
// | Copyright (c) 2005-2011 the Agavi Project.                                |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code. You can also view the    |
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
// |   vi: set noexpandtab:                                                    |
// |   Local Variables:                                                        |
// |   indent-tabs-mode: t                                                     |
// |   End:                                                                    |
// +---------------------------------------------------------------------------+

require_once(dirname(__FILE__) . '/AgaviTask.php');

/**
 * Writes properties to a given file.
 *
 * @package    agavi
 * @subpackage build
 *
 * @author     Noah Fontes <noah.fontes@bitextender.com>
 * @copyright  Authors
 * @copyright  The Agavi Project
 *
 * @since      1.0.0
 *
 * @version    $Id: AgaviWritepropertiesTask.php 4667 2011-05-20 12:34:58Z david $
 */
class AgaviWritepropertiesTask extends AgaviTask
{
	protected $file = null;
	protected $update = false;
	protected $properties = array();

	/**
	 * Sets the file that this property will modify.
	 *
	 * @param      PhingFile The file to modify.
	 */
	public function setFile(PhingFile $file)
	{
		$this->file = $file;
	}
	
	/**
	 * Sets whether this task will overwrite or update the file.
	 *
	 * @param      boolean Whether the file should be updated or replaced.
	 */
	public function setUpdate($update)
	{
		$this->update = StringHelper::booleanValue($update);
	}
	
	/**
	 * Creates a new property to be added to the property list.
	 */
	public function createProperty()
	{
		$property = new AgaviPropertyType();
		$this->properties[] = $property;
		return $property;
	}
	
	/**
	 * Executes the task.
	 */
	public function main()
	{
		if($this->file === null) {
			throw new BuildException('The file attribute must be set');
		}
		
		$properties = new Properties();
		if($this->update === true) {
			/* Load existing properties. */
			try {
				$properties->load($this->file);
			}
			catch(IOException $ioe) {
				/* File doesn't exist or isn't readable, so don't worry here. */
			}
		}
		
		/* Add new properties. */
		foreach($this->properties as $property) {
			foreach($property->resolve()->getProperties() as $name => $value) {
				$properties->setProperty($name, $value);
			}
		}
		
		$properties->store($this->file, 'Automatically-updated properties file ' . 
			'generated by the Agavi write-properties task');
	}
}

?>