public static function convertArrayToCsv(string $filepath, array $rows, bool $addHeader, string $delimiter = ",", string $enclosure = '"')
    {
        $fileHandle = fopen($filepath, 'w');
        
        if ($fileHandle === FALSE)
        {
            throw new \Exception("Failed to open {$filepath} for writing.");
        }
        
        if (count($rows) === 0)
        {
            throw new \Exception("Cannot create CSV file with no data.");
        }
        
        $firstRow = ArrayLib::getFirstElement($rows);
        
        if (ArrayLib::isAssoc($firstRow) === FALSE)
        {
            throw new \Exception("convertArrayToCsv expects a list of assosciative arrays.");
        }
        
        $keys = array_keys($firstRow);
        
        if ($addHeader)
        {
            fputcsv($fileHandle, $keys, $delimiter, $enclosure);
        }
        
        foreach ($rows as $index => $row)
        {
            if (count($keys) != count($row))
            {
                $msg = "Cannot convert array to CSV. Number of keys: " . count($keys) . 
                       " is not the same as the number of values: " . count($row);
                
                throw new \Exception($msg);
            }
                
            $rowOfValues = array();
            
            foreach ($keys as $key)
            {
                if (!isset($row[$key]))
                {
                    // key might be set, the value might just be null. Check for this.
                    $keys = array_keys($row);
                    
                    if (in_array($key, $keys) === FALSE)
                    {
                        throw new \Exception("row missing expected key {$key} on row {$index}");
                    }
                    else
                    {
                        $value = null;
                    }
                }
                else
                {
                    $value = $row[$key];
                }
                
                $rowOfValues[] = $value;
            }
            
            fputcsv($fileHandle, $rowOfValues, $delimiter, $enclosure);
        }
    }