<?php
/**
 * @copyright  2013 Roberto Perpuly
 *
 * This source may not be redistributed without prior consent.  Access to the 
 * source does not imply that you have consent to redistribute either this source
 * code or the generated binary. See LICENSE file for details.
 */

/**
 * This class will take care of inserting and deleting from the
 * detected_tags table.
 */
class Triumph_DetectedTagTable extends Zend_Db_Table_Abstract {

	protected $_name = 'detected_tags';
	
	/**
	 * Saves all of the tags into the database
	 *
	 * @param Triumph_DetectedTag[] $allTags the tags to save
	 */
	public function saveTags($allTags, $sourceDir) {
		
		// remove all tags from previous detection. since there is no
		// easy way to tell of duplicates
		$sourceDbTable = new Triumph_SourceTable($this->getAdapter());
		$sourceId = $sourceDbTable->getOrSave($sourceDir);
		$strWhere = $this->getAdapter()->quoteInto("source_id = ?", $sourceId);
		$this->delete($strWhere);
		
		if (empty($allTags)) {
			return ;
		}
				
		// sqlite optimizes transactions really well; use transaction so that the inserts are faster
		$this->getAdapter()->beginTransaction();
		foreach ($allTags as $tag) {
			
			// insert twice; once fully qualified and once
			// just the method name; that way qualified lookups
			// work 
			$this->insert(array(
				'source_id' => $sourceId,
				'key' => $tag->className . '::' . $tag->identifier,
				'type' => $tag->type,
				'class_name' => $tag->className,
				'method_name' => $tag->identifier,
				'return_type' => $tag->returnType,
				'namespace_name' => $tag->namespaceName,
				'signature' => $tag->signature,
				'comment' => $tag->comment,
				'is_static' => $tag->isStatic,
			));
			
			$this->insert(array(
				'source_id' => $sourceId,
				'key' => $tag->identifier,
				'type' => $tag->type,
				'class_name' => $tag->className,
				'method_name' => $tag->identifier,
				'return_type' => $tag->returnType,
				'namespace_name' => $tag->namespaceName,
				'signature' => $tag->signature,
				'comment' => $tag->comment,
				'is_static' => $tag->isStatic,
			));
		}
		$this->getAdapter()->commit();
 	}
}
