<?PHP

#
#   FILE:  VocabularyFactory.php
#
#   Part of the Collection Workflow Integration System
#   Copyright 2007-2009 Edward Almasy and Internet Scout
#   http://scout.wisc.edu
#

/**
* Factory for manipulating Vocabulary objects.
*/
class VocabularyFactory {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    /**
    * object constructor
    * @param $Path path to directory containing .voc controlled vocabulary files
    */
    function VocabularyFactory($Path)
    {
        $this->Path = $Path;
    }

    /**
    * load vocabulary objects from files
    * @return Array of Vocabulary objects.
    * @note Vocabularies are returned sorted by name.
    */
    function GetVocabularies()
    {
        # load vocabularies (if any)
        $Vocabularies = array();
        $VocFileNames = $this->GetFileList();
        foreach ($VocFileNames as $FileName)
        {
            $Vocabularies[] = new Vocabulary($FileName);
        }

        # sort vocabularies by name
        function SORT_VocabularyFactory_GetVocabularies($VocA, $VocB)
        {
            $NameA = $VocA->Name();
            $NameB = $VocB->Name();
            return ($NameA == $NameB) ? 0 : (($NameA < $NameB) ? -1 : 1);
        }
        usort($Vocabularies, "SORT_VocabularyFactory_GetVocabularies");

        # return array of vocabularies to caller
        return $Vocabularies;
    }

    /**
    * retrieve vocabulary object based on hash string
    * @param $Hash Hash string for Vocabulary (returned by Hash() method).
    * @return Vocabulary object corresponding to hash, or NULL if no matching vocabulary found.
    */
    function GetVocabularyByHash($Hash)
    {
        # for each available vocabulary file
        $Vocab = NULL;
        $VocFileNames = $this->GetFileList();
        foreach ($VocFileNames as $FileName)
        {
            # if hash for vocabulary file matches specified hash
            if (Vocabulary::HashForFile($FileName) == $Hash)
            {
                # load vocabulary and stop searching file list
                $Vocab = new Vocabulary($FileName);
                break;
            }
        }

        # return matching vocabulary (if any) to caller
        return $Vocab;
    }

    # ---- PRIVATE INTERFACE -------------------------------------------------

    private $Path;

    private function GetFileList()
    {
        # read in list of vocabulary files
        $VocFiles = array();
        if (is_dir($this->Path))
        {
            $AllFiles = scandir($this->Path);
            foreach ($AllFiles as $FileName)
            {
                if (preg_match("/\\.voc\$/i", $FileName))
                {
                    $VocFiles[] = realpath($this->Path."/".$FileName);
                }
            }
        }
        return $VocFiles;
    }
}


?>
