├── .gitignore
├── library
└── Bgy
│ ├── Exception.php
│ ├── Filter
│ ├── Exception.php
│ ├── Scheme
│ │ └── Http.php
│ ├── HotWord.php
│ ├── Slugify.php
│ └── StringShortener.php
│ ├── Mail
│ ├── Exception.php
│ ├── Template
│ │ ├── Exception.php
│ │ ├── Html
│ │ │ ├── Renderer.php
│ │ │ └── Renderer
│ │ │ │ └── SimpleText.php
│ │ └── View
│ │ │ └── Helper
│ │ │ └── SetSubject.php
│ └── Template.php
│ ├── Controller
│ ├── Exception.php
│ └── Plugin
│ │ └── AjaxContextDefaultFormat.php
│ ├── Application
│ ├── Exception.php
│ └── Resource
│ │ ├── Exception.php
│ │ ├── Emailtemplate.php
│ │ └── Doctrine2.php
│ ├── View
│ └── Helper
│ │ ├── Exception.php
│ │ ├── FlashMessenger.php
│ │ └── RelativeDateTime.php
│ ├── Service
│ ├── Geonames
│ │ └── Exception.php
│ ├── ShortUrl
│ │ └── GooGl.php
│ └── Geonames.php
│ ├── Uuid.php
│ ├── DBAL
│ └── Logging
│ │ └── Firebug.php
│ ├── Doctrine
│ └── EntitySerializer.php
│ └── Auth
│ └── Adapter
│ └── Doctrine2.php
└── tests
├── Bgy
├── AllTests.php
└── Filter
│ ├── AllTests.php
│ ├── Scheme
│ └── HttpTest.php
│ ├── HotWordTest.php
│ └── SlugifyTest.php
└── TestHelper.php
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
--------------------------------------------------------------------------------
/library/Bgy/Exception.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | class Bgy_Exception extends Zend_Exception {}
20 |
--------------------------------------------------------------------------------
/tests/Bgy/AllTests.php:
--------------------------------------------------------------------------------
1 | addTestSuite('Bgy_Filter_AllTests');
28 |
29 | return $suite;
30 | }
31 | }
--------------------------------------------------------------------------------
/library/Bgy/Filter/Exception.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 |
20 | class Bgy_Filter_Exception extends Bgy_Exception {}
21 |
22 |
--------------------------------------------------------------------------------
/library/Bgy/Mail/Exception.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | namespace Bgy\Mail;
20 |
21 | class Exception extends \Bgy_Exception {}
22 |
--------------------------------------------------------------------------------
/library/Bgy/Controller/Exception.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | class Bgy_Controller_Exception extends Bgy_Exception
20 | {
21 | }
22 |
--------------------------------------------------------------------------------
/library/Bgy/Application/Exception.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | class Bgy_Application_Exception extends Bgy_Exception
20 | {
21 |
22 | }
--------------------------------------------------------------------------------
/library/Bgy/View/Helper/Exception.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 | class Bgy_View_Helper_Exception extends Bgy_Exception {}
21 |
--------------------------------------------------------------------------------
/library/Bgy/Application/Resource/Exception.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 | class Bgy_Application_Resource_Exception extends Bgy_Application_Exception {}
--------------------------------------------------------------------------------
/library/Bgy/Mail/Template/Exception.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 | namespace Bgy\Mail\Template;
21 |
22 | class Exception extends \Bgy\Mail\Exception {}
23 |
--------------------------------------------------------------------------------
/library/Bgy/Mail/Template/Html/Renderer.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | namespace Bgy\Mail\Template\Html;
22 | interface Renderer
23 | {
24 | public function render($html);
25 | }
26 |
--------------------------------------------------------------------------------
/library/Bgy/Service/Geonames/Exception.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 |
22 | /**
23 | * @see Zend_Service_Exception
24 | */
25 | require_once 'Zend/Service/Exception.php';
26 |
27 | class Bgy_Service_Geonames_Exception extends Zend_Service_Exception {}
28 |
--------------------------------------------------------------------------------
/tests/Bgy/Filter/AllTests.php:
--------------------------------------------------------------------------------
1 | addTestSuite('Bgy_Filter_HotWordTest');
29 | $suite->addTestSuite('Bgy_Filter_SlugifyTest');
30 | $suite->addTestSuite('Bgy_Filter_Scheme_HttpTest');
31 |
32 | return $suite;
33 | }
34 | }
--------------------------------------------------------------------------------
/library/Bgy/Mail/Template/Html/Renderer/SimpleText.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | namespace Bgy\Mail\Template\Html\Renderer;
22 | use Bgy\Mail\Template\Html\Renderer;
23 |
24 | class SimpleText implements Renderer {
25 | public function render($html)
26 | {
27 | return strip_tags($html);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/tests/Bgy/Filter/Scheme/HttpTest.php:
--------------------------------------------------------------------------------
1 | _filter = new Bgy_Filter_Scheme_Http();
19 | }
20 |
21 | public function testFilter()
22 | {
23 | $urls = array(
24 | 'borisguery.com',
25 | 'http://borisguery.com',
26 | 'ftp://borisguery.com',
27 | 'htp://borisguery.com',
28 | 'http:/borisguery.com',
29 | 'http\:borisguery.com',
30 | );
31 | $exceptedResult = 'http://borisguery.com';
32 |
33 | $filter = new Bgy_Filter_Scheme_Http();
34 | foreach ($urls as $url) {
35 | $this->assertEquals($exceptedResult, $filter->filter($url));
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/library/Bgy/View/Helper/FlashMessenger.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | require_once 'Zend/View/Helper/Abstract.php';
22 |
23 | class Bgy_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
24 | {
25 | protected $_flashMessenger;
26 |
27 | public function flashMessenger()
28 | {
29 | if (null === $this->_flashMessenger) {
30 | $this->_flashMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
31 | }
32 |
33 | return $this->_flashMessenger;
34 | }
35 | }
36 |
37 |
--------------------------------------------------------------------------------
/library/Bgy/Mail/Template/View/Helper/SetSubject.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | namespace Bgy\Mail\Template\View\Helper;
22 | use Bgy\Mail\Template;
23 |
24 | class SetSubject extends \Zend_View_Helper_Abstract
25 | {
26 | const APPEND = 'APPEND';
27 | const PREPEND = 'PREPEND';
28 | const REPLACE = 'REPLACE';
29 |
30 | public function setSubject($subject = '', $placement = self::APPEND)
31 | {
32 | $this->view->assign(Template::VAR_SUBJECT, $subject);
33 | $this->view->assign(Template::VAR_SUBJECT_PLACEMENT, strtoupper($placement));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/library/Bgy/Filter/Scheme/Http.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | require_once 'Zend/Filter/Interface.php';
20 |
21 | class Bgy_Filter_Scheme_Http implements Zend_Filter_Interface
22 | {
23 | public function filter($value)
24 | {
25 | $uri = explode(':', $value, 2);
26 | $valueFiltered = 'http://';
27 |
28 | if (!isset($uri[1])) {
29 | $valueFiltered .= $uri[0];
30 | } else {
31 | while (0 === ($pos = strpos($uri[1], '/'))) {
32 | $uri[1] = substr($uri[1], 1);
33 | }
34 | $valueFiltered .= $uri[1];
35 | }
36 |
37 | return $valueFiltered;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/library/Bgy/Application/Resource/Emailtemplate.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | *
20 | */
21 | use Bgy\Mail\Template;
22 |
23 | class Bgy_Application_Resource_Emailtemplate
24 | extends \Zend_Application_Resource_ResourceAbstract
25 | {
26 | public function init()
27 | {
28 | $options = $this->getOptions();
29 | if (isset($options)) {
30 | foreach ($options as $option => $value) {
31 | if ('default' === substr($option, 0, 7)) {
32 | $method = 'set' . ucfirst($option);
33 | Template::$method($value);
34 | }
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/library/Bgy/Uuid.php:
--------------------------------------------------------------------------------
1 |
19 | * @license http://sam.zoy.org/wtfpl/COPYING
20 | * @link http://borisguery.github.com/bgylibrary
21 | */
22 |
23 | class Uuid
24 | {
25 | protected $_uuid = null;
26 |
27 | /**
28 | * This implementation of UUID generation is based on code from a note
29 | * made on the PHP documentation.
30 | *
31 | * @return string
32 | * @link http://de3.php.net/manual/en/function.uniqid.php#69164
33 | */
34 | protected function _generate()
35 | {
36 | $this->_uuid = sprintf(
37 | '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
38 | mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
39 | mt_rand(0, 0x0fff) | 0x4000,
40 | mt_rand(0, 0x3fff) | 0x8000,
41 | mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
42 | );
43 | }
44 |
45 | public function __toString()
46 | {
47 | $this->_generate();
48 |
49 | return $this->_uuid;
50 | }
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/library/Bgy/Filter/HotWord.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | require_once 'Zend/Filter/Interface.php';
20 |
21 | class Bgy_Filter_HotWord implements Zend_Filter_Interface
22 | {
23 | protected $_wrapper = '%string%';
24 |
25 | protected $_keywords = array();
26 |
27 | public function filter($value)
28 | {
29 | usort($this->_keywords, function($a,$b){return(strlen($a)_wrapper);
31 | $wrapper = array_map(function($a) { return addcslashes($a, '<>/="\'-()[]^*.$: ');}, $wrapper);
32 |
33 | foreach ($this->_keywords as $keyword) {
34 | $value = preg_replace(
35 | '/((?_wrapper) . '\3',
37 | $value
38 | );
39 | }
40 |
41 | return $value;
42 | }
43 |
44 | public function setKeywords(array $keywords = array())
45 | {
46 | $this->_keywords = $keywords;
47 |
48 | return $this;
49 | }
50 |
51 | public function setWrapper($string = '')
52 | {
53 | $this->_wrapper = $string;
54 |
55 | return $this;
56 | }
57 |
58 | public function getKeywords()
59 | {
60 | return $this->_keywords;
61 | }
62 |
63 | public function getWrapper()
64 | {
65 | return $this->_wrapper;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/library/Bgy/Controller/Plugin/AjaxContextDefaultFormat.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 | class Bgy_Controller_Plugin_AjaxContextDefaultFormat
21 | extends Zend_Controller_Plugin_Abstract
22 | {
23 | protected $_defaultFormat = null;
24 |
25 | /**
26 | * Set a default format for context switcher
27 | *
28 | * It is used when no format paramater are provided
29 | * If no format are specified in paramater, json will
30 | * be used.
31 | * @param string $context either json, xml or html
32 | */
33 | public function __construct($format = 'json')
34 | {
35 | $this->setDefaultFormat($format);
36 | }
37 |
38 | public function setDefaultFormat($format)
39 | {
40 | $ajaxContext = new Zend_Controller_Action_Helper_AjaxContext();
41 | if (!array_key_exists($format, $ajaxContext->getContexts())) {
42 | throw new Bgy_Controller_Exception('The format "'.$format.'" is not a valid format.');
43 | }
44 | $this->_defaultFormat = $format;
45 |
46 | return $this;
47 | }
48 |
49 | public function getDefaultFormat()
50 | {
51 | return $this->_defaultFormat;
52 | }
53 |
54 | public function preDispatch(Zend_Controller_Request_Abstract $request)
55 | {
56 | if ($request->isXmlHttpRequest() && null === $request->getParam('format', null)) {
57 | $request->setParam('format', $this->getDefaultFormat());
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/tests/TestHelper.php:
--------------------------------------------------------------------------------
1 | =')) {
15 | if (version_compare($phpunitVersion, '3.6.0', '>=')) {
16 | echo 'This version of PHPUnit is not supported in Zend Framework 1.x unit tests.';
17 | exit(1);
18 | }
19 | require_once 'PHPUnit/Autoload.php'; // >= PHPUnit 3.5.5
20 | } else {
21 | require_once 'PHPUnit/Framework.php'; // < PHPUnit 3.5.5
22 | }
23 |
24 | /*
25 | * Set error reporting to the level to which Zend Framework code must comply.
26 | */
27 | error_reporting(E_ALL | E_STRICT);
28 |
29 | /*
30 | * Determine the root, library, and tests directories of the framework
31 | * distribution.
32 | */
33 | $bgyRoot = realpath(dirname(dirname(__FILE__)));
34 | $zfCoreLibrary = '/usr/local/zend/share/ZendFramework/library/';
35 | $bgyCoreLibrary = "$bgyRoot/library";
36 | $bgyCoreTests = "$bgyRoot/tests";
37 |
38 | /*
39 | * Prepend the Zend Framework library/ and tests/ directories to the
40 | * include_path. This allows the tests to run out of the box and helps prevent
41 | * loading other copies of the framework code and tests that would supersede
42 | * this copy.
43 | */
44 | $path = array(
45 | $zfCoreLibrary,
46 | $bgyCoreLibrary,
47 | $bgyCoreTests,
48 | get_include_path()
49 | );
50 | set_include_path(implode(PATH_SEPARATOR, $path));
51 |
52 | /*
53 | * Load the user-defined test configuration file, if it exists; otherwise, load
54 | * the default configuration.
55 | */
56 |
57 | /**
58 | * Start output buffering, if enabled
59 | */
60 | if (defined('TESTS_ZEND_OB_ENABLED') && constant('TESTS_ZEND_OB_ENABLED')) {
61 | ob_start();
62 | }
63 |
64 | /*
65 | * Unset global variables that are no longer needed.
66 | */
67 | unset($bgyRoot, $zfCoreLibrary, $bgyCoreLibrary, $bgyCoreTests, $path);
68 |
69 |
--------------------------------------------------------------------------------
/tests/Bgy/Filter/HotWordTest.php:
--------------------------------------------------------------------------------
1 | _keywords = array(
19 | 'consectetur',
20 | 'rhoncus commodo',
21 | 'sollicitudin',
22 | 'dapibus',
23 | 'rhoncus',
24 | );
25 |
26 | $this->_filter = new Bgy_Filter_HotWord();
27 | }
28 |
29 | public function testSetKeywords()
30 | {
31 | $this->_filter->setKeywords($this->_keywords);
32 | $this->assertEquals($this->_keywords, $this->_filter->getKeywords());
33 | }
34 |
35 | public function testGetDefaultWrapper()
36 | {
37 | $this->assertEquals('%string%', $this->_filter->getWrapper());
38 | }
39 |
40 | public function testFilter()
41 | {
42 | $text = 'Lorem ipsum dolor sit amet, consectetur rhoncus adipiscing elit. '
43 | . 'Vestibulum dapibus tortor rhoncus rhoncus commodo fermentum erat gravida '
44 | . 'sollicitudin. Ut magna diam, tincidunt ac dapibus id, placerat at arcu. '
45 | . 'Mauris a sapien sit amet risus auctor venenatis et consequat urna. '
46 | . 'Pellentesque orci erat, gravida vitae rhoncus commodo, laoreet in ipsum.';
47 |
48 | $exceptedResult = 'Lorem ipsum dolor sit amet, consectetur'
49 | .' rhoncus adipiscing elit. Vestibulum dapibus'
50 | .' tortor rhoncus rhoncus commodo fermentum erat'
51 | .' gravida sollicitudin. Ut magna diam, tincidunt ac'
52 | .' dapibus id, placerat at arcu. Mauris a sapien sit amet'
53 | .' risus auctor venenatis et consequat urna. Pellentesque orci erat, gravida'
54 | .' vitae rhoncus commodo, laoreet in ipsum.';
55 |
56 | $this->testSetKeywords();
57 | $result = $this->_filter->filter($text);
58 | $this->assertEquals($exceptedResult, $result);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/library/Bgy/Service/ShortUrl/GooGl.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | /**
22 | * @see Zend_Service_ShortUrl_AbstractShortener
23 | */
24 | require_once 'Zend/Service/ShortUrl/AbstractShortener.php';
25 |
26 | /**
27 | * @see Zend_Json
28 | */
29 | require_once 'Zend/Json.php';
30 |
31 | class Bgy_Service_ShortUrl_GooGl extends Zend_Service_ShortUrl_AbstractShortener
32 | {
33 | /**
34 | * Base URI of the service
35 | *
36 | * @var string
37 | */
38 | protected $_baseUri = 'http://goo.gl';
39 |
40 | /**
41 | * Api endpoint
42 | *
43 | * @var string
44 | */
45 | protected $_endpoint = 'https://www.googleapis.com/urlshortener/v1/url';
46 |
47 | /**
48 | * This function shortens long url
49 | *
50 | * @param string $url URL to Shorten
51 | * @return string Shortened url
52 | */
53 | public function shorten($url)
54 | {
55 | $this->_validateUri($url);
56 |
57 | $rawData = Zend_Json::encode(array(
58 | 'longUrl' => $url
59 | ));
60 |
61 | $httpClient = $this->_getHttpClient();
62 |
63 | $httpClient->setUri($this->_endpoint)
64 | ->setHeaders('Content-Type', 'application/json')
65 | ->setRawData($rawData);
66 |
67 | $response = $httpClient->request(Zend_Http_Client::POST);
68 | $body = $response->getBody();
69 | $body = Zend_Json::decode($body, Zend_Json::TYPE_OBJECT);
70 |
71 | return $body->id;
72 | }
73 |
74 | /**
75 | * Unshorten shortened URL
76 | *
77 | * @param string $shortenedUrl Shortened URL
78 | * @throws Zend_Service_ShortUrl_Exception Invalid shortened URL
79 | * @return string The unshortened URL
80 | */
81 | public function unshorten($shortenedUrl)
82 | {
83 | $this->_validateUri($shortenedUrl);
84 | $this->_verifyBaseUri($shortenedUrl);
85 |
86 | $httpClient = $this->_getHttpClient();
87 | $httpClient->setUri($this->_endpoint)
88 | ->setParameterGet('shortUrl', $shortenedUrl);
89 |
90 | $response = $httpClient->request();
91 | if ($response->isError()) {
92 | require_once 'Zend/Service/ShortUrl/Exception.php';
93 | throw new Zend_Service_ShortUrl_Exception($response->getMessage());
94 | }
95 |
96 | $body = $response->getBody();
97 | $body = Zend_Json::decode($body, Zend_Json::TYPE_OBJECT);
98 |
99 | return $body->longUrl;
100 | }
101 |
102 | protected function _getHttpClient()
103 | {
104 | $options = array(
105 | 'curloptions' => array(CURLOPT_SSL_VERIFYPEER => FALSE)
106 | );
107 |
108 | return $this->getHttpClient()
109 | ->setConfig($options);
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/library/Bgy/DBAL/Logging/Firebug.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 | namespace Bgy\DBAL\Logging;
21 | use \Zend_Wildfire_Plugin_FirePhp as FirePhp,
22 | \Zend_Wildfire_Plugin_FirePhp_TableMessage as FirePhp_TableMessage;
23 |
24 | require_once 'Doctrine/DBAL/Logging/SQLLogger.php';
25 |
26 | class Firebug implements \Doctrine\DBAL\Logging\SQLLogger
27 | {
28 | /**
29 | * The original label for this profiler.
30 | * @var string
31 | */
32 | protected $_label = null;
33 |
34 | /**
35 | * The label template for this profiler
36 | * @var string
37 | */
38 | protected $_label_template = '%label% (%totalCount% @ %totalDuration% sec)';
39 |
40 | /**
41 | * The message envelope holding the profiling summary
42 | * @var Zend_Wildfire_Plugin_FirePhp_TableMessage
43 | */
44 | protected $_message = null;
45 |
46 | /**
47 | * The total time taken for all profiled queries.
48 | * @var float
49 | */
50 | protected $_totalElapsedTime = 0;
51 |
52 | /**
53 | * Current query
54 | * @var array
55 | */
56 | protected $_currentQuery = array();
57 |
58 | /**
59 | * Query count
60 | * @var integer
61 | */
62 | protected $_queryCount = 0;
63 |
64 | /**
65 | * Constructor
66 | *
67 | * @return void
68 | */
69 | public function __construct()
70 | {
71 | $this->_label = 'Doctrine 2 Queries';
72 | $this->_message = new FirePhp_TableMessage(
73 | 'Doctrine2 Queries'
74 | );
75 | $this->_message->setBuffered(true);
76 | $this->_message->setHeader(array('Time', 'Event', 'Parameters'));
77 | $this->_message->setOption('includeLineNumbers', false);
78 | FirePhp::getInstance()->send($this->_message);
79 | }
80 |
81 | public function startQuery($sql, array $params = null, array $types = null)
82 | {
83 | $this->_currentQuery['sql'] = $sql;
84 | $this->_currentQuery['parameters'] = $params;
85 | $this->_currentQuery['types'] = $types;
86 | $this->_currentQuery['startTime'] = microtime(true);
87 | }
88 |
89 | public function stopQuery() {
90 | $elapsedTime = microtime(true) - $this->_currentQuery['startTime'];
91 | $this->_totalElapsedTime += $elapsedTime;
92 | ++$this->_queryCount;
93 | $this->_message->addRow(
94 | array(
95 | round($elapsedTime, 5),
96 | $this->_currentQuery['sql'],
97 | $this->_currentQuery['parameters'],
98 | )
99 | );
100 | $this->_updateMessageLabel();
101 | }
102 |
103 | /**
104 | * Update the label of the message holding the profile info.
105 | *
106 | * @return void
107 | */
108 | protected function _updateMessageLabel()
109 | {
110 | if (!$this->_message) {
111 | return;
112 | }
113 | $search = array('%label%', '%totalCount%', '%totalDuration%');
114 | $replacements = array(
115 | $this->_label,
116 | $this->_queryCount,
117 | (string)round($this->_totalElapsedTime,5)
118 | );
119 | $label = str_replace($search, $replacements, $this->_label_template);
120 | $this->_message->setLabel($label);
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/tests/Bgy/Filter/SlugifyTest.php:
--------------------------------------------------------------------------------
1 | _filter = new Bgy_Filter_Slugify();
11 | }
12 |
13 | public function testGetDefaultSeparator()
14 | {
15 | $this->assertEquals('-', $this->_filter->getSeparator());
16 | }
17 |
18 | public function testSetSeparator()
19 | {
20 | $this->_filter->setSeparator('&');
21 | $this->assertEquals('&', $this->_filter->getSeparator());
22 | }
23 |
24 | public function testGetDefaultLowercase()
25 | {
26 | $this->assertEquals(true, $this->_filter->getLowercase());
27 | }
28 |
29 | public function testSetLowercase()
30 | {
31 | $this->_filter->setLowercase(false);
32 | $this->assertEquals(false, $this->_filter->getLowercase());
33 | }
34 |
35 | public function testGetDefaultMaxlength()
36 | {
37 | $this->assertEquals(null, $this->_filter->getMaxlength());
38 | }
39 |
40 | public function testSetMaxlength()
41 | {
42 | $this->_filter->setMaxlength(30);
43 | $this->assertEquals(30, $this->_filter->getMaxlength());
44 | }
45 |
46 | public function testPassingOptionsAsArgumentsToConstructor()
47 | {
48 | $filter = new Bgy_Filter_Slugify('|', false, 25);
49 | $this->assertEquals('|', $filter->getSeparator());
50 | $this->assertEquals(false, $filter->getLowercase());
51 | $this->assertEquals(25, $filter->getMaxlength());
52 | }
53 |
54 | public function testPassingOptionsAsArrayToConstructor()
55 | {
56 | $options = array(
57 | 'separator' => '\\',
58 | 'lowercase' => false,
59 | 'maxlength' => 985978456464,
60 | );
61 | $filter = new Bgy_Filter_Slugify($options);
62 | $this->assertEquals('\\', $filter->getSeparator());
63 | $this->assertEquals(false, $filter->getLowercase());
64 | $this->assertEquals(985978456464, $filter->getMaxlength());
65 | }
66 |
67 | public function testFilterValueBasic()
68 | {
69 | $value = 'Lorem ipsum dolor sid amet x 10 .';
70 | $this->assertEquals('lorem-ipsum-dolor-sid-amet-x-10', $this->_filter->filter($value));
71 | }
72 |
73 | public function testFilterValueWithSpecialChars()
74 | {
75 | $value = 'lo\rem ipsum do|or sid amet||| #\`[|\" 10 .';
76 | $this->assertEquals('lo-rem-ipsum-do-or-sid-amet-10', $this->_filter->filter($value));
77 | }
78 |
79 | public function testFilterValueWithUnicode()
80 | {
81 | $this->markTestIncomplete('Testing with unicode is not well tested');
82 | $value = 'lørém ipßum dœlör sîd æmèt '; // space
83 | $this->assertEquals('lorem-ipssum-doelor-sid-aemet', $this->_filter->filter($value));
84 | }
85 |
86 | public function testFilterValueWithCustomSeparator()
87 | {
88 | $value = 'lørém ipßum##dœlör sîd æmèt '; // space
89 | $options = array(
90 | 'separator' => '#',
91 | );
92 | $filter = new Bgy_Filter_Slugify($options);
93 | $this->assertEquals('lorem#ipssum#doelor#sid#aemet', $filter->filter($value));
94 | }
95 |
96 | public function testFilterValueWithMaxLength()
97 | {
98 | $value = 'lørém ipßum dœlör sîd æmèt '; // space
99 | $options = array(
100 | 'maxlength' => 13,
101 | );
102 | $filter = new Bgy_Filter_Slugify($options);
103 | $result = $filter->filter($value);
104 | $this->assertLessThanOrEqual(13, strlen($result));
105 | }
106 |
107 | public function testFilterValueWithLowercaseSetToFalse()
108 | {
109 | $value = 'LØrém iPßum dœlör Sîd æmèt '; // space
110 | $options = array(
111 | 'lowercase' => false,
112 | );
113 | $filter = new Bgy_Filter_Slugify($options);
114 | $result = $filter->filter($value);
115 | $this->assertEquals('LOrem-iPssum-doelor-Sid-aemet', $result);
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/library/Bgy/Filter/Slugify.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | require_once 'Zend/Filter/Interface.php';
20 |
21 | class Bgy_Filter_Slugify implements Zend_Filter_Interface
22 | {
23 |
24 | protected $_separator = '-';
25 |
26 | protected $_lowercase = true;
27 |
28 | protected $_maxlength = null;
29 |
30 | /**
31 | * @return string The separator
32 | */
33 | public function getSeparator()
34 | {
35 | return $this->_separator;
36 | }
37 |
38 | /**
39 | * @param string $separator
40 | */
41 | public function setSeparator($separator)
42 | {
43 | $this->_separator = $separator;
44 |
45 | return $this;
46 | }
47 |
48 | /**
49 | * @return bool True if the string must be converted to lowercase
50 | */
51 | public function getLowercase()
52 | {
53 | return $this->_lowercase;
54 | }
55 |
56 | /**
57 | * @param field_type $_lowercase
58 | */
59 | public function setLowercase($lowercase)
60 | {
61 | $this->_lowercase = (bool) $lowercase;
62 |
63 | return true;
64 | }
65 |
66 | /**
67 | * @return int The max length of the slug
68 | */
69 | public function getMaxlength()
70 | {
71 | return $this->_maxlength;
72 | }
73 |
74 | /**
75 | * @param int $maxlength
76 | */
77 | public function setMaxlength($maxlength)
78 | {
79 | if (is_null($maxlength)) {
80 | $this->_maxlength = null;
81 | } else {
82 | $this->_maxlength = (int) $maxlength;
83 | }
84 |
85 | return $this;
86 | }
87 |
88 | public function __construct($options = null)
89 | {
90 | if ($options instanceof Zend_Config) {
91 | $options = $options->toArray();
92 | } else if (!is_array($options)) {
93 | $options = func_get_args();
94 | $temp = array();
95 | if (!empty($options)) {
96 | $temp['separator'] = array_shift($options);
97 | }
98 |
99 | if (!empty($options)) {
100 | $temp['lowercase'] = array_shift($options);
101 | }
102 |
103 | if (!empty($options)) {
104 | $temp['maxlength'] = array_shift($options);
105 | }
106 |
107 | $options = $temp;
108 | }
109 |
110 | if (array_key_exists('separator', $options)) {
111 | $this->setSeparator($options['separator']);
112 | }
113 |
114 | if (array_key_exists('lowercase', $options)) {
115 | $this->setLowercase($options['lowercase']);
116 | }
117 |
118 | if (array_key_exists('maxlength', $options)) {
119 | $this->setMaxlength($options['maxlength']);
120 | }
121 | }
122 |
123 | public function filter($value)
124 | {
125 | $value = preg_replace('/[^\\pL\d]+/u', $this->getSeparator(), $value);
126 | $value = @iconv('UTF-8', 'US-ASCII//TRANSLIT', $value); // transliterate, silently
127 | $value = preg_replace('/[^'.$this->getSeparator().'\w]+/', '', $value);
128 |
129 | if (null !== $this->getMaxlength()) {
130 | $value = substr($value, 0, $this->getMaxlength());
131 | }
132 | $value = trim($value, $this->getSeparator());
133 |
134 | if ($this->getLowercase()) {
135 | $value = strtolower($value);
136 | }
137 |
138 | if (empty($value)) {
139 | $value = null; // should we return null or an empty string?
140 | }
141 |
142 | return $value;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/library/Bgy/View/Helper/RelativeDateTime.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | require_once 'Zend/View/Helper/Abstract.php';
22 |
23 | class Bgy_View_Helper_RelativeDateTime extends Zend_View_Helper_Abstract
24 | {
25 | const YEAR = 'YEAR';
26 | const MONTH = 'MONTH';
27 | const WEEK = 'WEEK';
28 | const DAY = 'DAY';
29 | const HOUR = 'HOUR';
30 | const MINUTE = 'MINUTE';
31 | const SECOND = 'SECOND';
32 | const YEARS = 'YEARS';
33 | const MONTHS = 'MONTHS';
34 | const WEEKS = 'WEEKS';
35 | const DAYS = 'DAYS';
36 | const HOURS = 'HOURS';
37 | const MINUTES = 'MINUTES';
38 | const SECONDS = 'SECONDS';
39 |
40 | protected $_unitTemplates = array(
41 | self::YEAR => '%value% year',
42 | self::MONTH => '%value% month',
43 | self::WEEK => '%value% week',
44 | self::DAY => '%value% day',
45 | self::HOUR => '%value% hour',
46 | self::MINUTE => '%value% minute',
47 | self::SECOND => '%value% second',
48 | self::YEARS => '%value% years',
49 | self::MONTHS => '%value% months',
50 | self::WEEKS => '%value% weeks',
51 | self::DAYS => '%value% days',
52 | self::HOURS => '%value% hours',
53 | self::MINUTES => '%value% minutes',
54 | self::SECONDS => '%value% seconds',
55 | );
56 |
57 | public function __construct($config = null)
58 | {
59 |
60 | }
61 |
62 | public function relativeDateTime(Zend_Date $date = null)
63 | {
64 | if (null === $date) {
65 | return $this;
66 | }
67 |
68 | $todayDate = new Zend_Date();
69 | $diff = $todayDate->sub($date);
70 |
71 | $mt = new Zend_Measure_Time($diff);
72 | $units = $mt->getConversionList();
73 |
74 | $chunks = array(
75 | Zend_Measure_Time::YEAR,
76 | Zend_Measure_Time::MONTH,
77 | Zend_Measure_Time::WEEK,
78 | Zend_Measure_Time::DAY,
79 | Zend_Measure_Time::HOUR,
80 | Zend_Measure_Time::MINUTE,
81 | Zend_Measure_Time::SECOND,
82 | );
83 |
84 | for ($i = 0, $count = count($chunks); $i < $count; ++$i) {
85 | $seconds = $units[$chunks[$i]][0];
86 | $unitKey = $chunks[$i];
87 | if (0.0 !== ($result = floor($diff->get(Zend_Date::TIMESTAMP) / $seconds))) {
88 | break;
89 | }
90 | }
91 |
92 | $translateHelper = new Zend_View_Helper_Translate();
93 | if ($result === (float)1) {
94 | $formatedString = $translateHelper->translate($this->getUnitTemplate($unitKey));
95 | } else {
96 | $formatedString = $translateHelper->translate($this->getUnitTemplate($unitKey.'S'));
97 | }
98 | $formatedString = str_replace('%value%', (string) $result, $formatedString);
99 |
100 | return $formatedString;
101 | }
102 |
103 | public function setUnitTemplate($unitKey, $template)
104 | {
105 | if (!isset($this->_unitTemplates[$unitKey])) {
106 | require_once 'Bgy/View/Helper/Exception.php';
107 | throw new Bgy_View_Helper_Exception("No unit template exists for key '$unitKey'");
108 | }
109 |
110 | $this->_unitTemplates[$unitKey] = $template;
111 |
112 | return $this;
113 | }
114 |
115 | public function setUnitTemplates(array $templates)
116 | {
117 | foreach ($templates as $key => $template) {
118 | $this->setUnitTemplate($key, $template);
119 | }
120 | return $this;
121 | }
122 |
123 | public function getUnitTemplates()
124 | {
125 | return $this->_unitTemplates;
126 | }
127 |
128 | public function getUnitTemplate($unitKey)
129 | {
130 | if (!isset($this->_unitTemplates[$unitKey])) {
131 | require_once 'Bgy/View/Helper/Exception.php';
132 | throw new Bgy_View_Helper_Exception("No unit template exists for key '$unitKey'");
133 | }
134 |
135 | return $this->_unitTemplates[$unitKey];
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/library/Bgy/Filter/StringShortener.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | */
19 | require_once 'Zend/Filter/Interface.php';
20 |
21 | class Bgy_Filter_StringShortener implements Zend_Filter_Interface
22 | {
23 | const AFFIX_POSITION_START = 'start';
24 | const AFFIX_POSITION_END = 'end';
25 | const AFFIX_POSITION_MIDDLE = 'middle';
26 |
27 | protected $_affixPosition = 'middle';
28 |
29 | protected $_affix = null;
30 |
31 | protected $_maxlength = 80;
32 |
33 | /**
34 | * Constructor
35 | * @param Zend_Config|Array $options
36 | * @param int $maxlength The maximum length of a string (Required)
37 | * @param string $affix The separator to add to the shortened string (optional)
38 | * @param string|integer $position Can be start, middle, end, or integer,
39 | * if integer, will positioned to the given
40 | * offset in the string. (optional, default to middle)
41 | */
42 | public function __construct($options = null)
43 | {
44 | if ($options instanceof Zend_Config) {
45 | $options = $options->toArray();
46 | } else if (!is_array($options)) {
47 | $options = func_get_args();
48 | $temp = array();
49 | if (!empty($options)) {
50 | $temp['maxlength'] = array_shift($options);
51 | }
52 |
53 | if (!empty($options)) {
54 | $temp['affix'] = array_shift($options);
55 | }
56 |
57 | if (!empty($options)) {
58 | $temp['affixPosition'] = array_shift($options);
59 | }
60 |
61 | $options = $temp;
62 | }
63 |
64 | if (array_key_exists('maxlength', $options)) {
65 | $this->setMaxlength($options['maxlength']);
66 | }
67 |
68 | if (array_key_exists('affix', $options)) {
69 | $this->setAffix($options['affix']);
70 | }
71 |
72 | if (array_key_exists('affixPosition', $options)) {
73 | $this->setAffixPosition($options['affixPosition']);
74 | }
75 |
76 | }
77 |
78 | public function setMaxlength($length)
79 | {
80 | $this->_maxlength = (int)$length;
81 |
82 | return $this;
83 | }
84 |
85 | public function setAffix($affix)
86 | {
87 | $this->_affix = $affix;
88 |
89 | return $this;
90 | }
91 |
92 | public function setAffixPosition($position)
93 | {
94 | if (!in_array(strtolower($position), array(
95 | self::AFFIX_POSITION_START,
96 | self::AFFIX_POSITION_MIDDLE,
97 | self::AFFIX_POSITION_END
98 | )) && !is_numeric($position)) {
99 | throw new Bgy_Filter_Exception('Incorrect position provided: ' . $position);
100 | }
101 |
102 | $this->_affixPosition = $position;
103 |
104 | return $this;
105 | }
106 |
107 | public function filter($value)
108 | {
109 | if (strlen($value) > $this->_maxlength) {
110 | $valueLength = strlen($value);
111 | if (null !== $this->_affix) {
112 | $position = 0;
113 | switch ($this->_affixPosition) {
114 | case self::AFFIX_POSITION_START:
115 | $position = 0;
116 | $value = $this->_affix . substr($value, 0, $this->_maxlength);
117 | break;
118 | case self::AFFIX_POSITION_END:
119 | $position = $this->_maxlength;
120 | $value = substr($value, -$position) . $this->_affix;
121 | break;
122 | case self::AFFIX_POSITION_MIDDLE:
123 | default:
124 | $position = floor($this->_maxlength / 2);
125 | $value = substr($value, 0, $position) . $this->_affix . substr($value, -$position);
126 | break;
127 | }
128 | }
129 | }
130 |
131 | return $value;
132 | }
133 | }
134 |
135 |
--------------------------------------------------------------------------------
/library/Bgy/Doctrine/EntitySerializer.php:
--------------------------------------------------------------------------------
1 |
16 | * @license http://sam.zoy.org/wtfpl/COPYING
17 | * @link http://borisguery.github.com/bgylibrary
18 | * @see https://gist.github.com/1034079#file_serializable_entity.php
19 | */
20 |
21 | namespace Bgy\Doctrine;
22 |
23 | use Doctrine\ORM\Mapping\ClassMetadata,
24 | Doctrine\Common\Util\Inflector,
25 | Doctrine\ORM\EntityManager,
26 | Exception;
27 |
28 | class EntitySerializer
29 | {
30 |
31 | /**
32 | * @var Doctrine\ORM\EntityManager
33 | */
34 | protected $_em;
35 |
36 | /**
37 | * @var int
38 | */
39 | protected $_recursionDepth = 0;
40 |
41 | /**
42 | * @var int
43 | */
44 | protected $_maxRecursionDepth = 0;
45 |
46 | public function __construct($em)
47 | {
48 | $this->setEntityManager($em);
49 | }
50 |
51 | /**
52 | *
53 | * @return Doctrine\ORM\EntityManager
54 | */
55 | public function getEntityManager()
56 | {
57 | return $this->_em;
58 | }
59 |
60 | public function setEntityManager(EntityManager $em)
61 | {
62 | $this->_em = $em;
63 |
64 | return $this;
65 | }
66 |
67 | protected function _serializeEntity($entity)
68 | {
69 | $className = get_class($entity);
70 | $metadata = $this->_em->getClassMetadata($className);
71 |
72 | $data = array();
73 |
74 | foreach ($metadata->fieldMappings as $field => $mapping) {
75 | $value = $metadata->reflFields[$field]->getValue($entity);
76 | $field = Inflector::tableize($field);
77 | if ($value instanceof \DateTime) {
78 | // We cast DateTime to array to keep consistency with array result
79 | $data[$field] = (array)$value;
80 | } elseif (is_object($value)) {
81 | $data[$field] = (string)$value;
82 | } else {
83 | $data[$field] = $value;
84 | }
85 | }
86 |
87 | foreach ($metadata->associationMappings as $field => $mapping) {
88 | $key = Inflector::tableize($field);
89 | if ($mapping['isCascadeDetach']) {
90 | $data[$key] = $metadata->reflFields[$field]->getValue($entity);
91 | if (null !== $data[$key]) {
92 | $data[$key] = $this->_serializeEntity($data[$key]);
93 | }
94 | } elseif ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadata::TO_ONE) {
95 | if (null !== $metadata->reflFields[$field]->getValue($entity)) {
96 | if ($this->_recursionDepth < $this->_maxRecursionDepth) {
97 | $this->_recursionDepth++;
98 | $data[$key] = $this->_serializeEntity(
99 | $metadata->reflFields[$field]
100 | ->getValue($entity)
101 | );
102 | $this->_recursionDepth--;
103 | } else {
104 | $data[$key] = $this->getEntityManager()
105 | ->getUnitOfWork()
106 | ->getEntityIdentifier(
107 | $metadata->reflFields[$field]
108 | ->getValue($entity)
109 | );
110 | }
111 | } else {
112 | // In some case the relationship may not exist, but we want
113 | // to know about it
114 | $data[$key] = null;
115 | }
116 | }
117 | }
118 |
119 | return $data;
120 | }
121 |
122 | /**
123 | * Serialize an entity to an array
124 | *
125 | * @param The entity $entity
126 | * @return array
127 | */
128 | public function toArray($entity)
129 | {
130 | return $this->_serializeEntity($entity);
131 | }
132 |
133 |
134 | /**
135 | * Convert an entity to a JSON object
136 | *
137 | * @param The entity $entity
138 | * @return string
139 | */
140 | public function toJson($entity)
141 | {
142 | return json_encode($this->toArray($entity));
143 | }
144 |
145 | /**
146 | * Convert an entity to XML representation
147 | *
148 | * @param The entity $entity
149 | * @throws Exception
150 | */
151 | public function toXml($entity)
152 | {
153 | throw new Exception('Not yet implemented');
154 | }
155 |
156 | /**
157 | * Set the maximum recursion depth
158 | *
159 | * @param int $maxRecursionDepth
160 | * @return void
161 | */
162 | public function setMaxRecursionDepth($maxRecursionDepth)
163 | {
164 | $this->_maxRecursionDepth = $maxRecursionDepth;
165 | }
166 |
167 | /**
168 | * Get the maximum recursion depth
169 | *
170 | * @return int
171 | */
172 | public function getMaxRecursionDepth()
173 | {
174 | return $this->_maxRecursionDepth;
175 | }
176 |
177 | }
178 |
--------------------------------------------------------------------------------
/library/Bgy/Auth/Adapter/Doctrine2.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | *
20 | */
21 | namespace Bgy\Auth\Adapter;
22 |
23 | use Doctrine\ORM\EntityManager;
24 |
25 | class Doctrine2 implements \Zend_Auth_Adapter_Interface
26 | {
27 | /**
28 | * The entity manager
29 | *
30 | * @var Doctrine\ORM\EntityManager
31 | */
32 | protected $_entityManager;
33 |
34 | /**
35 | * @var string
36 | */
37 | protected $_entityClassName;
38 |
39 | /**
40 | * @var string
41 | */
42 | protected $_identityField;
43 |
44 | /**
45 | * @var string
46 | */
47 | protected $_credentialField;
48 |
49 | /**
50 | * @var Closure
51 | */
52 | protected $_credentialTreatment;
53 |
54 | /**
55 | * @var string
56 | */
57 | protected $_identity;
58 |
59 | /**
60 | * @var string
61 | */
62 | protected $_credential;
63 |
64 | /**
65 | * @var array
66 | */
67 | protected $_authenticateResultInfo;
68 |
69 | /**
70 | * __construct() - Sets configuration options
71 | *
72 | * @param \Doctrine\ORM\EntityManager $entityManager The Entity Manager
73 | * @param string $enitityClassName The Entity Class name
74 | * @param string $identityField The identity property
75 | * @param string $credentialField The credential property
76 | * @param Closure $credentialTreatment Optional credential function streatment
77 | * @return void
78 | */
79 | public function __construct(EntityManager $entityManager = null, $entityClassName = null,
80 | $identityField = null, $credentialField = null,
81 | \Closure $credentialTreatment = null)
82 | {
83 | $this->setEntityManager($entityManager);
84 |
85 | if (null !== $entityClassName) {
86 | $this->setEntityClassName($entityClassName);
87 | }
88 |
89 | if (null !== $identityField) {
90 | $this->setIdentityField($identityField);
91 | }
92 |
93 | if (null !== $credentialField) {
94 | $this->setCredentialField($credentialField);
95 | }
96 |
97 | if (null !== $credentialTreatment) {
98 | $this->setCredentialTreatment($credentialTreatment);
99 | }
100 | }
101 |
102 | /**
103 | * authenticate() - defined by Zend_Auth_Adapter_Interface. This method is called to
104 | * attempt an authentication. Previous to this call, this adapter would have already
105 | * been configured with all necessary information to successfully connect to a database
106 | * table and attempt to find a record matching the provided identity.
107 | *
108 | * @return Zend_Auth_Result
109 | */
110 | public function authenticate()
111 | {
112 | $this->_authenticateSetup();
113 |
114 | $query = $this->_authenticateCreateQuery();
115 | $resultIdentities = $query->setParameter(1, $this->getIdentity())
116 | ->execute();
117 |
118 | $authResult = $this->_authenticateValidateResultSet($resultIdentities);
119 |
120 | return $authResult;
121 | }
122 |
123 | /**
124 | * @return Doctrine\ORM\EntityManager $_entityManager
125 | */
126 | public function getEntityManager()
127 | {
128 | return $this->_entityManager;
129 | }
130 |
131 | /**
132 | * @param Doctrine\ORM\EntityManager $entityManager
133 | */
134 | public function setEntityManager(EntityManager $entityManager)
135 | {
136 | $this->_entityManager = $entityManager;
137 |
138 | return $this;
139 | }
140 |
141 | /**
142 | * @return the $_entityClassName
143 | */
144 | public function getEntityClassName()
145 | {
146 | return $this->_entityClassName;
147 | }
148 |
149 | /**
150 | * @param field_type $_entityClassName
151 | */
152 | public function setEntityClassName($entityClassName)
153 | {
154 | if (null === $entityClassName) {
155 | throw new \InvalidArgumentException('EntityClassName cannot be null');
156 | }
157 | $this->_entityClassName = $entityClassName;
158 |
159 | return $this;
160 | }
161 |
162 | /**
163 | * @return the $_identityField
164 | */
165 | public function getIdentityField()
166 | {
167 | return $this->_identityField;
168 | }
169 |
170 | /**
171 | * @param field_type $_identityField
172 | */
173 | public function setIdentityField($identityField)
174 | {
175 | if (null === $identityField) {
176 | throw new \InvalidArgumentException('IdentityField cannot be null');
177 | }
178 | $this->_identityField = $identityField;
179 |
180 | return $this;
181 | }
182 |
183 | /**
184 | * @return the $_credentialField
185 | */
186 | public function getCredentialField()
187 | {
188 | return $this->_credentialField;
189 | }
190 |
191 | /**
192 | * @param field_type $_credentialField
193 | */
194 | public function setCredentialField($credentialField)
195 | {
196 | if (null === $credentialField) {
197 | throw new \InvalidArgumentException('CredentialField cannot be null');
198 | }
199 | $this->_credentialField = $credentialField;
200 |
201 | return $this;
202 | }
203 |
204 | /**
205 | * @return the $_credentialTreatment
206 | */
207 | public function getCredentialTreatment()
208 | {
209 | return $this->_credentialTreatment;
210 | }
211 |
212 | /**
213 | * @param Closure $_credentialTreatment
214 | */
215 | public function setCredentialTreatment(\Closure $credentialTreatment)
216 | {
217 | $this->_credentialTreatment = $credentialTreatment;
218 |
219 | return $this;
220 | }
221 |
222 | /**
223 | * @return the $identity
224 | */
225 | public function getIdentity()
226 | {
227 | return $this->_identity;
228 | }
229 |
230 | /**
231 | * @param field_type $identity
232 | */
233 | public function setIdentity($identity)
234 | {
235 | $this->_identity = $identity;
236 |
237 | return $this;
238 | }
239 |
240 | /**
241 | * @return the $_credential
242 | */
243 | public function getCredential()
244 | {
245 | return $this->_credential;
246 | }
247 |
248 | /**
249 | * @param field_type $credential
250 | */
251 | public function setCredential($credential)
252 | {
253 | $this->_credential = $credential;
254 |
255 | return $this;
256 | }
257 |
258 | /**
259 | * _authenticateSetup() - This method abstracts the steps involved with
260 | * making sure that this adapter was indeed setup properly with all
261 | * required pieces of information.
262 | *
263 | * @throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly
264 | * @return true
265 | */
266 | protected function _authenticateSetup()
267 | {
268 | $exception = null;
269 |
270 | if ($this->getEntityClassName() == '') {
271 | $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
272 | } elseif ($this->getIdentityField() == '') {
273 | $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
274 | } elseif ($this->getCredentialField() == '') {
275 | $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
276 | } elseif ($this->getIdentity() == '') {
277 | $exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
278 | } elseif ($this->getCredential() === null) {
279 | $exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
280 | }
281 |
282 | if (null !== $exception) {
283 | /**
284 | * @see Zend_Auth_Adapter_Exception
285 | */
286 | require_once 'Zend/Auth/Adapter/Exception.php';
287 | throw new \Zend_Auth_Adapter_Exception($exception);
288 | }
289 |
290 | $this->_authenticateResultInfo = array(
291 | 'code' => \Zend_Auth_Result::FAILURE,
292 | 'identity' => $this->_identity,
293 | 'messages' => array()
294 | );
295 |
296 | return true;
297 | }
298 |
299 | /**
300 | * Create the doctrine query
301 | *
302 | * @return \Doctrine\ORM\QueryBuilder
303 | */
304 | protected function _authenticateCreateQuery()
305 | {
306 | $qb = $this->getEntityManager()->createQuery(
307 | 'SELECT entity.' . $this->getCredentialField() . ', entity ' .
308 | ' FROM '. $this->getEntityClassName() .' entity ' .
309 | ' WHERE entity.' . $this->getIdentityField() . ' = ?1 '
310 | );
311 |
312 | return $qb;
313 | }
314 |
315 | /**
316 | * _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from
317 | * the information that has been collected during the authenticate() attempt.
318 | *
319 | * @return Zend_Auth_Result
320 | */
321 | protected function _authenticateCreateAuthResult()
322 | {
323 | return new \Zend_Auth_Result(
324 | $this->_authenticateResultInfo['code'],
325 | $this->_authenticateResultInfo['identity'],
326 | $this->_authenticateResultInfo['messages']
327 | );
328 | }
329 |
330 | /**
331 | * _authenticateValidateResultSet() - This method attempts to make
332 | * certain that only one record was returned in the resultset
333 | *
334 | * @param array $resultIdentities
335 | * @return true|Zend_Auth_Result
336 | */
337 | protected function _authenticateValidateResultSet(array $resultIdentities)
338 | {
339 | if (count($resultIdentities) < 1) {
340 | $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
341 | $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
342 | } elseif (count($resultIdentities) > 1) {
343 | $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
344 | $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
345 | } else {
346 | $credential = $this->getCredential();
347 | if ($this->getCredentialTreatment() instanceof \Closure) {
348 | $closure = $this->getCredentialTreatment();
349 | $credential = $closure($credential);
350 | }
351 |
352 | if ($resultIdentities[0][$this->getCredentialField()] !== $credential) {
353 | $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
354 | $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
355 | } else {
356 | $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::SUCCESS;
357 | $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
358 | }
359 | }
360 |
361 | return $this->_authenticateCreateAuthResult();
362 | }
363 | }
364 |
365 |
--------------------------------------------------------------------------------
/library/Bgy/Application/Resource/Doctrine2.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | * @link http://www.doctrine-project.org/docs/orm/2.0/en/reference/configuration.html
20 | */
21 | use Doctrine\ORM\Mapping\Driver\AnnotationDriver,
22 | Doctrine\ORM\Configuration,
23 | Doctrine\ORM\Mapping\Driver\YamlDriver,
24 | Doctrine\ORM\Mapping\Driver\XmlDriver,
25 | Doctrine\ORM\Mapping\Driver\PHPDriver,
26 | Doctrine\DBAL\Connection,
27 | Doctrine\DBAL\Types\Type,
28 | Doctrine\ORM\EntityManager;
29 |
30 | require_once ('Zend/Application/Resource/ResourceAbstract.php');
31 |
32 | class Bgy_Application_Resource_Doctrine2
33 | extends Zend_Application_Resource_ResourceAbstract
34 | {
35 | /**
36 | *
37 | * @var \Doctrine\ORM\Configuration
38 | */
39 | protected $_configuration;
40 |
41 | /**
42 | *
43 | * @var \Doctrine\ORM\EntityManager
44 | */
45 | protected $_entityManager;
46 |
47 | /**
48 | * @var \Doctrine\Common\EventManager
49 | */
50 | protected $_eventManager;
51 |
52 |
53 | /**
54 | *
55 | * @return mixed
56 |
57 | * @see Zend_Application_Resource_Resource::init()
58 | */
59 | public function init()
60 | {
61 | $this->_setupProxy();
62 | $this->_setupMetadata();
63 | $this->_setupCache();
64 | $this->_setupCustomTypes();
65 | $this->_setupCustomHydrators();
66 | $this->_setupEventManager();
67 | $this->_setupOptions();
68 |
69 | return $this;
70 | }
71 |
72 | public function getConfiguration()
73 | {
74 | if (null === $this->_configuration) {
75 | $this->_configuration = new Configuration();
76 | }
77 |
78 | return $this->_configuration;
79 |
80 | }
81 |
82 | public function getEntityManager()
83 | {
84 | if (null === $this->_entityManager) {
85 | $options = $this->getOptions();
86 | $this->_entityManager = EntityManager::create(
87 | $options['params'],
88 | $this->getConfiguration(),
89 | $this->getEventManager()
90 | );
91 | }
92 |
93 | return $this->_entityManager;
94 | }
95 |
96 | public function getEventManager()
97 | {
98 | return $this->_eventManager;
99 | }
100 |
101 | public function setEventManager(\Doctrine\Common\EventManager $eventManager)
102 | {
103 | $this->_eventManager = $eventManager;
104 |
105 | return $this;
106 | }
107 |
108 | public function getConnectionInformations()
109 | {
110 | $options = $this->getOptions();
111 |
112 | return $options['params'];
113 | }
114 |
115 | protected function _setupEventManager()
116 | {
117 | $options = $this->getOptions();
118 |
119 | if (!empty($options['events'])) {
120 | if (isset($options['events']['eventManager'])) {
121 | $eventManager = new $options['events']['eventManager'];
122 | } else {
123 | $eventManager = new \Doctrine\Common\EventManager();
124 | }
125 |
126 | if (!empty($options['events']['subscribers'])) {
127 | $subscribers = $options['events']['subscribers'];
128 |
129 | foreach ($subscribers as $subscriberOptions) {
130 | if (is_array($subscriberOptions)) {
131 | $subscriberClass = $subscriberOptions['className'];
132 | unset($subscriberOptions['className']);
133 | // We use Reflection to create a new instance of the Subscriber
134 | // and provides according arguments
135 | $subscriberReflection = new ReflectionClass($subscriberClass);
136 | $subscriber = $subscriberReflection
137 | ->newInstanceArgs($subscriberOptions);
138 | } else {
139 | $subscriber = new $subscriberOptions;
140 | }
141 |
142 | $eventManager->addEventSubscriber($subscriber);
143 | }
144 | }
145 |
146 | $this->setEventManager($eventManager);
147 | }
148 | }
149 |
150 | protected function _setupMetadata()
151 | {
152 | $options = $this->getOptions();
153 |
154 | if (!empty($options['metadata']['driver'])) {
155 | $driver = $options['metadata']['driver'];
156 |
157 | if (!empty($options['metadata']['paths'])) {
158 | $paths = (array)$options['metadata']['paths'];
159 | }
160 |
161 | switch (strtolower($driver)) {
162 | case 'yaml':
163 | $driver = new YamlDriver($paths);
164 | break;
165 | case 'php':
166 | $driver = new PHPDriver($paths);
167 | break;
168 | case 'xml':
169 | $driver = new XmlDriver($paths);
170 | break;
171 | case 'annotation':
172 | $driver = $this->getConfiguration()
173 | ->newDefaultAnnotationDriver($paths);
174 | break;
175 | default:
176 | $isCustomDriver = true;
177 | break;
178 | }
179 |
180 | if (isset($isCustomDriver) && true === $isCustomDriver) {
181 | if (!class_exists($driver)) {
182 | throw new Bgy_Application_Resource_Exception(
183 | 'Class "'.$driver.'" does not exist'
184 | );
185 | }
186 |
187 | $driver = new $driver($paths);
188 | }
189 |
190 |
191 | $this->getConfiguration()->setMetadataDriverImpl($driver);
192 | }
193 | }
194 |
195 | protected function _setupEntities()
196 | {
197 | $options = $this->getOptions();
198 |
199 | foreach ($options['entities']['namespaces'] as $alias => $namespace) {
200 | $this->getConfiguration()->addEntityNamespace($alias, $namespace);
201 | }
202 | }
203 |
204 | protected function _setupCustomFunctions()
205 | {
206 | $options = $this->getOptions();
207 |
208 | if (!empty($options['functions'])) {
209 | if (!empty($options['functions']['string'])) {
210 | foreach ($options['functions']['string'] as $name => $className) {
211 | $this->getConfiguration()->addCustomStringFunction($name, $className);
212 | }
213 | }
214 | if (!empty($options['functions']['numeric'])) {
215 | foreach ($options['functions']['numeric'] as $name => $className) {
216 | $this->getConfiguration()->addCustomStringFunction($name, $className);
217 | }
218 | }
219 | if (!empty($options['functions']['datetime'])) {
220 | foreach ($options['functions']['datetime'] as $name => $className) {
221 | $this->getConfiguration()->addCustomStringFunction($name, $className);
222 | }
223 | }
224 | }
225 |
226 | }
227 |
228 | protected function _setupCache()
229 | {
230 | $options = $this->getOptions();
231 |
232 | $cachable = array('metadata', 'query', 'result');
233 |
234 | foreach ($cachable as $thing) {
235 | // we trigger a E_USER_NOTICE if the APPLICATION_ENV === production
236 | // for "educational purpose only"
237 | if (!empty($options['cache'][$thing])) {
238 | $cache = $options['cache'][$thing];
239 | if (class_exists($cache)) {
240 | $cache = new $cache;
241 | }
242 |
243 | $method = 'set' . ucfirst($thing) . 'CacheImpl';
244 | $this->_configuration->$method($cache);
245 | } elseif (('metadata' === $thing || 'query' === $thing)
246 | && 'production' === APPLICATION_ENV) {
247 | trigger_error('You should really cache metadata in production environement');
248 | }
249 | }
250 | }
251 |
252 | // Fallback methods for other parameters
253 |
254 | protected function _setupOptions()
255 | {
256 | $options = $this->getOptions();
257 |
258 | if (!empty($options['options']['sqlLogger'])) {
259 | $sqlLogger = new $options['options']['sqlLogger'];
260 |
261 | $this->getConfiguration()->setSQLLogger($sqlLogger);
262 | }
263 |
264 | if (!empty($options['options']['useCExtension'])) {
265 | $this->getConfiguration()
266 | ->setUseCExtension((bool)$options['options']['useCExtension']);
267 | }
268 | }
269 |
270 | protected function _setupProxy()
271 | {
272 | $options = $this->getOptions();
273 |
274 | // Those are mandatory options.
275 | if (!empty($options['proxy']['dir'])) {
276 | $this->getConfiguration()->setProxyDir($options['proxy']['dir']);
277 | }
278 |
279 | if (!empty($options['proxy']['namespace'])) {
280 | $this->getConfiguration()->setProxyNamespace($options['proxy']['namespace']);
281 | }
282 |
283 | // this one is optionnal, but not recommended in production
284 | if (isset($options['proxy']['autoGenerateClasses'])) {
285 | $autoGenerateClasses = (bool) $options['proxy']['autoGenerateClasses'];
286 | $this->getConfiguration()
287 | ->setAutoGenerateProxyClasses($autoGenerateClasses);
288 |
289 | if (true === $autoGenerateClasses
290 | && 'production' === APPLICATION_ENV) {
291 | trigger_error('Generate proxies classes in production is not recommended.');
292 | }
293 | }
294 | }
295 |
296 | protected function _setupCustomTypes()
297 | {
298 | $options = $this->getOptions();
299 |
300 | if (!empty($options['types'])) {
301 | if (is_array($options['types'])) {
302 | foreach ($options['types'] as $name => $class) {
303 | if (is_string($name)) {
304 | if (class_exists($class)) {
305 | //$this->getConfiguration()->setCustomTypes();
306 | Type::addType($name, $class);
307 | }
308 | } else {
309 | throw new Bgy_Application_Resource_Exception(
310 | "Name must be a string, " . gettype($name) . " given"
311 | );
312 | }
313 | }
314 |
315 | } else {
316 | throw new Bgy_Application_Resource_Exception(
317 | "Types option must be an array, you must provide the "
318 | . "name and the corresponding class of the custom type."
319 | );
320 | }
321 | }
322 | }
323 |
324 | public function _setupCustomHydrators()
325 | {
326 | $options = $this->getOptions();
327 |
328 | if (!empty($options['hydrators'])) {
329 | if (is_array($options['hydrators'])) {
330 | foreach ($options['hydrators'] as $name => $class) {
331 | if (is_string($name)) {
332 | if (class_exists($class)) {
333 | $this->getConfiguration()
334 | ->addCustomHydrationMode($name, $class);
335 | }
336 | } else {
337 | throw new Bgy_Application_Resource_Exception(
338 | "Name must be a string, " . gettype($name) . " given"
339 | );
340 | }
341 | }
342 |
343 | } else {
344 | throw new Bgy_Application_Resource_Exception(
345 | "Types option must be an array, you must provide the "
346 | . "name and the corresponding class of the custom type."
347 | );
348 | }
349 | }
350 | }
351 | }
352 |
--------------------------------------------------------------------------------
/library/Bgy/Service/Geonames.php:
--------------------------------------------------------------------------------
1 |
17 | * @license http://sam.zoy.org/wtfpl/COPYING
18 | * @link http://borisguery.github.com/bgylibrary
19 | */
20 |
21 | /**
22 | * @see Zend_Rest_Client
23 | */
24 | require_once 'Zend/Rest/Client.php';
25 |
26 | /**
27 | * @see Zend_Json
28 | */
29 | require_once 'Zend/Json.php';
30 |
31 | /**
32 | * @method array astergdem() astergdem(array $params)
33 | * @method array children() children(array $params)
34 | * @method array cities() cities(array $params)
35 | * @method array countryCode() countryCode(array $params)
36 | * @method array countryInfo() countryInfo(array $params)
37 | * @method array countrySubdivision() countrySubdivision(array $params)
38 | * @method array earthquakes() earthquakes(array $params)
39 | * @method array extendedFindNearby() extendedFindNearby(array $params)
40 | * @method array findNearby() findNearby(array $params)
41 | * @method array findNearbyPlaceName() findNearbyPlaceName(array $params)
42 | * @method array findNearbyPostalCodes() findNearbyPostalCodes(array $params)
43 | * @method array findNearbyStreets() findNearbyStreets(array $params)
44 | * @method array findNearbyStreetsOSM() findNearbyStreetsOSM(array $params)
45 | * @method array findNearByWeather() findNearByWeather(array $params)
46 | * @method array findNearByWikipedia() findNearByWikipedia(array $params)
47 | * @method array findNearestAddress() findNearestAddress(array $params)
48 | * @method array findNearestIntersection() findNearestIntersection(array $params)
49 | * @method array findNearestIntersectionOSM() findNearestIntersectionOSM(array $params)
50 | * @method array get() get(array $params)
51 | * @method array gtopo30() gtopo30(array $params)
52 | * @method array hierarchy() hierarchy(array $params)
53 | * @method array neighbourhoud() neighbourhoud(array $params)
54 | * @method array neighbours() neighbours(array $params)
55 | * @method array postalCodeCountryInfo() postalCodeCountryInfo(array $params)
56 | * @method array postalCodeLookup() postalCodeLookup(array $params)
57 | * @method array search() search(array $params)
58 | * @method array siblings() siblings(array $params)
59 | * @method array srtm3() srtm3(array $params)
60 | * @method array timezone() timezone(array $params)
61 | * @method array weather() weather(array $params)
62 | * @method array weatherIcao() weatherIcao(array $params)
63 | * @method array wikipediaBoundingBox() wikipediaBoundingBox(array $params)
64 | * @method array wikipediaSearch() wikipediaSearch(array $params)
65 | */
66 |
67 | class Bgy_Service_Geonames
68 | {
69 |
70 | const API_URI = 'http://api.geonames.org';
71 |
72 | /**
73 | * Supported methods
74 | * Describe prefered output type and root property/node
75 | * to format the result in a user-friendly manner
76 | *
77 | * @var array
78 | */
79 | protected static $_supportedMethods = array(
80 | 'astergdem' => array(
81 | 'output' => 'json',
82 | ),
83 | 'children' => array(
84 | 'output' => 'json',
85 | 'root' => 'geonames',
86 | ),
87 | 'cities' => array(
88 | 'output' => 'json',
89 | 'root' => 'geonames',
90 | ),
91 | 'countryCode' => array(
92 | 'output' => 'json',
93 | ),
94 | 'countryInfo' => array(
95 | 'output' => 'json',
96 | 'root' => 'geonames',
97 | ),
98 | 'countrySubdivision' => array(
99 | 'output' => 'json',
100 | ),
101 | 'earthquakes' => array(
102 | 'output' => 'json',
103 | 'root' => 'earthquakes',
104 | ),
105 | 'extendedFindNearby' => array(
106 | 'output' => 'xml',
107 | ),
108 | 'findNearby' => array(
109 | 'output' => 'json',
110 | 'root' => 'geonames',
111 | ),
112 | 'findNearbyPlaceName' => array(
113 | 'output' => 'json',
114 | 'root' => 'geonames',
115 | ),
116 | 'findNearbyPostalCodes' => array(
117 | 'output' => 'json',
118 | 'root' => 'postalCodes',
119 | ),
120 | 'findNearbyStreets' => array(
121 | 'output' => 'json',
122 | 'root' => 'streetSegment',
123 | ),
124 | 'findNearbyStreetsOSM' => array(
125 | 'output' => 'json',
126 | 'root' => 'streetSegment',
127 | ),
128 | 'findNearByWeather' => array(
129 | 'output' => 'json',
130 | 'root' => 'weatherObservation',
131 | ),
132 | 'findNearByWikipedia' => array(
133 | 'output' => 'json',
134 | 'root' => 'geonames',
135 | ),
136 | 'findNearestAddress' => array(
137 | 'output' => 'json',
138 | 'root' => 'address',
139 | ),
140 | 'findNearestIntersection' => array(
141 | 'output' => 'json',
142 | 'root' => 'intersection',
143 | ),
144 | 'findNearestIntersectionOSM' => array(
145 | 'output' => 'json',
146 | 'root' => 'intersection',
147 | ),
148 | 'get' => array(
149 | 'output' => 'json',
150 | ),
151 | 'gtopo30' => array(
152 | 'output' => 'json',
153 | ),
154 | 'hierarchy' => array(
155 | 'output' => 'json',
156 | 'root' => 'geonames',
157 | ),
158 | 'neighbourhoud' => array(
159 | 'output' => 'json',
160 | 'root' => 'neighbourhood',
161 | ),
162 | 'neighbours' => array(
163 | 'output' => 'json',
164 | 'root' => 'geonames',
165 | ),
166 | 'postalCodeCountryInfo' => array(
167 | 'output' => 'json',
168 | 'root' => 'geonames',
169 | ),
170 | 'postalCodeLookup' => array(
171 | 'output' => 'json',
172 | 'root' => 'postalcodes',
173 | ),
174 | 'postalCodeSearch' => array(
175 | 'output' => 'json',
176 | 'root' => 'postalCodes',
177 | ),
178 | 'search' => array(
179 | 'output' => 'json',
180 | 'root' => 'geonames',
181 | ),
182 | 'siblings' => array(
183 | 'output' => 'json',
184 | 'root' => 'geonames',
185 | ),
186 | 'srtm3' => array(
187 | 'output' => 'json',
188 | ),
189 | 'timezone' => array(
190 | 'output' => 'json',
191 | ),
192 | 'weather' => array(
193 | 'output' => 'json',
194 | 'root' => 'weatherObservations',
195 | ),
196 | 'weatherIcao' => array(
197 | 'output' => 'json',
198 | 'root' => 'weatherObservation',
199 | ),
200 | 'wikipediaBoundingBox' => array(
201 | 'output' => 'json',
202 | 'root' => 'geonames',
203 | ),
204 | 'wikipediaSearch' => array(
205 | 'output' => 'json',
206 | 'root' => 'geonames',
207 | ),
208 | );
209 |
210 | /**
211 | * Username
212 | *
213 | * @var string
214 | */
215 | protected $_username;
216 |
217 | /**
218 | * Token
219 | *
220 | * @var string
221 | */
222 | protected $_token;
223 |
224 | /**
225 | * Zend_Rest_Client instance
226 | *
227 | * @var Zend_Rest_Client
228 | */
229 | protected $_rest = null;
230 |
231 | /**
232 | * Options passed to constructor
233 | *
234 | * @var array
235 | */
236 | protected $_options = array();
237 |
238 | /**
239 | * Construct a new Geonames.org web service
240 | *
241 | * @param array $options
242 | * @return void
243 | */
244 | public function __construct($options = null)
245 | {
246 | if ($options instanceof Zend_Config) {
247 | $options = $options->toArray();
248 | }
249 | $this->_options = $options;
250 |
251 | if (isset($options['username'])) {
252 | $this->setUsername($options['username']);
253 | unset($options['username']);
254 | }
255 |
256 | if (isset($options['token'])) {
257 | $this->setToken($options['token']);
258 | unset($options['token']);
259 | }
260 |
261 | $this->_rest = new Zend_Rest_Client();
262 | }
263 |
264 | /**
265 | * Set username
266 | *
267 | * @param string $username
268 | * @return Bgy_Service_Geonames Provides a fluent interface
269 | */
270 | public function setUsername($username)
271 | {
272 | $this->_username = $username;
273 |
274 | return $this;
275 | }
276 |
277 | /**
278 | * Get username
279 | *
280 | * @return string
281 | */
282 | public function getUsername()
283 | {
284 | return $this->_username;
285 | }
286 |
287 |
288 | /**
289 | * Set token
290 | *
291 | * @param string $token
292 | * @return Bgy_Service_Geonames Provides a fluent interface
293 | */
294 | public function setToken($token)
295 | {
296 | $this->_token = $token;
297 |
298 | return $this;
299 | }
300 |
301 | /**
302 | * Get token
303 | *
304 | * @return string
305 | */
306 | public function getToken()
307 | {
308 | return $this->_token;
309 | }
310 |
311 | /**
312 | * Retrieve all the supported methods
313 | *
314 | * @deprecated Proxy to getSupportedMethods
315 | * @return array Supported methods
316 | */
317 | public static function getAvailableMethods()
318 | {
319 | return self::getSupportedMethods();
320 | }
321 |
322 | /**
323 | * Retrieve all the supported methods
324 | *
325 | * @return array Supported methods
326 | */
327 | public static function getSupportedMethods()
328 | {
329 | return array_keys(self::$_supportedMethods);
330 | }
331 |
332 | /**
333 | * Method overloading which checks for supported methods
334 | *
335 | * @param string $method The webservice method
336 | * @param array $params The parameters
337 | * @throws Bgy_Service_Geonames_Exception
338 | * @return array
339 | */
340 | public function __call($method, $params = array())
341 | {
342 | if (!in_array($method, $this->getSupportedMethods())) {
343 | include_once 'Bgy/Service/Geonames/Exception.php';
344 | throw new Bgy_Service_Geonames_Exception(
345 | 'Invalid method "' . $method . '"'
346 | );
347 | }
348 |
349 | if (isset($params[0])) {
350 | if (!is_array($params[0])) {
351 | include_once 'Bgy/Service/Geonames/Exception.php';
352 | throw new Bgy_Service_Geonames_Exception(
353 | '$params must be an Array, "'.gettype($params[0]).'" given'
354 | );
355 | }
356 |
357 | $params = $params[0];
358 | }
359 |
360 | $result = $this->makeRequest($method, $params);
361 | $this->_evalResult($result);
362 |
363 | return $result;
364 | }
365 |
366 | /**
367 | * Handles all GET requests to a web service
368 | *
369 | * @param string $method Requested API method
370 | * @param array $params Array of GET parameters
371 | * @return mixed decoded response from web service
372 | * @throws Bgy_Service_Geonames_Exception
373 | */
374 |
375 | public function makeRequest($method, $params = array())
376 | {
377 | $this->_rest->setUri(self::API_URI);
378 | $path = $method;
379 | $type = self::$_supportedMethods[$path]['output'];
380 |
381 | // Construct the path accordingly to the output type
382 | switch ($type) {
383 | case 'json':
384 | $path = $path . 'JSON';
385 | break;
386 | case 'xml':
387 | $params += array('type' => 'xml');
388 | break;
389 | default:
390 | /**
391 | * @see Bgy_Service_Geonames_Exception
392 | */
393 | require_once 'Bgy/Service/Geonames/Exception.php';
394 | throw new Bgy_Service_Geonames_Exception(
395 | 'Unknown request type'
396 | );
397 | }
398 |
399 | if (null !== $this->getUsername()) {
400 | $params['username'] = $this->getUsername();
401 | }
402 |
403 | if (null !== $this->getToken()) {
404 | $params['token'] = $this->getToken();
405 | }
406 |
407 | $response = $this->_rest->restGet($path, $params);
408 |
409 | if (!$response->isSuccessful()) {
410 | /**
411 | * @see Bgy_Service_Geonames_Exception
412 | */
413 | require_once 'Bgy/Service/Geonames/Exception.php';
414 | throw new Bgy_Service_Geonames_Exception(
415 | "Http client reported an error: '{$response->getMessage()}'"
416 | );
417 | }
418 |
419 | $responseBody = $response->getBody();
420 |
421 | switch ($type) {
422 | case 'xml':
423 | $dom = new DOMDocument() ;
424 | if (!@$dom->loadXML($responseBody)) {
425 | /**
426 | * @see Bgy_Service_Geonames_Exception
427 | */
428 | require_once 'Bgy/Service/Geonames/Exception.php';
429 | throw new Bgy_Service_Geonames_Exception('Malformed XML');
430 | }
431 | $jsonResult = Zend_Json::fromXml($dom->saveXML());
432 | break;
433 | case 'json':
434 | $jsonResult = $responseBody;
435 | break;
436 | }
437 | $arrayFromJson = Zend_Json::decode($jsonResult);
438 |
439 | if (isset(self::$_supportedMethods[$method]['root'])
440 | && (null !== ($root = self::$_supportedMethods[$method]['root']))
441 | && isset($arrayFromJson[$root])) {
442 | $arrayFromJson = $arrayFromJson[$root];
443 | }
444 |
445 | return $arrayFromJson;
446 | }
447 |
448 | /**
449 | * Evaluates result
450 | *
451 | * @param Array $result
452 | * @return void
453 | * @throws Bgy_Service_Geonames_Exception
454 | */
455 | private function _evalResult($result)
456 | {
457 | if (isset($result['status']['value'])
458 | && isset($result['status']['message'])) {
459 | $strValue = (int)$result['status']['value'];
460 | $strMessage = $result['status']['message'];
461 | /**
462 | * @see Bgy_Service_Geonames_Exception
463 | */
464 | require_once 'Bgy/Service/Geonames/Exception.php';
465 | throw new Bgy_Service_Geonames_Exception(
466 | "Geonames web service: '{$strMessage}'",
467 | $strValue
468 | );
469 | }
470 | }
471 | }
--------------------------------------------------------------------------------
/library/Bgy/Mail/Template.php:
--------------------------------------------------------------------------------
1 |
9 | *
10 | */
11 | namespace Bgy\Mail;
12 | use Bgy\Mail\Template;
13 |
14 | class Template extends \Zend_Mail
15 | {
16 |
17 | const FORMAT_HTML = 'html';
18 | const FORMAT_TEXT = 'text';
19 | const FORMAT_BOTH = 'both';
20 |
21 | /**
22 | * Obscure name used by view helpers to avoid conflict
23 | *
24 | * @var string
25 | */
26 | const VAR_SUBJECT = '#INTERNAL#EmailSubject#INTERNAL#';
27 |
28 | /**
29 | * Obscure name used by view helpers to avoid conflict
30 | *
31 | * @var string
32 | */
33 | const VAR_SUBJECT_PLACEMENT = '#INTERNAL#EmailSubjectPlacement#INTERNAL#';
34 |
35 | /**
36 | * The html prefix (ie: phtml) without the leading '.' (dot)
37 | * @var string
38 | */
39 | protected $_htmlSuffix = 'phtml';
40 | protected static $_defaultHtmlSuffix;
41 |
42 | /**
43 | * The text prefix (ie: ptxt) without the leading '.' (dot)
44 | * @var string
45 | */
46 | protected $_textSuffix = 'ptxt';
47 | protected static $_defaultTextSuffix;
48 |
49 | /**
50 | * @var Zend_Layout
51 | */
52 | protected $_layout;
53 | protected static $_defaultLayout;
54 |
55 | /**
56 | * The path to find the layouts
57 | *
58 | * @var string
59 | */
60 | protected static $_defaultLayoutPath;
61 |
62 | /**
63 | *
64 | * @var Zend_View_Interface
65 | */
66 | protected $_view;
67 | protected static $_defaultView;
68 |
69 | /**
70 | *
71 | * The path with the view scripts
72 | * @var string
73 | */
74 | protected $_templatePath;
75 | protected static $_defaultTemplatePath;
76 |
77 | /**
78 | * The view script name (without the suffix)
79 | * @var string
80 | */
81 | protected $_templateScript;
82 |
83 | /**
84 | * The format to use
85 | * Bgy\Mail\Template::FORMAT_HTML
86 | * Bgy\Mail\Template::FORMAT_TEXT
87 | * Bgy\Mail\Template::FORMAT_BOTH
88 | * @var string
89 | */
90 | protected $_format;
91 |
92 | /**
93 | *
94 | * By default, we send the both format if available
95 | * @var string
96 | */
97 | protected static $_defaultFormat = self::FORMAT_BOTH;
98 |
99 | /**
100 | * Mail character set
101 | * @var string
102 | */
103 | protected static $_defaultCharset = 'iso-8859-1';
104 |
105 | /**
106 | *
107 | * The HTML Renderer to convert Html to Text
108 | * @var \Bgy\Mail\Template\Html\Renderer
109 | */
110 | protected $_htmlRenderer;
111 | protected static $_defaultHtmlRenderer;
112 |
113 | /**
114 | *
115 | * The variables to assign to the view object
116 | * @var Array
117 | */
118 | protected $_viewVariables = array();
119 |
120 | /**
121 | *
122 | * Default subject to use for all emails
123 | * @var string
124 | */
125 | protected static $_defaultSubject;
126 |
127 | /**
128 | *
129 | * Default subject to use for all emails
130 | * @var string
131 | */
132 | protected static $_defaultSubjectSeparator;
133 |
134 | /**
135 | *
136 | * Default subject to use for all emails
137 | * @var string
138 | */
139 | protected $_subjectSeparator;
140 |
141 | /**
142 | *
143 | * Convert html to text when the text version is missing
144 | * @var bool
145 | */
146 | protected $_convertHtmlToText;
147 | protected static $_defaultConvertHtmlToText;
148 |
149 | /**
150 | *
151 | * Available options
152 | * 'layout' => Zend_Layout
153 | * 'view' => Zend_View
154 | * 'charset' => 'utf-8'
155 | * 'htmlSuffix' => 'phtml'
156 | * 'textSuffix' => 'ptxt'
157 | * 'layoutPath' => 'layout/scripts'
158 | * 'layoutScript' => 'layout'
159 | * 'templatePath' => 'templates/path'
160 | *
161 | * @param Zend_Config|Array $options
162 | * @return void
163 | */
164 | public function __construct($options = array())
165 | {
166 | // We reset the actual charset which defaults to 'iso-8859-1'
167 | // to allow a custom default charset
168 | $this->setCharset(null);
169 |
170 | if (is_array($options)) {
171 | $this->setOptions($options);
172 | } elseif ($options instanceof \Zend_Config) {
173 | $this->setOptions($options->toArray());
174 | }
175 |
176 | $this->init();
177 | }
178 |
179 | /**
180 | * Initialize default variables
181 | *
182 | * @return void
183 | */
184 | public function init()
185 | {
186 | if (null === $this->getHtmlSuffix() && null !== self::getDefaultHtmlSuffix())
187 | {
188 | $this->setHtmlSuffixToDefault();
189 | }
190 |
191 | if (null === $this->getTextSuffix() && null !== self::getDefaultTextSuffix())
192 | {
193 | $this->setTextSuffixToDefault();
194 | }
195 |
196 | if (null === $this->getTemplatePath()) {
197 | $this->setTemplatePathToDefault();
198 | }
199 |
200 | if (null === $this->getLayout()->getLayoutPath()) {
201 | $this->setLayoutPathToDefault();
202 | }
203 |
204 | if (method_exists($this->getView(), 'addScriptPath')) {
205 | $this->getView()->addScriptPath($this->getTemplatePath());
206 | } else {
207 | $this->getView()->setScriptPath($this->getTemplatePath());
208 | }
209 |
210 | if (null === $this->getFormat()) {
211 | $this->setFormatToDefault();
212 | }
213 |
214 | if (null === $this->getSubjectSeparator()) {
215 | $this->setSubjectSeparatorToDefault();
216 | }
217 |
218 | if (null === $this->isConvertHtmlToText()) {
219 | $this->setConvertHtmlToTextToDefault();
220 | }
221 |
222 | if (null === $this->getCharset()) {
223 | $this->setCharsetToDefault();
224 | }
225 | }
226 |
227 | /**
228 | * Set Options from an Array
229 | *
230 | * @param array $options
231 | * @return Bgy\Mail\Template Provides fluent interface
232 | */
233 | public function setOptions(Array $options = array())
234 | {
235 | if (isset($options['view'])) {
236 | $view = $options['view'];
237 | if (is_string($view)) {
238 | $view = new $view;
239 | }
240 | } else {
241 | // Set default view to Zend_View
242 | $view = new \Zend_View();
243 | }
244 | unset($options['view']);
245 |
246 | if (isset($options['layout'])) {
247 | $layout = $options['layout'];
248 | if (is_string($layout)) {
249 | $layout = new $layout;
250 | }
251 | } else {
252 | // Default layout to Zend_Layout
253 | $layout = new \Zend_Layout();
254 | }
255 |
256 | if (isset($options['htmlRenderer'])) {
257 | $htmlRenderer = $options['htmlRenderer'];
258 | if (is_string($htmlRenderer)) {
259 | $htmlRenderer = new $htmlRenderer;
260 | }
261 | } else {
262 | // Default provided Html Renderer to convert Html to Text
263 | $htmlRenderer = new Template\Html\Renderer\SimpleText();
264 | }
265 |
266 | $this->setHtmlRenderer($htmlRenderer);
267 | unset($options['htmlRenderer']);
268 |
269 | $layout->setView($view);
270 | $this->setLayout($layout);
271 | $this->setView($view);
272 | unset($options['layout']);
273 |
274 | if (!isset($options['layoutScript'])) {
275 | // Default layout script name 'layout'
276 | $options['layoutScript'] = 'layout';
277 | }
278 |
279 | foreach ($options as $key => $value) {
280 | $method = 'set' . ucfirst($key);
281 | if (method_exists($this, $method)) {
282 | $this->$method($value);
283 | }
284 | unset($options[$key]);
285 | }
286 |
287 | return $this;
288 | }
289 |
290 | /**
291 | * Set the charset used by Zend_Mail
292 | *
293 | * @param string $charset
294 | * @return Bgy\Mail\Template Provides fluent interface
295 | */
296 | public function setCharset($charset)
297 | {
298 | $this->_charset = $charset;
299 |
300 | return $this;
301 | }
302 |
303 | /**
304 | * Sets the default charset used by Zend_Mail
305 | *
306 | * @param string $charset
307 | */
308 | public static function setDefaultCharset($charset)
309 | {
310 | self::$_defaultCharset = $charset;
311 | }
312 |
313 | /**
314 | * Gets the default charset used by Zend_Mail
315 | *
316 | * @return string The default charset
317 | */
318 | public static function getDefaultCharset()
319 | {
320 | return self::$_defaultCharset;
321 | }
322 |
323 | /**
324 | * Clears the default charset
325 | */
326 | public static function clearDefaultCharset()
327 | {
328 | self::$_defaultCharset = null;
329 | }
330 |
331 | /**
332 | * Sets the charsets based on the defaults
333 | *
334 | * @return Bgy\Mail\Template Provides fluent interface
335 | */
336 | public function setCharsetToDefault()
337 | {
338 | $charset = self::getDefaultCharset();
339 | $this->setCharset($charset);
340 |
341 | return $this;
342 | }
343 |
344 | /**
345 | * Set the Renderer used to convert Html template to Text version
346 | *
347 | * @param Bgy\Mail\Template\Html\Renderer $renderer
348 | * @return Bgy\Mail\Template Provides fluent interface
349 | */
350 | public function setHtmlRenderer(Template\Html\Renderer $renderer)
351 | {
352 | $this->_htmlRenderer = $renderer;
353 |
354 | return $this;
355 | }
356 |
357 | /**
358 | * Return the Html Renderer
359 | *
360 | * @return \Bgy\Mail\Template\Html\Renderer
361 | */
362 | public function getHtmlRenderer()
363 | {
364 | return $this->_htmlRenderer;
365 | }
366 |
367 | /**
368 | * Set the Layout Object
369 | * It must be an instance of Zend_Layout
370 | *
371 | * @param \Zend_Layout $layout
372 | * @return Bgy\Mail\Template Provides fluent interface
373 | */
374 | public function setLayout(\Zend_Layout $layout)
375 | {
376 | $this->_layout = $layout;
377 |
378 | return $this;
379 | }
380 |
381 | /**
382 | * @return Zend_Layout
383 | */
384 | public function getLayout()
385 | {
386 |
387 | return $this->_layout;
388 | }
389 |
390 | /**
391 | * Sets the view object
392 | * Load helpers paths if found in Zend_Layout instance
393 | *
394 | * @param Zend_View_Interface $view
395 | * @return Bgy\Mail\Template Provides fluent interface
396 | */
397 | public function setView(\Zend_View_Interface $view = null)
398 | {
399 | if (\Zend_Layout::getMvcInstance() && ($layoutView = \Zend_Layout::getMvcInstance()->getView())
400 | && method_exists($layoutView, 'getHelperPaths') && method_exists($view, 'addHelperPath')) {
401 | // Use of \\ to fix problem when add a Prefix with namespaces (else _ is appended)
402 | $view->addHelperPath(dirname(__FILE__) . '/Template/View/Helper', 'Bgy\Mail\Template\View\Helper\\');
403 | $helperPaths = $layoutView->getHelperPaths();
404 | foreach ($helperPaths as $prefix => $paths) {
405 | foreach ($paths as $path) {
406 | $view->addHelperPath($path, $prefix);
407 | }
408 | }
409 | } elseif (($layoutView = $this->getLayout()->getView()) && method_exists($view, 'addHelperPath')) {
410 | $view->addHelperPath(dirname(__FILE__) . '/Template/View/Helper', 'Bgy\Mail\Template\View\Helper\\');
411 | }
412 |
413 | $this->_view = $view;
414 |
415 | return $this;
416 | }
417 |
418 | /**
419 | * @return Zend_View
420 | */
421 | public function getView()
422 | {
423 |
424 | return $this->_view;
425 | }
426 |
427 | /**
428 | *
429 | * Sets the default view objec to use
430 | *
431 | * @param \Zend_View_Interface $view
432 | */
433 | public static function setDefaultView(\Zend_View_Interface $view)
434 | {
435 | self::$_defaultView = $view;
436 | }
437 |
438 | /**
439 | * Sets the variables to assign to the view object
440 | * This will clear any previously used variables
441 | *
442 | * @param array $variables
443 | * @return Bgy\Mail\Template Provides fluent interface
444 | */
445 | public function setViewVariables(Array $variables)
446 | {
447 | $this->clearViewVariables();
448 | $this->_viewVariables = $variables;
449 |
450 | return $this;
451 | }
452 |
453 | /**
454 | * Add a variable to assign to the view object
455 | *
456 | * @param string $name
457 | * @param any Optional $value
458 | * @return Bgy\Mail\Template Provides fluent interface
459 | */
460 | public function addViewVariable($name, $value = null)
461 | {
462 | $this->_viewVariables[$name] = $value;
463 |
464 | return $this;
465 | }
466 |
467 | /**
468 | * Adds views variable to assign to the view object
469 | *
470 | * @param array $variables
471 | * @return Bgy\Mail\Template Provides fluent interface
472 | */
473 | public function addViewVariables(Array $variables)
474 | {
475 | $this->_viewVariables += $variables;
476 |
477 | return $this;
478 | }
479 |
480 | /**
481 | * Clear all views variables that will be assigned to the view object
482 | *
483 | * @return Bgy\Mail\Template Provides fluent interface
484 | */
485 | public function clearViewVariables()
486 | {
487 | $this->_viewVariables = array();
488 |
489 | return $this;
490 | }
491 |
492 | /**
493 | * Gets all the variables that will be assigned to the view object
494 | *
495 | * @return array The view variables
496 | */
497 | public function getViewVariables()
498 | {
499 | return $this->_viewVariables;
500 | }
501 |
502 | public function send($transport = null)
503 | {
504 | $layout = $this->getLayout();
505 | $this->getView()->assign($this->getViewVariables());
506 |
507 | switch ($this->getFormat()) {
508 | case self::FORMAT_HTML:
509 | $processedTemplate = $this->_processTemplate($this->getTemplate(), $this->getHtmlSuffix());
510 | $this->setBodyHtml($processedTemplate);
511 | break;
512 |
513 | case self::FORMAT_TEXT:
514 | $processedTemplate = $this->_processTemplate($this->getTemplate(), $this->getTextSuffix());
515 | $this->setBodyText($processedTemplate);
516 | break;
517 |
518 | case self::FORMAT_BOTH:
519 | default:
520 | $processedTemplate = $this->_processTemplate($this->getTemplate(), $this->getHtmlSuffix());
521 | $this->setBodyHtml($processedTemplate);
522 | $processedTemplate = $this->_processTemplate($this->getTemplate(), $this->getTextSuffix());
523 | $this->setBodyText($processedTemplate);
524 | break;
525 | }
526 |
527 | $this->setSubject($this->_formatSubject());
528 |
529 | parent::send($transport);
530 |
531 | return $this;
532 | }
533 |
534 | /**
535 | * Processes the template script, passes through the layout
536 | *
537 | * @param string $template
538 | * @param string $format
539 | * @return string The processed template
540 | * @throws Bgy\Mail\Template\Exception
541 | */
542 | protected function _processTemplate($template, $format)
543 | {
544 | if (!$this->_isTemplateScriptReadable($template . '.' . $format)) {
545 | throw new Template\Exception('Template \'' . $template . '.' . $format . '\' is not readable or does not exist');
546 | }
547 | $this->getLayout()->content = $this->getView()
548 | ->render($template . '.' . $format);
549 |
550 | $processedTemplate = $this->getLayout()->setViewSuffix($format)
551 | ->render();
552 | // we reset the layout
553 | $this->getLayout()->content = null;
554 |
555 | return $processedTemplate;
556 | }
557 |
558 | /**
559 | * Sets if we must convert html to text when the text version is missing
560 | *
561 | * @param bool $flag
562 | */
563 | public function setConvertHtmlToText($flag)
564 | {
565 | $this->_convertHtmlToText = (bool)$flag;
566 |
567 | return $this;
568 | }
569 |
570 | /**
571 | * Convert from Html if Text version does not exist?
572 | *
573 | * @return boolean
574 | */
575 | public function isConvertHtmlToText()
576 | {
577 | return (bool)$this->_convertHtmlToText;
578 | }
579 |
580 | /**
581 | * Convert from Html if Text version does not exist?
582 | *
583 | * @return boolean
584 | */
585 | public static function isDefaultConvertHtmlToText()
586 | {
587 | return (bool)self::$_defaultConvertHtmlToText;
588 | }
589 |
590 | /**
591 | * Sets if we must convert html to text when the text version is missing
592 | *
593 | * @param bool $flag
594 | */
595 | public static function setDefaultConvertHtmlToText($flag)
596 | {
597 | self::$_defaultConvertHtmlToText = (bool)$flag;
598 | }
599 |
600 | /**
601 | * Sets if we must convert html to text based on the defaults
602 | *
603 | * @return Bgy\Mail\Template Provides fluent interface
604 | */
605 | public function setConvertHtmlToTextToDefault()
606 | {
607 | $flag = self::isConvertHtmlToText();
608 | $this->setConvertHtmlToText($flag);
609 |
610 | return $this;
611 | }
612 |
613 | /**
614 | * Appends, Prepends, or Replaces the subject if no subject has been set
615 | *
616 | * @return string The subject
617 | */
618 | protected function _formatSubject()
619 | {
620 | $subject = (null !== $this->getSubject()) ? $this->getSubject() : (string)$this->getDefaultSubject();
621 | if (null === $this->getSubject()) {
622 | if ('PREPEND' === $this->getSubjectPlacement()) {
623 | $subject = $this->getSubjectAddition() . $this->getSubjectSeparator() . $subject;
624 | } elseif ('APPEND' === $this->getSubjectPlacement()) {
625 | $subject .= $this->getSubjectSeparator() . $this->getSubjectAddition();
626 | } elseif ('REPLACE' === $this->getSubjectPlacement()) {
627 | $subject = $this->getSubjectAddition();
628 | }
629 | }
630 |
631 | return $subject;
632 | }
633 |
634 | /**
635 | * Gets where we should place the subject addition
636 | *
637 | * @return string|null
638 | */
639 | public function getSubjectPlacement()
640 | {
641 | $placement = null;
642 | if (isset($this->getView()->{self::VAR_SUBJECT_PLACEMENT})) {
643 | $placement = $this->getView()->{self::VAR_SUBJECT_PLACEMENT};
644 | }
645 |
646 | return $placement;
647 | }
648 |
649 | /**
650 | * Gets the subject addition to be added to the default subject
651 | *
652 | * @return string
653 | */
654 | public function getSubjectAddition()
655 | {
656 | $addition = '';
657 | if (isset($this->getView()->{self::VAR_SUBJECT})) {
658 | $addition = $this->getView()->{self::VAR_SUBJECT};
659 | }
660 |
661 | return $addition;
662 | }
663 |
664 | /* (non-PHPdoc)
665 | * @see Zend_Mail::setSubject()
666 | */
667 | public function setSubject($subject)
668 | {
669 | // we reset the subject to allow override
670 | $this->_subject = null;
671 | parent::setSubject($subject);
672 |
673 | return $this;
674 | }
675 |
676 | /**
677 | * Sets the default subject to use
678 | *
679 | * @param string $subject
680 | */
681 | public static function setDefaultSubject($subject)
682 | {
683 | self::$_defaultSubject = $subject;
684 | }
685 |
686 | /**
687 | * @return string The default subject
688 | */
689 | public static function getDefaultSubject()
690 | {
691 | return self::$_defaultSubject;
692 | }
693 |
694 | /**
695 | * Clears the default subject
696 | */
697 | public static function clearDefaultSubject()
698 | {
699 | self::$_defaultSubject = '';
700 | }
701 |
702 | /**
703 | * Sets the subject based on the defaults
704 | *
705 | * @throws Bgy\Mail\Template\Exception
706 | * @return Bgy\Mail\Template Provides fluent interface
707 | */
708 | public function setSubjectToDefault()
709 | {
710 | $subject = self::$_defautlSubject;
711 | if (null === $subject) {
712 | require_once 'Bgy/Mail/Template/Exception.php';
713 | throw new Template\Exception('No Subject specified');
714 | }
715 |
716 | return $this;
717 | }
718 |
719 | /**
720 | * Sets the default separator used in subject
721 | * Ex: ' - ', ' | '
722 | * You must add the space yourself
723 | *
724 | * @param string $separator The separator
725 | */
726 | public static function setDefaultSubjectSeparator($separator)
727 | {
728 | self::$_defaultSubjectSeparator = $separator;
729 | }
730 |
731 | /**
732 | * Gets the default subject separator
733 | *
734 | * @return string The separator
735 | */
736 | public static function getDefaultSubjectSeparator()
737 | {
738 | return self::$_defaultSubjectSeparator;
739 | }
740 |
741 | /**
742 | * Clears the default subject separator
743 | */
744 | public static function clearDefaultSubjectSeparator()
745 | {
746 | self::$_defaultSubjectSeparator = '';
747 | }
748 |
749 | /**
750 | * Sets the separator in subject
751 | *
752 | * @param string $separator
753 | * @return Bgy\Mail\Template Provides fluent interface
754 | */
755 | public function setSubjectSeparator($separator = '')
756 | {
757 | $this->_subjectSeparator = $separator;
758 |
759 | return $this;
760 | }
761 |
762 | /**
763 | * Gets the subject separator
764 | *
765 | * @return string
766 | */
767 | public function getSubjectSeparator()
768 | {
769 | return $this->_subjectSeparator;
770 | }
771 |
772 | /**
773 | * Sets the default subject separator based on defaults
774 | *
775 | * @return \Bgy\Mail\Template Provides fluent interface
776 | */
777 | public function setSubjectSeparatorToDefault()
778 | {
779 | $separator = self::getDefaultSubjectSeparator();
780 | $this->setSubjectSeparator($separator);
781 |
782 | return $this;
783 | }
784 |
785 | /**
786 | * Checks if a template (view script) exists or is readable
787 | *
788 | * @param bool $template
789 | */
790 | protected function _isTemplateScriptReadable($template)
791 | {
792 | return (bool)$this->getView()->getScriptPath($template);
793 | }
794 |
795 | /**
796 | * Retrieves the text version from an Html template using the Html Renderer
797 | *
798 | * @return string The text version
799 | */
800 | public function getTextFromHtml()
801 | {
802 | $layout = $this->getLayout();
803 | $layout->content = $this->getView()->render($this->getTemplate() . '.' . $this->getHtmlSuffix());
804 | $resultHtml = $layout->setViewSuffix($this->getHtmlSuffix())->render();
805 |
806 | return $this->getHtmlRenderer()->render($resultHtml);
807 | }
808 |
809 | /**
810 | * Sets the template name
811 | *
812 | * @param string $template
813 | * @return Bgy\Mail\Template Provides fluent interface
814 | */
815 | public function setTemplate($template)
816 | {
817 | $this->_templateScript = $template;
818 |
819 | return $this;
820 | }
821 |
822 | /**
823 | * Gets the template name
824 | *
825 | * @return string
826 | */
827 | public function getTemplate()
828 | {
829 | return $this->_templateScript;
830 | }
831 |
832 | /**
833 | * Sets the suffix used by Html templates
834 | *
835 | * @param string $suffix
836 | * @return Bgy\Mail\Template Provides fluent interface
837 | */
838 | public function setHtmlSuffix($suffix)
839 | {
840 | $this->_htmlSuffix = $suffix;
841 |
842 | return $this;
843 | }
844 |
845 | /**
846 | * Gets the suffix used by Html templates
847 | *
848 | * @return string
849 | */
850 | public function getHtmlSuffix()
851 | {
852 | return $this->_htmlSuffix;
853 | }
854 |
855 |
856 | /**
857 | * Sets the default Html suffix to use
858 | *
859 | * @param string $suffix
860 | */
861 | public static function setDefaultHtmlSuffix($suffix)
862 | {
863 | self::$_defaultHtmlSuffix = $suffix;
864 | }
865 |
866 | /**
867 | * Gets the default suffix for Html template
868 | *
869 | * @return string|null Either the suffix or null
870 | */
871 | public static function getDefaultHtmlSuffix()
872 | {
873 | return self::$_defaultHtmlSuffix;
874 | }
875 |
876 | /**
877 | * Clears the default Html suffix
878 | */
879 | public static function clearDefaultHtmlSuffix()
880 | {
881 | self::$_defaultHtmlSuffix = null;
882 | }
883 |
884 | /**
885 | * Sets the Html suffix based on the defaults
886 | *
887 | * @throws Bgy\Mail\Template\Exception
888 | * @return Bgy\Mail\Template Provides fluent interface
889 | */
890 | public function setHtmlSuffixToDefault()
891 | {
892 | $htmlSuffix = self::$_defaultHtmlSuffix;
893 | if (null === $htmlSuffix) {
894 | require_once 'Bgy/Mail/Template/Exception.php';
895 | throw new Template\Exception('No Html Suffix to use');
896 | }
897 |
898 | $this->setHtmlSuffix($htmlSuffix);
899 |
900 | return $this;
901 | }
902 |
903 | /**
904 | * Sets the suffix used by text template
905 | *
906 | * @param unknown_type $suffix
907 | * @return Bgy\Mail\Template Provides fluent interface
908 | */
909 | public function setTextSuffix($suffix)
910 | {
911 | $this->_textSuffix = $suffix;
912 |
913 | return $this;
914 | }
915 |
916 | /**
917 | * Gets the suffix used by text template
918 | *
919 | * @return string
920 | */
921 | public function getTextSuffix()
922 | {
923 | return $this->_textSuffix;
924 | }
925 |
926 |
927 | /**
928 | * Sets the default suffix used by text template
929 | *
930 | * @param unknown_type $suffix
931 | */
932 | public static function setDefaultTextSuffix($suffix)
933 | {
934 | self::$_defaultTextSuffix = $suffix;
935 | }
936 |
937 | /**
938 | * Sets the default suffix used by text template
939 | *
940 | * @return string|null Either the suffix or null
941 | */
942 | public static function getDefaultTextSuffix()
943 | {
944 | return self::$_defaultTextSuffix;
945 | }
946 |
947 | /**
948 | * Clears the default suffix used by text template
949 | */
950 | public static function clearDefaultTextSuffix()
951 | {
952 | self::$_defaultTextSuffix = null;
953 | }
954 |
955 | /**
956 | * Sets the text suffix based on the defaults
957 | *
958 | * @throws Bgy\Mail\Template\Exception
959 | * @return Bgy\Mail\Template Provides fluent interface
960 | */
961 | public function setTextSuffixToDefault()
962 | {
963 | $textSuffix = self::$_defaultTextSuffix;
964 | if (null === $textSuffix) {
965 | require_once 'Bgy/Mail/Template/Exception.php';
966 | throw new Template\Exception('No Text Suffix to use');
967 | }
968 |
969 | $this->setTextSuffix($textSuffix);
970 |
971 | return $this;
972 | }
973 |
974 | /**
975 | * Sets the format to use when sending emails
976 | * Allowed formats are either:
977 | * - 'html' Html version only
978 | * - 'text' Text version only
979 | * - 'both' Both text and html version
980 | *
981 | * @param string $format
982 | * @return Bgy\Mail\Template Provides fluent interface
983 | */
984 | public function setFormat($format)
985 | {
986 | $this->_format = $format;
987 |
988 | return $this;
989 | }
990 |
991 | /**
992 | * Gets the format
993 | *
994 | * @return string
995 | */
996 | public function getFormat()
997 | {
998 | return $this->_format;
999 | }
1000 |
1001 | /**
1002 | * Sets the default format to use when sending emails
1003 | * Allowed formats are either:
1004 | * - 'html' Html version only
1005 | * - 'text' Text version only
1006 | * - 'both' Both text and html version
1007 | *
1008 | * @param string $format
1009 | */
1010 | public static function setDefaultFormat($format)
1011 | {
1012 | self::$_defaultFormat = $format;
1013 | }
1014 |
1015 | /**
1016 | * Gets the default format
1017 | *
1018 | * @return string
1019 | */
1020 | public static function getDefaultFormat()
1021 | {
1022 | return self::$_defaultFormat;
1023 | }
1024 |
1025 | /**
1026 | * Sets the format based on the defaults
1027 | *
1028 | * @throws Bgy\Mail\Template\Exception
1029 | * @return Bgy\Mail\Template Provides fluent interface
1030 | */
1031 | public function setFormatToDefault()
1032 | {
1033 | $format = self::$_defaultFormat;
1034 | if (null === $format) {
1035 | require_once 'Bgy/Mail/Template/Exception.php';
1036 | throw new Template\Exception('No default Format to use');
1037 | }
1038 |
1039 | return $this;
1040 | }
1041 |
1042 | /**
1043 | * Clears the default format
1044 | */
1045 | public static function clearDefaultFormat()
1046 | {
1047 | self::$_defaultFormat = null;
1048 | }
1049 |
1050 | /**
1051 | * Sets the path to templates
1052 | *
1053 | * @param string $path
1054 | * @return Bgy\Mail\Template Provides fluent interface
1055 | */
1056 | public function setTemplatePath($path)
1057 | {
1058 | $this->_templatePath = $path;
1059 |
1060 | return $this;
1061 | }
1062 |
1063 | /**
1064 | * Sets the default path to templates
1065 | *
1066 | * @param string $path
1067 | */
1068 | public static function setDefaultTemplatePath($path)
1069 | {
1070 | self::$_defaultTemplatePath = $path;
1071 | }
1072 |
1073 | /**
1074 | * Clears the default path to templates
1075 | */
1076 | public static function clearDefaultTemplatePath()
1077 | {
1078 | self::$_defaultTemplatePath = null;
1079 | }
1080 |
1081 | /**
1082 | * Sets the path to templates based on the defaults
1083 | *
1084 | * @throws Bgy\Mail\Template\Exception
1085 | * @return Bgy\Mail\Template Provides fluent interface
1086 | */
1087 | public function setTemplatePathToDefault()
1088 | {
1089 | $path = self::$_defaultTemplatePath;
1090 | if (null === $path) {
1091 | require_once 'Bgy/Mail/Template/Exception.php';
1092 | throw new Template\Exception('No template script path set');
1093 | }
1094 |
1095 | $this->setTemplatePath($path);
1096 |
1097 | return $this;
1098 | }
1099 |
1100 | /**
1101 | * Gets the path to templates
1102 | * @return string
1103 | */
1104 | public function getTemplatePath()
1105 | {
1106 | return $this->_templatePath;
1107 | }
1108 |
1109 | /**
1110 | * Sets the path to layout scripts
1111 | *
1112 | * @param string $path
1113 | * @return Bgy\Mail\Template Provides fluent interface
1114 | */
1115 | public function setLayoutPath($path)
1116 | {
1117 | $this->getLayout()->setLayoutPath($path);
1118 |
1119 | return $this;
1120 | }
1121 |
1122 | /**
1123 | * Gets the path to layout scripts
1124 | *
1125 | * @return string
1126 | */
1127 | public function getLayoutPath()
1128 | {
1129 | return $this->getLayout()->getLayoutPath();
1130 | }
1131 |
1132 | /**
1133 | * Sets the default layout path
1134 | *
1135 | * @param string $path
1136 | */
1137 | public static function setDefaultLayoutPath($path)
1138 | {
1139 | self::$_defaultLayoutPath = $path;
1140 | }
1141 |
1142 | /**
1143 | * Gets the default layout path
1144 | *
1145 | * @return string The layout path
1146 | */
1147 | public static function getDefaultLayoutPath()
1148 | {
1149 | return self::$_defaultLayoutPath;
1150 | }
1151 |
1152 | /**
1153 | * Clears the default layout path
1154 | */
1155 | public static function clearDefaultLayoutPath()
1156 | {
1157 | self::$_defaultLayoutPath = null;
1158 | }
1159 |
1160 | /**
1161 | * Sets the layout path based on the defaults
1162 | *
1163 | * @throws \Bgy\Mail\Template\Exception
1164 | * @return \Bgy\Mail\Template Provides fluent interface
1165 | */
1166 | public function setLayoutPathToDefault()
1167 | {
1168 | $layoutPath = self::getDefaultLayoutPath();
1169 | if (null === $layoutPath) {
1170 | require_once 'Bgy/Mail/Template/Exception.php';
1171 | throw new Template\Exception('You must set the path of the layouts');
1172 | }
1173 |
1174 | $this->setLayoutPath($layoutPath);
1175 |
1176 | return $this;
1177 | }
1178 |
1179 | /**
1180 | * Sets the layout script name
1181 | *
1182 | * @param string $scriptName
1183 | * @return Bgy\Mail\Template Provides fluent interface
1184 | */
1185 | public function setLayoutScript($scriptName)
1186 | {
1187 | $this->getLayout()->setLayout($scriptName);
1188 |
1189 | return $this;
1190 | }
1191 |
1192 | /**
1193 | * Gets the layout script name
1194 | *
1195 | * @return string
1196 | */
1197 | public function getLayoutScript()
1198 | {
1199 | return $this->getLayout()->getLayout();
1200 | }
1201 | }
1202 |
--------------------------------------------------------------------------------