#!/usr/bin/env php
<?php

$directory = new \RecursiveDirectoryIterator(__DIR__ . '/wsdls', FilesystemIterator::KEY_AS_PATHNAME
    | FilesystemIterator::CURRENT_AS_FILEINFO
    | FilesystemIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directory);

foreach ($iterator as $info) {
    if (strpos($filePath = $info->getPathname(), '.wsdl') !== false) {
        $p = xml_parser_create();

        xml_parse_into_struct($p, file_get_contents($filePath), $elements, $index);

        $data = [];
        $complexType = [];

        foreach ($elements as $key => $element) {
            if ($element['tag'] == 'COMPLEXTYPE' && $element['type'] == 'open') {
                if (array_key_exists('attributes', $element)) {
                    array_push($complexType, lcfirst($element['attributes']['NAME']));
                    $data[end($complexType)] = [];
                } else if ($elements[$key - 1]['tag'] == 'ELEMENT' && array_key_exists('attributes', $elements[$key - 1])) {
                    array_push($complexType, lcfirst($elements[$key - 1]['attributes']['NAME']));
                } else if (!end($complexType)) {
                    array_push($complexType, 'EMPTY');
                }
            }

            if (end($complexType) && end($complexType) != 'EMPTY' && $element['tag'] == 'ELEMENT' && array_key_exists('attributes', $element)) {
                $data[end($complexType)][$element['attributes']['NAME']] = $element;
            }

            if ($element['tag'] == 'COMPLEXTYPE' && $element['type'] == 'close') {
                array_pop($complexType);
            }
        }

        $typeMapFileName = basename($filePath, '.wsdl') . '-typeMap.json';

        $versionPath = ($versionPosition = strpos($filePath, '/v')) ? substr($filePath, $versionPosition, 3) . '/' : '';

        file_put_contents(__DIR__ . '/config/soap-client/' . $versionPath . $typeMapFileName, json_encode($data));
    }
}
