moongate2kantorterms.php 2.86 KB
<?php

function mg2kt_moongate_offices() {
    drush_log("Getting office data from moon_gate_pegawai table", "info");

    $result = db_query("
        SELECT
            kd_kantor, nm_kantor,
            kd_jns_kantor, jns_kantor,
            kd_kpp
        FROM moon_gate_pegawai
        GROUP BY kd_kantor
        ORDER BY modified DESC
    ");

    return $result;
}

function mg2kt_vocabulary_kantor() {
    static $vocabulary = null;

    if (!$vocabulary) {
        drush_log("Load vocabulary information", "info");
        $vocabulary = taxonomy_vocabulary_machine_name_load("kantor");
    }
    return $vocabulary;
}

function mg2kt_load_term($kd_kantor) {
    $vocabulary = mg2kt_vocabulary_kantor();

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', "taxonomy_term");
    $query->propertyCondition('vid', $vocabulary->vid);
    $query->fieldCondition('field_kd_kantor', 'value', $kd_kantor);


    $result = $query->execute();
    if (!$result) {
        return;
    }

    $tids = array_keys($result["taxonomy_term"]);
    $terms = taxonomy_term_load_multiple($tids);

    $term = array_shift($terms);
    return $term;
}

function mg2kt_field_value($entity, $field_name, $language = "und") {
    return $entity->{"$field_name"}[$language][0]['value'];
}

### MAIN ###
if (!function_exists("drush_main")) {
    return;
}

$offices = mg2kt_moongate_offices();

while ($office = $offices->fetchAssoc()) {
    drush_log($office['kd_kantor'] . " " . $office['nm_kantor'], "info");

    $modified = false;

    $term = mg2kt_load_term($office['kd_kantor']);
    if (!$term) {
        drush_log("Missing term detected on " . $office['kd_kantor'] . " " . $office['nm_kantor'], "warning");
        continue;
    }

    if ($office['kd_jns_kantor'] != mg2kt_field_value($term, 'field_kode_jenis_kantor')) {
        drush_log("JNS inconsistency detected on " . $office['kd_kantor'] . " " . $office['nm_kantor'], "warning");
        drush_log("moongate: " . $office['kd_jns_kantor'] . " taxonomy: " . mg2kt_field_value($term, 'field_kode_jenis_kantor'), "warning");
        continue;
    }

    if ($office['kd_kpp'] != mg2kt_field_value($term, 'field_kd_kpp')) {
        drush_log("KD_KPP inconsistency detected on " . $office['kd_kantor'] . " " . $office['nm_kantor'], "warning");
        drush_log("moongate: " . $office['kd_kpp'] . " taxonomy: " . mg2kt_field_value($term, 'field_kd_kpp'), "warning");
    }

    if ($office['nm_kantor'] != $term->name) {
        drush_log('Modified name detected', "notice");
        drush_log('Old name: "' . $term->name . '"', "notice");
        drush_log('New name: "' . $office["nm_kantor"] . '"', "notice");

        drush_log("Replacing old name", "notice");

        $term->name = $office['nm_kantor'];
        $modified = true;
    }

    if ($modified) {
        drush_log("Saving modified data", "ok");
        taxonomy_term_save($term);
    }
}