Chinaunix首页 | 论坛 | 博客
  • 博客访问: 236661
  • 博文数量: 54
  • 博客积分: 2656
  • 博客等级: 少校
  • 技术积分: 1020
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-19 21:06
文章分类

全部博文(54)

文章存档

2016年(3)

2014年(8)

2013年(4)

2012年(2)

2011年(29)

2010年(8)

我的朋友

分类:

2010-12-19 21:34:05

最近需要用到google contact api,参考zend 资料重新写了一个google contact api 的类,基本的增加,删除,修改,查询操作。操作类及其单元测试代码如下:

 


 

<?php
/*
 * google contact api php
 * @author qintao
 * @2012-12-01
 */


require_once 'Zend/Loader.php';
Zend_Loader::loadClass ( 'Zend_Gdata' );
Zend_Loader::loadClass ( 'Zend_Gdata_ClientLogin' );
Zend_Loader::loadClass ( 'Zend_Http_Client' );
Zend_Loader::loadClass ( 'Zend_Gdata_Query' );
Zend_Loader::loadClass ( 'Zend_Gdata_Feed' );

class contact {
 private $client;
 public $gdata;
 public $doc;
 public $url_delete = '%user/base/%id';
 public $url_search = '%user/full/%id';
 public $url_edit = 'default/full/%id';
 public $user;
 public $password;
 public $domain = '@gmail';
 
