public static function getBestMapping($codeName, $consumerName = null, $personTypeId = null)
 {
     if (!($codeName && is_string($codeName))) {
         throw new ArgumentTypeException('codeName', 'string>""');
     }
     if (!($consumerName === null || is_string($consumerName) && $consumerName != '')) {
         throw new ArgumentTypeException('consumerName', 'string>""|null');
     }
     if (!($personTypeId === null || is_numeric($personTypeId) && $personTypeId > 0)) {
         throw new ArgumentTypeException('personTypeId', 'int>0|null');
     }
     $personTypeId = (int) $personTypeId;
     $result = BusinessValueTable::getList(array('select' => array('ID', 'CODE_NAME', 'CONSUMER_NAME', 'PERSON_TYPE_ID', 'PROVIDER_NAME', 'PROVIDER_FIELD'), 'filter' => array('=CODE_NAME' => $codeName, '=CONSUMER_NAME' => $consumerName ? array($consumerName, null) : null, '=PERSON_TYPE_ID' => $personTypeId ? array($personTypeId, null) : null), 'limit' => $consumerName && $personTypeId ? 4 : ($consumerName || $personTypeId ? 2 : 1)));
     $bestRow = null;
     $bestWeight = -1;
     while ($row = $result->fetch()) {
         $weight = 0;
         // TODO check weight logic!
         if ($row['CONSUMER_NAME'] === $consumerName) {
             $weight += 10;
         } elseif ($row['CONSUMER_NAME'] === null) {
             $weight += 1;
         }
         if ($row['PERSON_TYPE_ID'] === $personTypeId) {
             $weight += 10;
         } elseif ($row['PERSON_TYPE_ID'] === null) {
             $weight += 1;
         }
         if ($weight > $bestWeight) {
             $bestRow = $row;
             $bestWeight = $weight;
         }
     }
     return $bestRow;
 }
 /**
  * @param string $parentName - parent identifier
  * @param string $translationSource
  * @param array $data - GROUP => ()
  * @return bool - true on success or false on failure
  * @throws SystemException
  */
 static function install($parentName, $translationSource, array $data)
 {
     $error = false;
     // load person types
     $persons = array();
     $result = PersonTypeTable::getList(array('select' => array('ID')));
     while ($row = $result->fetch()) {
         $persons[$row['ID']] = true;
     }
     // load person domains
     $personsDomains = array();
     $result = BusinessValuePersonDomainTable::getList(array('select' => array('PERSON_TYPE_ID', 'DOMAIN')));
     while ($row = $result->fetch()) {
         $personsDomains[$row['PERSON_TYPE_ID']] = $row['DOMAIN'];
     }
     // install person domains
     if (is_array($data['PERSON_DOMAIN'])) {
         foreach ($data['PERSON_DOMAIN'] as $personId => $domain) {
             if (!$persons[$personId]) {
                 throw new SystemException("invalid person type `{$personId}`", 0, __FILE__, __LINE__);
             }
             switch ($domain) {
                 case self::COMMON_DOMAIN:
                 case self::INDIVIDUAL_DOMAIN:
                 case self::ENTITY_DOMAIN:
                     break;
                 default:
                     throw new SystemException("invalid domain: {$domain}", 0, __FILE__, __LINE__);
             }
             if (!$personsDomains[$personId]) {
                 if (BusinessValuePersonDomainTable::add(array('PERSON_TYPE_ID' => $personId, 'DOMAIN' => $domain))->isSuccess()) {
                     $personsDomains[$personId] = $domain;
                 } else {
                     $error = true;
                 }
             }
         }
     }
     $personsDomainsWithCommon = array(self::COMMON_PERSON_ID => self::COMMON_DOMAIN) + $personsDomains;
     // load groups
     $groups = array();
     $result = BusinessValueGroupTable::getList(array('select' => array('NAME', 'ID')));
     while ($row = $result->fetch()) {
         $groups[$row['NAME']] = $row['ID'];
     }
     // install new groups
     if (is_array($data['GROUPS'])) {
         foreach ($data['GROUPS'] as $groupName => $group) {
             if (!$groups[$groupName]) {
                 if (!is_string($groupName)) {
                     throw new SystemException("invalid group name", 0, __FILE__, __LINE__);
                 }
                 if (!is_array($group)) {
                     throw new SystemException("invalid group", 0, __FILE__, __LINE__);
                 }
                 $result = BusinessValueGroupTable::add(array('NAME' => $groupName, 'SORT' => $group['SORT']));
                 if ($result->isSuccess()) {
                     $groups[$groupName] = $result->getId();
                 } else {
                     $error = true;
                 }
             }
         }
     }
     // install codes
     if (is_array($data['CODES'])) {
         // get parent id, install parent if not exists
         if ($row = BusinessValueParentTable::getList(array('select' => array('ID'), 'filter' => array('=NAME' => $parentName)))->fetch()) {
             $parentId = $row['ID'];
         } else {
             $result = BusinessValueParentTable::add(array('NAME' => $parentName, 'LANG_SRC' => $translationSource));
             if ($result->isSuccess()) {
                 $parentId = $result->getId();
             } else {
                 return false;
             }
         }
         // load codes
         $codes = array();
         $result = BusinessValueCodeTable::getList(array('select' => array('ID', 'NAME')));
         while ($row = $result->fetch()) {
             $codes[$row['NAME']] = $row['ID'];
         }
         // load value maps
         $valueMaps = array();
         $result = BusinessValueTable::getList(array('select' => array('CODE_ID', 'PERSON_TYPE_ID')));
         while ($row = $result->fetch()) {
             $valueMaps[$row['CODE_ID']][$row['PERSON_TYPE_ID']] = true;
         }
         // load parent codes
         $parentCodes = array();
         $result = BusinessValueCodeParentTable::getList(array('select' => array('CODE_ID'), 'filter' => array('=PARENT_ID' => $parentId)));
         while ($row = $result->fetch()) {
             $parentCodes[$row['CODE_ID']] = true;
         }
         // install: groups, codes, parent codes
         foreach ($data['CODES'] as $codeName => $code) {
             if (!is_string($codeName)) {
                 throw new SystemException("invalid code name", 0, __FILE__, __LINE__);
             }
             if (!is_array($code)) {
                 throw new SystemException("invalid code", 0, __FILE__, __LINE__);
             }
             // get group id, install group if not exists
             $groupId = null;
             if (($groupName = $code['GROUP']) && !($groupId = $groups[$groupName])) {
                 $result = BusinessValueGroupTable::add(array('NAME' => $groupName));
                 if ($result->isSuccess()) {
                     $groups[$groupName] = $groupId = $result->getId();
                 } else {
                     $error = true;
                 }
             }
             // get code domain
             switch ($domain = $code['DOMAIN']) {
                 case self::COMMON_DOMAIN:
                 case self::INDIVIDUAL_DOMAIN:
                 case self::ENTITY_DOMAIN:
                     break;
                 default:
                     throw new SystemException("invalid domain: {$domain}", 0, __FILE__, __LINE__);
             }
             // get code id, install code if not exists
             if (!($codeId = $codes[$codeName])) {
                 $result = BusinessValueCodeTable::add(array('NAME' => $codeName, 'DOMAIN' => $domain, 'GROUP_ID' => $groupId, 'SORT' => $code['SORT']));
                 if ($result->isSuccess()) {
                     $codeId = $result->getId();
                     $codes[$codeName] = $codeId;
                 } else {
                     $error = true;
                     continue;
                 }
             }
             // install value maps if not exist
             if (is_array($code['MAP'])) {
                 foreach ($code['MAP'] as $personId => $map) {
                     if (!is_array($map) || count($map) != 2) {
                         throw new SystemException("invalid map: " . print_r($map, true), 0, __FILE__, __LINE__);
                     }
                     if ($domain === self::COMMON_DOMAIN) {
                         if (!$personsDomainsWithCommon[$personId]) {
                             throw new SystemException("invalid person type id `{$personId}`", 0, __FILE__, __LINE__);
                         }
                     } else {
                         if ($domain !== $personsDomains[$personId]) {
                             throw new SystemException("invalid person type id `{$personId}`", 0, __FILE__, __LINE__);
                         }
                     }
                     if (!isset($valueMaps[$codeId][$personId])) {
                         if (BusinessValueTable::add(array('PERSON_TYPE_ID' => $personId, 'CODE_ID' => $codeId, 'ENTITY' => $map[0], 'ITEM' => $map[1]))->isSuccess()) {
                             $valueMaps[$codeId][$personId] = true;
                         } else {
                             $error = true;
                         }
                     }
                 }
             }
             // install code parent if not exists
             if (!$parentCodes[$codeId]) {
                 if (BusinessValueCodeParentTable::add(array('CODE_ID' => $codeId, 'PARENT_ID' => $parentId))->isSuccess()) {
                     $parentCodes[$codeId] = true;
                 } else {
                     $error = true;
                 }
             }
         }
     }
     return !$error;
 }
                        }
                    }
                    unset($postedCode[$personId]);
                } else {
                    $data = array('CODE_ID' => $codeId, 'PERSON_TYPE_ID' => $personId, 'ENTITY' => $postedMap['ENTITY'], 'ITEM' => $postedMap['ITEM']);
                    if ($mapId = $map['ID']) {
                        if ($postedMap['ENTITY'] == $map['ENTITY'] && $postedMap['ITEM'] == $map['ITEM']) {
                            continue;
                        } else {
                            $result = BusinessValueTable::update($mapId, $data);
                        }
                    } else {
                        if ($map) {
                            continue;
                        } else {
                            $result = BusinessValueTable::add($data);
                        }
                    }
                    if ($result->isSuccess()) {
                        $map['ID'] = $result->getId();
                        $map['ENTITY'] = $postedMap['ENTITY'];
                        $map['ITEM'] = $postedMap['ITEM'];
                    } else {
                        $errors['MAP'][$personId][$codeId]['DATABASE'] = $result->getErrorMessages();
                    }
                }
            }
        }
        unset($postedCode, $code, $postedMap, $map);
    }
} else {