shopaholic /application/libraries/Engine/Api.php

Language PHP Lines 646
MD5 Hash 991de860ad8ab92c66a898f46252efbf
Repository https://github.com/shopaholiccompany/shopaholic.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<?php
/**
 * SocialEngine
 *
 * @category   Engine
 * @package    Engine_Api
 * @copyright  Copyright 2006-2010 Webligo Developments
 * @license    http://www.socialengine.net/license/
 * @version    $Id: Api.php 7244 2010-09-01 01:49:53Z john $
 * @author     John Boehr <j@webligo.com>
 */

/**
 * @category   Engine
 * @package    Engine_Api
 * @copyright  Copyright 2006-2010 Webligo Developments
 * @license    http://www.socialengine.net/license/
 */
class Engine_Api
{
  /**
   * The singleton Api object
   *
   * @var Engine_Api
   */
  protected static $_instance;

  /**
   * The current application instance
   * 
   * @var Engine_Application
   */
  protected $_application;

  /**
   * An array of module api objects
   * 
   * @var array
   */
  protected $_modules = array();

  /**
   * Contains the current set module name
   * @var string
   */
  protected $_currentModuleName;
  
  /**
   * @var array assoc map of item type => module
   */
  protected $_itemTypes;

  /**
   * Get or create the current api instance
   * 
   * @return Engine_Api
   */
  public static function getInstance()
  {
    if( is_null(self::$_instance) )
    {
      self::$_instance = new self();
    }
    
    return self::$_instance;
  }

  /**
   * Shorthand for getInstance
   *
   * @return Engine_Api
   */
  public static function _()
  {
    return self::getInstance();
  }

  /**
   * Set or unset the current api instance
   * 
   * @param Engine_Api $api
   * @return Engine_Api
   */
  public static function setInstance(Engine_Api $api = null) 
  {
    return self::$_instance = $api;
  }

  public function getAutoloader()
  {
    if( null === $this->_autoloader )
    {
      throw new Exception('Autoloader not set');
    }

    return $this->_autoloader;
  }

  public function setAutoloader(Engine_Application_Autoloader $autoloader)
  {
    $this->_autoloader = $autoloader;
    return $this;
  }



  // Application
  
  /**
   * Sets the current application instance
   * 
   * @param Engine_Application $application
   * @return Engine_Api
   */
  public function setApplication(Engine_Application $application)
  {
    $this->_application = $application;
    return $this;
  }

  /**
   * Gets the current application object
   * 
   * @return Engine_Application
   * @throws Engine_Api_Exception If application is not set
   */
  public function getApplication()
  {
    if( is_null($this->_application) )
    {
      throw new Engine_Api_Exception('Application instance not set');
    }
    
    return $this->_application;
  }



  // Bootstraps
  
  /**
   * Checks if the specfied module has been bootstrapped
   * 
   * @param string $name The module name
   * @return bool
   */
  public function hasModuleBootstrap($name)
  {
    return isset($this->_modules[$name]);
  }

  /**
   * Sets the local copy of a module bootstrap
   * 
   * @param Zend_Application_Module_Bootstrap $bootstrap
   * @return Engine_Api
   */
  public function setModuleBootstrap(Engine_Application_Bootstrap_Abstract $bootstrap)
  {
    $name = strtolower($bootstrap->getModuleName());
    $this->_modules[$name] = $bootstrap;
    return $this;
  }

  /**
   * Gets a module bootstrap
   * 
   * @param string $name The module name
   * @return Zend_Application_Module_Bootstrap|Zend_Application_Bootstrap_Bootstrap
   * @throws Engine_Api_Exception If module not found
   */
  public function getModuleBootstrap($name = null)
  {
    if( !$name )
    {
      $name = Zend_Controller_Front::getInstance()->getDefaultModule();
    }

    if( !isset($this->_modules[$name]) )
    {
      // Special case, default module can be detected and set
      if( $name == Zend_Controller_Front::getInstance()->getDefaultModule() )
      {
        $this->_modules[$name] = $this->getApplication()->getBootstrap();
      }

      // Normal modules must be registered manually
      else
      {
        throw new Engine_Api_Exception(sprintf('Module "%s" not found', $name));
      }
    }

    return $this->_modules[$name];
  }



  // Loading
  
  /**
   * Shorthand for loadModuleApi
   *
   * @return Engine_Application_Module_Api
   * @throws Engine_Api_Exception If given improper arguments or module is missing
   */
  public function __call($method, $args)
  {
    if( 'get' == substr($method, 0, 3) )
    {
      $type = strtolower(substr($method, 3));
      if( empty($args) )
      {
        throw new Engine_Api_Exception("Cannot load resources; no resource specified");
      }
      $resource = array_shift($args);
      $module = array_shift($args);
      if( $module === null )
      {
        if( $this->_currentModuleName === null )
        {
          throw new Engine_Api_Exception("Cannot load resources; no module specified");
        }
        else
        {
          $module = $this->_currentModuleName;
          $this->_currentModuleName = null;
        }
      }
      
      return $this->load($module, $type, $resource);
    }

    // Backwards
    if( isset($this->_modules[$method]) )
    {
      return $this->load($method, 'api', 'core');
      //return $this->load($method, 'model', 'api');
    }

    // Boo
    throw new Engine_Exception("Method '$method' is not supported");
  }