 function __construct($user, $password) {
  // perform login and set protocol version to 3.0

  try {
   $this->user = $user;
   $this->password = $password;
   $this->client = Zend_Gdata_ClientLogin::getHttpClient ( $this->user, $this->password, 'cp' );
   $this->gdata = new Zend_Gdata ( $this->client );
   $this->gdata->setMajorProtocolVersion ( 3 );
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function addContact(array $array) {
  try {
   $this->doc = new DOMDocument ();
   $this->doc->formatOutput = true;
   $entry = $this->doc->createElement ( 'atom:entry' );
   $entry->setAttributeNS ( '', 'xmlns:atom', '' );
   $entry->setAttributeNS ( '', 'xmlns:gd', '' );
   $entry->setAttributeNS ( '', 'xmlns:batch', '' );
   
   $this->doc->appendChild ( $entry );
   
   // add name element

   $name = $this->doc->createElement ( 'gd:name' );
   $entry->appendChild ( $name );
   $firstName = $this->doc->createElement ( 'gd:firstName', $array ['firstName'] );
   $name->appendChild ( $firstName );
   $lastName = $this->doc->createElement ( 'gd:middleName', $array ['middleName'] );
   $name->appendChild ( $lastName );
   $middleName = $this->doc->createElement ( 'gd:lastName', $array ['lastName'] );
   $name->appendChild ( $middleName );
   $fullName = $this->doc->createElement ( 'gd:fullName', $array ['lastName'] . $array ['middleName'] . $array ['firstName'] );
   $name->appendChild ( $fullName );
   
   // add email element

   for($i = 0; $i < count ( $array ['email'] ); $i ++) {
    $email = $this->doc->createElement ( "gd:email" );
    $email->setAttribute ( 'address', $array ["email"] [$i] );
    $email->setAttribute ( 'rel', '#' . self::getType ( $i ) );
    $entry->appendChild ( $email );
   }
   for($i = 0; $i < count ( $array ['phoneNumber'] ); $i ++) {
    $phoneNumber = $this->doc->createElement ( "gd:phoneNumber", $array ['phoneNumber'] [$i] );
    $phoneNumber->setAttribute ( 'rel', '#' . self::getType ( $i ) );
    $entry->appendChild ( $phoneNumber );
   }
   
   //var_dump($this->doc->saveXML ());

   // insert entry

   $entryResult = $this->gdata->insertEntry ( $this->doc->saveXML (), 'default/full' );
   return $entryResult->id;
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function deleteContact($id) {
  try {
   $id = str_replace ( array ('%user', '%id' ), array ($this->user . $this->domain, $id ), $this->url_delete );
   $this->client->setHeaders ( 'If-Match: *' );
   $this->gdata = new Zend_Gdata ( $this->client );
   $this->gdata->setMajorProtocolVersion ( 3 );
   
   // delete entry

   $this->gdata->delete ( $id );
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function getContact($id) {
  try {
   // perform query and get feed of all results

   $id = str_replace ( array ('%user', '%id' ), array ($this->user . $this->domain . ".com", $id ), $this->url_search );
   $feed = $this->gdata->getEntry ( $id );
   $xml = simplexml_load_string ( $feed->getXML () );
   
   $results = array ();
   
   $obj = new stdClass ();
   $obj->edit = $feed->getEditLink ()->href;
   $xml = simplexml_load_string ( $feed->getXML () );
   $obj->name = ( string ) $feed->title;
   $obj->orgName = ( string ) $xml->organization->orgName;
   $obj->orgTitle = ( string ) $xml->organization->orgTitle;
   
   foreach ( $xml->email as $e ) {
    $obj->emailAddress [] = ( string ) $e ['address'];
   }
   
   foreach ( $xml->phoneNumber as $p ) {
    $obj->phoneNumber [] = ( string ) $p;
   }
   foreach ( $xml->website as $w ) {
    $obj->website [] = ( string ) $w ['href'];
   }
   
   foreach ( $xml->structuredPostalAddress as $s ) {
    $obj->formattedAddress [] = ( string ) $s->formattedAddress;
   }
   $results [] = $obj;
   print_r ( $results );
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function getContactAll() {
  try {
   // perform query and get feed of all results

   $query = new Zend_Gdata_Query ( 'default/full' );
   $query->maxResults = 0;
   $query->setParam ( 'orderby', 'lastmodified' );
   $query->setParam ( 'sortorder', 'descending' );
   $feed = $this->gdata->getFeed ( $query );
   $results = array ();
   foreach ( $feed as $entry ) {
    $obj = new stdClass ();
    $obj->edit = $entry->getEditLink ()->href;
    $obj->id = end(explode("/", $entry->edit));
    $xml = simplexml_load_string ( $entry->getXML () );
    $obj->name = ( string ) $entry->title;
    $obj->edited = (string)$xml->edited;
    $obj->orgName = ( string ) $xml->organization->orgName;
    $obj->orgTitle = ( string ) $xml->organization->orgTitle;
    
    foreach ( $xml->email as $e ) {
     $obj->emailAddress [] = ( string ) $e ['address'];
    }
    
    foreach ( $xml->phoneNumber as $p ) {
     $obj->phoneNumber [] = ( string ) $p;
    }
    foreach ( $xml->website as $w ) {
     $obj->website [] = ( string ) $w ['href'];
    }
    
    $results [] = $obj;
   }
   //print_r($results);

   return $results;
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function editContact($id, array $array) {
  try {
   $this->client->setHeaders ( 'If-Match: *' );
   $this->gdata->setMajorProtocolVersion ( 3 );
   // perform query and get entry

   $id = str_replace('%id', $id, $this->url_edit);
   $query = new Zend_Gdata_Query ( $id );
   $entry = $this->gdata->getEntry ( $query );
   $xml = simplexml_load_string ( $entry->getXML () );
   
   //edit

   if(!empty($array))
   {
    foreach ($array as $key=>$val)
    {
     if($key == 'name'){
      $this->nameEdit(&$xml, $val);
     }elseif($key == 'phoneNumber')
     {
      $this->phoneNumberEdit(&$xml, $val);
     }elseif($key == 'email'){
      $this->emailEdit(&$xml, $val);
     }elseif($key == 'address')
     {
      $this->addressEdit(&$xml, $val);
     }
    }
   }
   $entryResult = $this->gdata->updateEntry($xml->saveXML(), $entry->getEditLink()->href);
  } catch ( Exception $e ) {
   die ( 'ERROR:' . $e->getMessage () );
  }
 }
 
 public function nameEdit($xml,$val)
 {
  if(count($val) > 0)
  {
   
   if(isset($val['firstName']) && !empty($val['firstName']))
   {
     $xml->name->familyName = $val['firstName'];
   }
   if(isset($val['lastName']) && !empty($val['lastName'])){
     $xml->name->givenName = $val['lastName'];
   }
   if(isset($val['middleName'])) $xml->name->additionalName = $val['middleName'];
   $xml->name->fullName = $val['firstName'].$val['middleName'].$val['lastName'];
  }else{
   return;
  }
 }
 
 public function phoneNumberEdit($xml,$val)
 {
  if(count($val) > 0)
  {
   foreach ($val as $k=>$v)
   {
    if(isset($val[$k]) && !empty($val[$k])) $xml->phoneNumber[$k] = $val[$k];
   }
  }else{
   return;
  }
 }
 
 public function emailEdit($xml,$val)
 {
  if(count($val) > 0)
  {
   foreach ($val as $k=>$v)
   {
    if(isset($val[$k]) && !empty($val[$k])) $xml->email[$k]['address'] = $val[$k];
   }
  }else{
   return;
  }
 }
 
 public function addressEdit($xml,$val)
 {
  if(count($val) > 0)
  {
   foreach ($val as $k=>$v)
   {
    if(isset($val[$k]) && !empty($val[$k])) $xml->structuredPostalAddress[$k]->formattedAddress = $val[$k];
   }
  }else{
   return;
  }
 }
 
 public static function getType($i, $application = 'email') {
  if ($application == 'email' && $i > 1)
   $i = 10;
  switch ($i) {
   case 0 :
    $type = 'home';
    break;
   case 1 :
    $type = 'work';
    break;
   case 2 :
    $type = 'mobile';
    break;
   default :
    $type = 'other';
    break;
  }
  
  empty ( $type ) && $type = 'other';
  return $type;
 }
}
?>

单元测试用例:

<?php

require_once 'contact\contact.class.php';

require_once 'PHPUnit\Framework\TestCase.php';

/**
 * contact test case.
 */

class contactTest extends PHPUnit_Framework_TestCase {
 
 /**
  * @var contact
  */

 private $contact;
 
 /**
  * Prepares the environment before running a test.
  */

 protected function setUp() {
  parent::setUp ();
  $this->contact = new contact ( "user", "password" );
 }
 
 /**
  * Cleans up the environment after running a test.
  */

 protected function tearDown() {
  // TODO Auto-generated contactTest::tearDown()

  

  $this->contact = null;
  
  parent::tearDown ();
 }
 
 /**
  * Constructs the test case.
  */

 public function __construct() {
  // TODO Auto-generated constructor

 }
 
 /**
  * Tests contact->__construct()
  */

 public function test__construct() {
  // TODO Auto-generated contactTest->test__construct()

  $this->markTestIncomplete ( "__construct test not implemented" );
  
  $this->contact->__construct(/* parameters */);
 
 }
 
 /**
  * Tests contact->addContact()
  */

 public function testAddContact() {
  $this->contact->addContact(array("firstName"=>"tao","middleName"=>"123","lastName"=>"qin",
       "email"=>array("qqsheji@126.com","qintao@k-toucn.cn","qintao@126.com"),
       "phoneNumber"=>array('13811111111','13822222222','13833333333')
       ));
 }
 
 /**
  * Tests contact->deleteContact()
  */

 public function testDeleteContact() {
  // TODO Auto-generated contactTest->testDeleteContact()

  $this->markTestIncomplete ( "deleteContact test not implemented" );
  
  $this->contact->deleteContact(/* parameters */);
 
 }
 
 /**
  * Tests contact->getContact()
  */

 public function testGetContact() {
  // TODO Auto-generated contactTest->testGetContact()

  $this->markTestIncomplete ( "getContact test not implemented" );
  
  $this->contact->getContact(/* parameters */);
 
 }
 
 /**
  * Tests contact->getContactAll()
  */

 public function testGetContactAll() {
  $this->contact->getContactAll();
 }
 
 /**
  * Tests contact->editContact()
  */

 public function testEditContact() {
  $this->contact->editContact ( '6728ee858ad54a80',array("name"=>array("lastName"=>6,"firstName"=>4,"middleName"=>5),"phoneNumber"=>array(1=>"13822222222"),"email"=>array(1=>"1@gmail.com",2=>"2@gmail.com"),'address'=>array(1=>'天津')));
 }
 
 /**
  * Tests contact->nameEdit()
  */

 public function testNameEdit() {
  // TODO Auto-generated contactTest->testNameEdit()

  $this->markTestIncomplete ( "nameEdit test not implemented" );
  
  $this->contact->nameEdit(/* parameters */);
 
 }
 
 /**
  * Tests contact->phoneNumberEdit()
  */

 public function testPhoneNumberEdit() {
  // TODO Auto-generated contactTest->testPhoneNumberEdit()

  $this->markTestIncomplete ( "phoneNumberEdit test not implemented" );
  
  $this->contact->phoneNumberEdit(/* parameters */);
 
 }
 
 /**
  * Tests contact->emailEdit()
  */

 public function testEmailEdit() {
  // TODO Auto-generated contactTest->testEmailEdit()

  $this->markTestIncomplete ( "emailEdit test not implemented" );
  
  $this->contact->emailEdit(/* parameters */);
 
 }
 
 /**
  * Tests contact->addressEdit()
  */

 public function testAddressEdit() {
  // TODO Auto-generated contactTest->testAddressEdit()

  $this->markTestIncomplete ( "addressEdit test not implemented" );
  
  $this->contact->addressEdit(/* parameters */);
 
 }
 
 /**
  * Tests contact::getType()
  */

 public function testGetType() {
  // TODO Auto-generated contactTest::testGetType()

  $this->markTestIncomplete ( "getType test not implemented" );
  
  contact::getType(/* parameters */);
 
 }

}


阅读(1699) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~