1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
/**
 * Imports member records, and checks/updates duplicates based on their
 * 'Email' property.
 * 
 * @package sapphire
 * @subpackage security
 */
class MemberCsvBulkLoader extends CsvBulkLoader {
	
	/**
	 * @var array Array of {@link Group} records. Import into a specific group.
	 *  Is overruled by any "Groups" columns in the import.
	 */
	protected $groups = array();
	
	function __construct($objectClass = null) {
		if(!$objectClass) $objectClass = 'Member';
		
		parent::__construct($objectClass);
	}
	
	public $duplicateChecks = array(
		'Email' => 'Email',
	);
	
	function processRecord($record, $columnMap, &$results, $preview = false) {
		$objID = parent::processRecord($record, $columnMap, $results, $preview);
		
		$_cache_groupByCode = array();
		
		// Add to predefined groups
		$member = DataObject::get_by_id($this->objectClass, $objID);
		foreach($this->groups as $group) {
			// TODO This isnt the most memory effective way to add members to a group
			$member->Groups()->add($group);
		}
		
		// Add to groups defined in CSV
		if(isset($record['Groups']) && $record['Groups']) {
			$groupCodes = explode(',', $record['Groups']);
			foreach($groupCodes as $groupCode) {
				if(!isset($_cache_groupByCode[$groupCode])) {
					$group = DataObject::get_one(
						'Group', 
						sprintf('"Code" = \'%s\'', Convert::raw2sql($groupCode))
					);
					if(!$group) {
						$group = new Group();
						$group->Code = $groupCode;
						$group->Title = $groupCode;
						$group->write();
					}
					$member->Groups()->add($group);
				}
				$_cache_groupByCode[$groupCode] = $group;
			}
		}
		
		$member->destroy();
		unset($member);
		
		return $objID;
	}
	
	/**
	 * @param Array $groups
	 */
	function setGroups($groups) {
		$this->groups = $groups;
	}
	
	/**
	 * @return Array
	 */
	function getGroups() {
		return $this->groups;
	}
}