load and validate xml file - parse to array

@throws XmlParsingException
350159
public function read(string $xmlFile): array
    {
        try {
            $dom = XmlUtils::loadFile($xmlFile, $this->xsdFile);
        } catch (\Exception $e) {
            throw new XmlParsingException($xmlFile, $e->getMessage());
        }

        return $this->parseFile($dom);
    }
1062607
private function _LoadXml() {
        $xml = new \DOMDocument;
        $filename = "APP_ROOT_DIR" . \Puzzlout\Framework\Enums\ApplicationFolderName::AppsFolderName . $this->app->name() . '/Config/menus.xml';
        if (file_exists($filename)) {
            $xml->load($filename);
        } else {
            throw new \Exception("In " . __CLASS__ . "->" . __METHOD__);
        }
        return $xml->getElementsByTagName("main_menu");
    }
486960
public function read()
    {
        $old    = libxml_use_internal_errors(true);
        $xml    = simplexml_load_file($this->path);
        $errors = libxml_get_errors();
        libxml_use_internal_errors($old);

        if (count($errors)) {
            throw new \RuntimeException('xml file \''. $this->path . '\': ' . $errors[0]->message);
        }
        return $xml;
    }
555745
public function xml2array(): void
    {
        $this->xml2json();
        $this->arrayData = json_decode($this->jsonData, TRUE);
    }
578231
protected function parseToArray( ) {
        try {
            $xml = new \SimpleXMLElement( $this->file_path, 0, true );
            //\common\components\CustomVarDamp::dumpAndDie($xml->children()->children());
            $result = $this->recursiveParseToArray( $xml );
        } catch(\Exception $ex) {

            throw $ex;
        }
        return $result;
    }
231796
public function loadFile()
    {
        $key = $this->getKey();

        $tags = $this->getTags();

        if (!$this->cache->has($key, $tags)) {
            $this->xmlRepo->loadFile();

            $XMLFile = $this->xmlRepo->getFile()->asXML();

            $this->cache->put($key, $XMLFile, $tags, $this->seconds);
        }
    }
950068
public void validateXMLString(String xml, String dtdFile, String docType) throws SAXException, IOException, ParserConfigurationException {
    validateInternal(xml, dtdFile, docType);
  }
743877
protected function init()
    {
        if ($this->request->getResponseFormat() == 'xml') {
            $aggregated = new \SimpleXMLElement('<response/>');
            foreach ($this->responseRaw as $name => $response) {
                $child = $aggregated->addChild('classification');
                $child->addAttribute('classifier', $name);
                $xml = simplexml_load_string($response);

                if (! $xml instanceof \SimpleXMLElement) {
                    throw new ServiceReaderException('Failed parsing XML response.');
                }

                if ((string) $xml->status->attributes()->success !== 'true') {
                    throw new ServiceReaderException($xml->status->attributes()->statusCode);
                }

                foreach ($xml->readCalls->classify as $classify) {
                    $child->addAttribute('textCoverage', $classify->classification->attributes()->textCoverage);
                    foreach ($classify->classification->class as $class) {
                        $this->simplexmlImportXml($child, $class->asXML());
                    }
                }
            }

            return $aggregated->asXML();
        }

        if ($this->request->getResponseFormat() == 'json') {
            $aggregated = array();
            foreach ($this->responseRaw as $name => $response) {
                $current = json_decode($response, 1);

                if (! array_key_exists('success', $current)) {
                    throw new ServiceReaderException('Unable to complete request');
                }

                if ($current['success'] !== true) {
                    throw new ServiceReaderException($current['statusCode'] . ' ' . $current['errorMessage']);
                }

                array_key_exists('textCoverage', $current) ? '' : $current['textCoverage'] = null;
                array_key_exists('cls1', $current) ? '' : $current['cls1'] = null;

                $aggregated[] = array(
                    'classifier' => $name,
                    'textCoverage' => $current['textCoverage'],
                    'classes' => $current['cls1']
                );
            }

            return json_encode($aggregated);
        }

        return $this->responseRaw;
    }
335653
protected function doParse()
    {
        // just make it work modified base class
        $this->document = $this->data;
        $object = $this->objectName;

        if (!$this->document instanceof SimpleXmlElement) {
            throw new RuntimeException('document is not instance of SimpleXmlElement');
        }

        if ('ok' !== (string) $this->document->attributes()->stat) {
            $errorCode = (integer) $this->document->err->attributes()->code;
            $errorMessage = (string) $this->document->err;

            if (in_array($errorCode, array(1, 15))) {
                throw new AuthenticationErrorException($errorMessage, $errorCode);
            } else {
                throw new RuntimeException($errorMessage, $errorCode);
            }
        }

        if ('login' == $object) {
            $this->result = (string) $this->document->api_key;
        } else {
            if (!empty($this->document->result)) {
                $this->resultCount = (integer) $this->document->result->total_results;
                $this->result = $this->document->xpath('/rsp/result/'.$object);
            } elseif (!empty($this->document->$object)) {
                $this->resultCount = 1;
                $this->result = array($this->document->$object);
            } else {
                throw new RuntimeException('Unknown response format');
            }
        }
    }