  /**
   * Used to shorten some api calls, sets the default module to load resources
   * from
   * 
   * @param string $module
   * @return Engine_Api
   */
  public function setCurrentModule($module)
  {
    if( is_string($module) )
    {
      $this->_currentModuleName = $module;
    }
    else if( is_object($module) && method_exists($object, 'getModuleName') )
    {
      $this->_currentModuleName = $object->getModuleName();
    }
    else
    {
      $this->_currentModuleName = null;
    }

    return $this;
  }

  /**
   * Loads a singleton instance of a module resource
   *
   * @param string $module The module name
   * @param string $type The resource type
   * @param string $resource The resource name
   * @return mixed The requested singleton object
   */
  public function load($module, $type, $resource)
  {
    if( strtolower($type) == 'dbtable' )
    {
      $type = 'Model_DbTable';
    }
    return Engine_Loader::getInstance()->load(ucfirst($module) . '_' . ucfirst($type) . '_' . ucfirst($resource));
    //return $this->getModuleBootstrap($module)->getResourceLoader()->load($resource, $type);
  }

  /**
   * Loads a singleton instance of a module resource using a full class name
   *
   * @param string $class The class name
   * @return mixed The requested singleton object
   */
  public function loadClass($class)
  {
    return Engine_Loader::getInstance()->load($class);
  }



  // Item handling stuff

  /**
   * Checks if the item of $type has been registered
   * 
   * @param string $type
   * @return bool
   */
  public function hasItemType($type)
  {
    $this->_loadItemInfo();
    return isset($this->_itemTypes[$type]);
  }
  
  /**
   * Gets an item given a type and identity
   * 
   * @param string $type
   * @param int $identity
   * @return Core_Model_Item_Abstract
   */
  public function getItem($type, $identity)
  {
    $this->_loadItemInfo();
    
    $api = $this->getItemApi($type);

    $method = 'get'.ucfirst($type);
    if( method_exists($api, $method) )
    {
      return $api->$method($identity);
    }
    else if( method_exists($api, 'getItem') )
    {
      return $api->getItem($type, $identity);
    }

    return $this->getItemTable($type)->find($identity)->current();
  }

  /**
   * Gets multiple items of a type from an array of ids
   * 
   * @param string $type
   * @param array $identities
   * @return Engine_Db_Table_Rowset
   */
  public function getItemMulti($type, array $identities)
  {
    $this->_loadItemInfo();
    
    $api = $this->getItemApi($type);

    $method = 'get'.ucfirst($type).'Multi';
    if( method_exists($api, $method) )
    {
      return $api->$method($identities);
    }
    else if( method_exists($api, 'getItemMulti') )
    {
      return $api->getItemMulti($type, $identities);
    }

    return $this->getItemTable($type)->find($identities);
  }
  
  /**
   * Gets an item using a guid array or string
   * 
   * @param array|string $guid
   * @return Core_Model_Item_Abstract
   * @throws Engine_Api_Exception If given improper arguments
   */
  public function getItemByGuid($guid)
  {
    $this->_loadItemInfo();
    
    if( is_string($guid) )
    {
      $guid = explode('_', $guid);
      if( count($guid) > 2 )
      {
        $id = array_pop($guid);
        $guid = array(join('_', $guid), $id);
      }
    }
    if( !is_array($guid) || count($guid) !== 2 || !is_string($guid[0]) || !is_numeric($guid[1]) )
    {
      throw new Engine_Api_Exception(sprintf('Malformed guid passed to getItemByGuid(): %s', join('_', $guid)));
    }
    return $this->getItem($guid[0], $guid[1]);
  }

  /**
   * Gets the name of the module that an item type belongs to
   * 
   * @param string $type The item type
   * @return string The module name
   * @throws Engine_Api_Exception If item type isn't registered
   */
  public function getItemModule($type)
  {
    $this->_loadItemInfo();
    
    return $this->getItemInfo($type, 'module');
  }

  /**
   * Gets info about an item
   * 
   * @param string $type The item type
   * @param string (OPTIONAL) $key The info key
   * @return mixed
   */
  public function getItemInfo($type, $key = null)
  {
    $this->_loadItemInfo();
    
    if( empty($this->_itemTypes[$type]) )
    {
      throw new Engine_Api_Exception(sprintf("Unknown item type: %s", $type));
    }
    
    if( null === $key )
    {
      return $this->_itemTypes[$type];
    }

    else if( array_key_exists($key, $this->_itemTypes[$type]) )
    {
      return $this->_itemTypes[$type][$key];
    }
    
    return null;
  }

  /**
   * Gets the class of an item
   *
   * @param string $type The item type
   * @return string The class name
   */
  public function getItemClass($type)
  {
    $this->_loadItemInfo();
    
    // Check api for overriding method
    $api = $this->getItemApi($type);
    if( method_exists($api, 'getItemClass') )
    {
      return $api->getItemClass($type);
    }

    // Generate item class manually
    $module = $this->getItemModule($type);
    return ucfirst($module) . '_Model_' . self::typeToClassSuffix($type, $module);
  }

