1<?php 2/* Copyright (c) 1998-2017 ILIAS open source, Extended GPL, see docs/LICENSE */ 3 4/** 5 * Class ilSamlMappedUserAttributeValueParser 6 */ 7class ilSamlMappedUserAttributeValueParser 8{ 9 const ATTR_REGEX = '/^(.*?)(\|(\d+))?$/'; 10 11 /** 12 * @var \ilExternalAuthUserAttributeMappingRule 13 */ 14 protected $rule; 15 16 /** 17 * @var array 18 */ 19 protected $userData = []; 20 21 /** 22 * ilSamlMappedUserAttributeValueParser constructor. 23 * @param ilExternalAuthUserAttributeMappingRule $rule 24 * @param array $userData 25 */ 26 public function __construct(\ilExternalAuthUserAttributeMappingRule $rule, array $userData) 27 { 28 $this->rule = $rule; 29 $this->userData = $userData; 30 } 31 32 /** 33 * @return int 34 */ 35 protected function getValueIndex() 36 { 37 $index = 0; 38 39 $matches = array(); 40 preg_match(self::ATTR_REGEX, $this->rule->getExternalAttribute(), $matches); 41 42 if (is_array($matches) && isset($matches[3]) && is_numeric($matches[3])) { 43 $index = (int) $matches[3]; 44 } 45 46 return $index >= 0 ? $index : 0; 47 } 48 49 /** 50 * @return string 51 */ 52 public function getAttributeKey() 53 { 54 $attribute = ''; 55 56 $matches = array(); 57 preg_match(self::ATTR_REGEX, $this->rule->getExternalAttribute(), $matches); 58 59 if (is_array($matches) && isset($matches[1]) && is_string($matches[1])) { 60 $attribute = $matches[1]; 61 } 62 63 return $attribute; 64 } 65 66 /** 67 * @throws \ilSamlException 68 * @return mixed 69 */ 70 public function parse() 71 { 72 $attributeKey = $this->getAttributeKey(); 73 74 if (!array_key_exists($attributeKey, $this->userData)) { 75 throw new \ilSamlException(sprintf( 76 "Configured external attribute of mapping '%s' -> '%s' does not exist in SAML attribute data.", 77 $this->rule->getAttribute(), 78 $this->rule->getExternalAttribute() 79 )); 80 } 81 82 $value = $this->userData[$attributeKey]; 83 84 if (is_array($value)) { 85 $valueIndex = $this->getValueIndex(); 86 87 if (!array_key_exists($valueIndex, $value)) { 88 throw new \ilSamlException(sprintf( 89 "Configured external attribute of mapping '%s' -> '%s' does not exist in SAML attribute data.", 90 $this->rule->getAttribute(), 91 $this->rule->getExternalAttribute() 92 )); 93 } 94 95 $value = $value[$valueIndex]; 96 } 97 98 if (!is_scalar($value)) { 99 throw new \ilSamlException(sprintf( 100 "Could not parse a scalar value based on the user attribute mapping '%s' -> '%s'.", 101 $this->rule->getAttribute(), 102 $this->rule->getExternalAttribute() 103 )); 104 } 105 106 return $value; 107 } 108} 109