442232
public function getMessage(): array
    {
        if (!empty($this->message)) {
            return $this->message;
        }

        try {
            $message = XML::parse(strval($this->app['request']->getContent()));
        } catch (\Throwable $e) {
            throw new Exception('Invalid request XML: '.$e->getMessage(), 400);
        }

        if (!is_array($message) || empty($message)) {
            throw new Exception('Invalid request XML.', 400);
        }

        if ($this->check) {
            $this->validate($message);
        }

        return $this->message = $message;
    }
1152715
private static function array_to_xml($data = array(), &$xml_data) {
	foreach($data as $key => $value) {

	    if(is_array($value) or (is_object($value))) {
		if(!is_numeric($key)){
		    $subnode = $xml_data->addChild("$key");
		    self::array_to_xml($value, $subnode);
		}
		else{
		    $subnode = $xml_data->addChild("element");
		    self::array_to_xml($value, $subnode);
		}
	    }
	    else {
		if (is_bool($value)) {$value = $value ? "true" : "false";}
		$xml_data->addChild("$key","$value");
	    }
	}
    }
629051
protected function parseImportFile()
    {
        $importFileContent = file_get_contents($this->importFile->tempName);

        if ($this->importFile->extension == Response::FORMAT_JSON) {
            $data = Json::decode($importFileContent);
        } elseif ($this->importFile->extension == Response::FORMAT_XML) {
            $xml = simplexml_load_string($importFileContent);
            $json = json_encode($xml);
            $data = json_decode($json, true);

            //rebuild data due to simplexml merging duplicate elements
            foreach ($data as $key => $value) {
                $data[$key] = current($value);
            }
        } else {//should be caught by the form validation, but just in case
            throw new BadRequestHttpException('Only json and xml files are supported.');
        }

        return $data;
    }
629181
public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');
        Validate::isString($xmlString, 'xmlString');

        $this->fromXml(simplexml_load_string($xmlString));
    }
430387
public function parse( $xml, $validateRules = TRUE )
	{
		$this->language		= "en";
		$this->channelData	= $this->emptyChannelData;
		$this->entries		= array();
			
		$root		= new XML_Element( $xml );
		if( $validateRules )
		{
			$validator	= new XML_Atom_Validator();
			if( !$validator->isValid( $root ) )	
				throw new Exception( $validator->getFirstError() );
		}

		$this->language		= $this->getNodeLanguage( $root );
		$this->channelData	= $this->parseNodes( $root, $this->emptyChannelData );
	}
291269
protected Validation parseValidation(XMLStreamReader reader) throws XMLStreamException, 
      ParserException, 
      ValidateException
   {
      Boolean validateOnMatch = Defaults.VALIDATE_ON_MATCH;
      Boolean useFastFail = Defaults.USE_FAST_FAIL;
      Boolean backgroundValidation = Defaults.BACKGROUND_VALIDATION;
      Long backgroundValidationMillis = null;

      Map<String, String> expressions = new HashMap<String, String>();

      while (reader.hasNext())
      {
         switch (reader.nextTag())
         {
            case END_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case CommonXML.ELEMENT_VALIDATION :
                     return new ValidationImpl(validateOnMatch, backgroundValidation, backgroundValidationMillis,
                        useFastFail,
                             !expressions.isEmpty() ? expressions : null);
                  case CommonXML.ELEMENT_VALIDATE_ON_MATCH :
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS :
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION :
                  case CommonXML.ELEMENT_USE_FAST_FAIL :
                     break;
                  default :
                     throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
               }
            }
            case START_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case CommonXML.ELEMENT_VALIDATE_ON_MATCH : {
                     validateOnMatch = elementAsBoolean(reader, CommonXML.ELEMENT_VALIDATE_ON_MATCH, expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS : {
                     backgroundValidationMillis = elementAsLong(reader, CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS,
                                                                expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION : {
                     backgroundValidation = elementAsBoolean(reader, CommonXML.ELEMENT_BACKGROUND_VALIDATION,
                                                             expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_USE_FAST_FAIL : {
                     useFastFail = elementAsBoolean(reader, CommonXML.ELEMENT_USE_FAST_FAIL, expressions);
                     break;
                  }
                  default :
                     throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
               }
               break;
            }
         }
      }
      throw new ParserException(bundle.unexpectedEndOfDocument());
   }
927178
public function load()
    {
        $returnValue = array();

    	//load it using the SimpleXml library
        $xml = false;
    	switch($this->sourceType){
    	    
    		case self::SOURCE_FILE:
    		    $xml = simplexml_load_file($this->source);
    		break;
    		
    		case self::SOURCE_URL:
    			$xmlContent = tao_helpers_Request::load($this->source, true);
    			$xml = simplexml_load_string($xmlContent);
    		break;
    		
    		case self::SOURCE_STRING:
    			$xml = simplexml_load_string($this->source);
    		break;
    	}
    	
    	if ($xml !== false) {
    		
    		//get the QTI Item's resources from the imsmanifest.xml
    		$returnValue = ManifestParserFactory::getResourcesFromManifest($xml);
    		
    		if (!$this->valid) {
    			$this->valid = true;
    			libxml_clear_errors();
    		}
    	}
    	else if (!$this->valid) {
    		$this->addErrors(libxml_get_errors());
    		libxml_clear_errors();
    	}
        
        return (array) $returnValue;
    }
521802
private function validateXml() : void
    {
        if (!isset($this->xml->project) || !isset($this->xml->project->metrics)) {
            throw new RuntimeException('invalid clover xml file');
        }
    }