  /**
   * Gets the class of the dbtable that an item type belongs to
   *
   * @param string $type The item type
   * @return string The table class name
   */
  public function getItemTableClass($type)
  {
    $this->_loadItemInfo();
    
    // Check api for overriding method
    $api = $this->getItemApi($type);
    if( method_exists($api, 'getItemTableClass') )
    {
      return $api->getItemTableClass($type);
    }

    // Generate item table class manually
    $module = $this->getItemInfo($type, 'moduleInflected');
    $class = $module . '_Model_DbTable_' . self::typeToClassSuffix($type, $module);
    if( substr($class, -1, 1) === 'y' ) {
      $class = substr($class, 0, -1) . 'ies';
    } else if( substr($class, -1, 1) !== 's' ) {
      $class .= 's';
    }
    return $class;
  }

  /**
   * Gets a singleton instance of the dbtable an item type belongs to
   *
   * @param string $type The item type
   * @return Engine_Db_Table The table object
   */
  public function getItemTable($type)
  {
    $this->_loadItemInfo();
    
    // Check api for overriding method
    $api = $this->getItemApi($type);
    if( method_exists($api, 'getItemTable') )
    {
      return $api->getItemTable($type);
    }

    $class = $this->getItemTableClass($type);
    return $this->loadClass($class);
  }

  /**
   * Gets the item api object that an item type belongs to
   *
   * @param string $type The item type
   * @return Engine_Application_Module_Api
   */
  public function getItemApi($type)
  {
    $this->_loadItemInfo();
    
    $module = $this->getItemInfo($type, 'moduleInflected');
    return $this->load($module, 'api', 'core');
  }

  /**
   * Load item info from manifest
   */
  protected function _loadItemInfo()
  {
    if( null === $this->_itemTypes )
    {
      $manifest = Zend_Registry::get('Engine_Manifest');
      if( null === $manifest )
      {
        throw new Engine_Api_Exception('Manifest data not loaded!');
      }
      $this->_itemTypes = array();
      foreach( $manifest as $module => $config )
      {
        if( !isset($config['items']) ) continue;
        foreach( $config['items'] as $key => $value )
        {
          if( is_numeric($key) ) {
            $this->_itemTypes[$value] = array(
              'module' => $module,
              'moduleInflected' => self::inflect($module),
            );
          } else {
            $this->_itemTypes[$key] = $value;
            $this->_itemTypes[$key]['module'] = $module;
            $this->_itemTypes[$key]['moduleInflected'] = self::inflect($module);
          }
        }
      }
    }
  }



  // Utility

  static public function inflect($string)
  {
    return str_replace(' ', '', ucwords(str_replace(array('.', '-'), ' ' , $string)));
  }

  static public function deflect($string)
  {
    return strtolower(trim(preg_replace('/([a-z0-9])([A-Z])/', '\1-\2', $string), '-. '));
    //return strtolower(trim(preg_replace('/([a-z0-9])([A-Z])/', '\1-\2', preg_replace('/[^A-Za-z0-9-]/', '', $string)), '-. '));
  }

  /**
   * Used to inflect item types to class suffix.
   * 
   * @param string $type
   * @param string $module
   * @return string
   */
  static public function typeToClassSuffix($type, $module)
  {
    $parts = explode('_', $type);
    if( count($parts) > 1 && $parts[0] === strtolower($module) )
    {
      array_shift($parts);
    }
    $partial = str_replace(' ', '', ucwords(join(' ', $parts)));
    return $partial;
  }

  /**
   * Used to inflect item class to type.
   * 
   * @param string $class
   * @param string $module
   * @return string
   * @throws Engine_Api_Exception If given improper arguments
   */
  static public function classToType($class, $module)
  {
    list($classModule, $resourceType, $resourceName)
      = explode('_', $class, 3);

    // Throw stuff
    if( strtolower($classModule) != strtolower($module) )
    {
      throw new Engine_Api_Exception('class and module do not match');
    }
    else if( $resourceType != 'Model' )
    {
      throw new Engine_Api_Exception('resource type must be a model');
    }

    // Parse camel case
    preg_match_all('/([A-Z][a-z]+)/', $resourceName, $matches);
    if( empty($matches[0]) )
    {
      throw new Engine_Exception('resource name not useable');
    }
    $matches = $matches[0];

    // Append module name if first not equal
    if( strtolower($matches[0]) != strtolower($module) )
    {
      array_unshift($matches, $module);
    }
    $type = strtolower(join('_', $matches));
    return $type;
  }

  /**
   * Inflects a type to the class name suffix
   * @todo Not used?
   * 
   * @param string $type
   * @param string $module
   * @return string
   */
  static public function typeToShort($type, $module)
  {
    $parts = explode('_', $type);
    if( count($parts) > 1 && strtolower($parts[0]) == strtolower($module) )
    {
      array_shift($parts);
    }
    return strtolower(join('_', $parts));
  }
}
Back to Top