beeframework-svn Mailing List for Bee Framework (Page 11)
Brought to you by:
b_hartmann,
m_plomer
You can subscribe to this list here.
2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(5) |
Sep
|
Oct
|
Nov
|
Dec
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2011 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(6) |
2013 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
(12) |
Jun
(5) |
Jul
(6) |
Aug
(25) |
Sep
(25) |
Oct
(6) |
Nov
(29) |
Dec
|
2014 |
Jan
(2) |
Feb
(10) |
Mar
(2) |
Apr
(2) |
May
|
Jun
(5) |
Jul
(35) |
Aug
(9) |
Sep
(33) |
Oct
(30) |
Nov
(4) |
Dec
(1) |
2015 |
Jan
(3) |
Feb
(13) |
Mar
(13) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <m_p...@us...> - 2013-07-30 15:26:37
|
Revision: 46 http://sourceforge.net/p/beeframework/code/46 Author: m_plomer Date: 2013-07-30 15:26:33 +0000 (Tue, 30 Jul 2013) Log Message: ----------- - new exception subclass ProcExecException Added Paths: ----------- trunk/framework/Bee/Exceptions/ProcExecException.php Added: trunk/framework/Bee/Exceptions/ProcExecException.php =================================================================== --- trunk/framework/Bee/Exceptions/ProcExecException.php (rev 0) +++ trunk/framework/Bee/Exceptions/ProcExecException.php 2013-07-30 15:26:33 UTC (rev 46) @@ -0,0 +1,62 @@ +<?php +namespace Bee\Tools; +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 30.07.13 + * Time: 17:21 + * + * todo: move this to Bee Framework + */ + +class ProcExecException extends \Bee_Exceptions_Base { + + private $returnValue; + + private $stdOut; + + private $stdErr; + + function __construct($message, $returnValue, $stdOut, $stdErr) { + parent::__construct($message); + $this->returnValue = $returnValue; + $this->stdOut = $stdOut; + $this->stdErr = $stdErr; + } + + /** + * @return mixed + */ + public function getReturnValue() { + return $this->returnValue; + } + + /** + * @return mixed + */ + public function getStdErr() { + return $this->stdErr; + } + + /** + * @return mixed + */ + public function getStdOut() { + return $this->stdOut; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-07-01 11:39:56
|
Revision: 45 http://sourceforge.net/p/beeframework/code/45 Author: m_plomer Date: 2013-07-01 11:39:54 +0000 (Mon, 01 Jul 2013) Log Message: ----------- - IScopeAware Modified Paths: -------------- trunk/framework/Bee/MVC/Dispatcher.php Modified: trunk/framework/Bee/MVC/Dispatcher.php =================================================================== --- trunk/framework/Bee/MVC/Dispatcher.php 2013-07-01 11:25:52 UTC (rev 44) +++ trunk/framework/Bee/MVC/Dispatcher.php 2013-07-01 11:39:54 UTC (rev 45) @@ -59,7 +59,7 @@ /** * @var Bee_MVC_IHttpRequest */ - private static $currentRequest; + private static $currentRequest = null; /** * The root context used by this dispatcher @@ -111,6 +111,10 @@ * @return Bee_MVC_IHttpRequest */ public static function getCurrentRequest() { + if(is_null(self::$currentRequest)) { + throw new Bee_Exceptions_Base('No request object constructed yet'); + } + return self::$currentRequest; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-07-01 11:25:55
|
Revision: 44 http://sourceforge.net/p/beeframework/code/44 Author: m_plomer Date: 2013-07-01 11:25:52 +0000 (Mon, 01 Jul 2013) Log Message: ----------- - IScopeAware Modified Paths: -------------- trunk/framework/Bee/Context/Abstract.php trunk/framework/Bee/Framework.php trunk/framework/Bee/MVC/Dispatcher.php Added Paths: ----------- trunk/framework/Bee/Context/Config/IScopeAware.php Modified: trunk/framework/Bee/Context/Abstract.php =================================================================== --- trunk/framework/Bee/Context/Abstract.php 2013-06-28 17:29:46 UTC (rev 43) +++ trunk/framework/Bee/Context/Abstract.php 2013-07-01 11:25:52 UTC (rev 44) @@ -219,7 +219,7 @@ return $exposedObject; } - + /** * Initialize the given bean instance, applying factory callbacks * as well as init methods and bean post processors. @@ -229,8 +229,10 @@ * @param object $bean the new bean instance we may need to initialize * @param Bee_Context_Config_IBeanDefinition $beanDefinition the bean definition that the bean was created with * (can also be <code>null</code>, if given an existing bean instance) + * @throws Bee_Context_BeanCreationException * @return object the initialized bean instance (potentially wrapped) * @see Bee_Context_Config_IBeanNameAware + * @see \Bee\Context\Config\IScopeAware * @see Bee_Context_Config_IContextAware * @see #invokeInitMethods */ @@ -239,10 +241,14 @@ $bean->setBeanName($beanName); } + if ($bean instanceof \Bee\Context\Config\IScopeAware) { + $beanDefinition->getScope($this); + } + if ($bean instanceof Bee_Context_Config_IContextAware) { $bean->setBeeContext($this); } - + $wrappedBean = $bean; if (is_null($beanDefinition) || !$beanDefinition->isSynthetic()) { $wrappedBean = $this->applyBeanPostProcessorsBeforeInitialization($wrappedBean, $beanName); Added: trunk/framework/Bee/Context/Config/IScopeAware.php =================================================================== --- trunk/framework/Bee/Context/Config/IScopeAware.php (rev 0) +++ trunk/framework/Bee/Context/Config/IScopeAware.php 2013-07-01 11:25:52 UTC (rev 44) @@ -0,0 +1,31 @@ +<?php +namespace Bee\Context\Config; +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 01.07.13 + * Time: 13:21 + */ + +interface IScopeAware { + /** + * @param string $scope + * @return void + */ + public function setScope($scope); +} Modified: trunk/framework/Bee/Framework.php =================================================================== --- trunk/framework/Bee/Framework.php 2013-06-28 17:29:46 UTC (rev 43) +++ trunk/framework/Bee/Framework.php 2013-07-01 11:25:52 UTC (rev 44) @@ -259,14 +259,14 @@ echo '<div>'; echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; - echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Message</div>'; + echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="toggle(event);">Message</div>'; echo '<div style="padding: 5px;">'; echo $e->getMessage(); echo '</div>'; echo '</div>'; echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; - echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Stracktrace</div>'; + echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="toggle(event);">Stracktrace</div>'; echo '<div style="padding: 5px; font-size: 10px; display: none;">'; self::printArray($e->getTrace()); echo '</div>'; Modified: trunk/framework/Bee/MVC/Dispatcher.php =================================================================== --- trunk/framework/Bee/MVC/Dispatcher.php 2013-06-28 17:29:46 UTC (rev 43) +++ trunk/framework/Bee/MVC/Dispatcher.php 2013-07-01 11:25:52 UTC (rev 44) @@ -54,7 +54,12 @@ * * @var Bee_MVC_Dispatcher */ - private static $currentDispatcher; + private static $currentDispatcher; + + /** + * @var Bee_MVC_IHttpRequest + */ + private static $currentRequest; /** * The root context used by this dispatcher @@ -101,9 +106,15 @@ public static function get() { return self::$currentDispatcher; } - - + /** + * @return Bee_MVC_IHttpRequest + */ + public static function getCurrentRequest() { + return self::$currentRequest; + } + + /** * Allows to dispatch control to sub-controllers from within a current request. Intended to be used to include hierarchical structures * which must be also available as first-class handlers (e.g. for AJAX-based updates). * @@ -192,12 +203,12 @@ */ public function dispatch() { self::$currentDispatcher = $this; - $request = $this->buildRequestObject(); + self::$currentRequest = $this->buildRequestObject(); if(!is_null($this->filterChainProxy)) { - $this->filterChainProxy->doFilter($request, $this); + $this->filterChainProxy->doFilter(self::$currentRequest, $this); } else { - $this->doFilter($request); + $this->doFilter(self::$currentRequest); } // Bee_Cache_Manager::shutdown(); @@ -304,5 +315,4 @@ } self::includeDispatch(Bee_MVC_HttpRequest::constructRequest(MODEL::get(MODEL::CURRENT_REQUEST_KEY), $pathInfo, $params, $method)); } -} -?> \ No newline at end of file +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-06-28 17:29:49
|
Revision: 43 http://sourceforge.net/p/beeframework/code/43 Author: m_plomer Date: 2013-06-28 17:29:46 +0000 (Fri, 28 Jun 2013) Log Message: ----------- - removed proprietary parts from SF Removed Paths: ------------- trunk/examples/bootstrap.php trunk/examples/classes/Persistence/ trunk/examples/classes/Treetest/ trunk/examples/cli-config.php trunk/examples/composer.json trunk/examples/conf/ trunk/examples/index.php trunk/examples/index2.php trunk/framework/Bee/Persistence/Behaviors/ trunk/framework/Bee/Persistence/Doctrine/Behaviors/ trunk/framework/Bee/Persistence/Doctrine2/Behaviors/ trunk/framework/Bee/Persistence/Pdo/Behaviors/ trunk/tests/Bee/Persistence/Behaviors/ Deleted: trunk/examples/bootstrap.php =================================================================== --- trunk/examples/bootstrap.php 2013-06-28 14:49:43 UTC (rev 42) +++ trunk/examples/bootstrap.php 2013-06-28 17:29:46 UTC (rev 43) @@ -1,49 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * User: mp - * Date: 21.06.13 - * Time: 14:15 - */ - -unlink('db/examples.sqlite'); - -require_once '../framework/Bee/Framework.php'; -require_once 'vendor/autoload.php'; - -// Verzeichnis mit Applikations-Klassen zum Classpath hinzufügen -Bee_Framework::addApplicationIncludePath('classes'); - -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/helpers'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/pattern'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/layouts'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/appenders'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/configurators'); -Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/renderers'); - -Logger::configure('conf/log4php.xml'); - -$ctx = new Bee_Context_Xml('conf/context.xml'); - -$conn = $ctx->getBean('pdoConnection'); - -$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - -// obtaining the entity manager -$entityManager = $ctx->getBean('entityManager'); Deleted: trunk/examples/cli-config.php =================================================================== --- trunk/examples/cli-config.php 2013-06-28 14:49:43 UTC (rev 42) +++ trunk/examples/cli-config.php 2013-06-28 17:29:46 UTC (rev 43) @@ -1,26 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * User: mp - * Date: 21.06.13 - * Time: 14:40 - */ - -require_once "bootstrap.php"; - -$helperSet = $ctx->getBean('cliHelperSet'); Deleted: trunk/examples/composer.json =================================================================== --- trunk/examples/composer.json 2013-06-28 14:49:43 UTC (rev 42) +++ trunk/examples/composer.json 2013-06-28 17:29:46 UTC (rev 43) @@ -1,7 +0,0 @@ -{ - "require": { - "doctrine/orm": "~2.3@stable", - "doctrine/doctrine1": "~1.2@stable" - }, - "minimum-stability": "dev" -} \ No newline at end of file Deleted: trunk/examples/index.php =================================================================== --- trunk/examples/index.php 2013-06-28 14:49:43 UTC (rev 42) +++ trunk/examples/index.php 2013-06-28 17:29:46 UTC (rev 43) @@ -1,161 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * User: mp - * Date: 07.05.13 - * Time: 12:25 - */ - -require_once('bootstrap.php'); - -use Persistence\Pdo\SimpleHierarchyDao; -use Persistence\Pdo\OrderedColorsDao as OrderedColorsDaoPdo; -use Persistence\Doctrine\OrderedColorsDao as OrderedColorsDaoDoctrine; - -/* - * == EXAMPLE : Ordered Dao (PDO) ============================================= - */ -$dao = $ctx->getBean('orderedColorsDaoPdo'); - -$dao->createTable(); -$dao->deleteAllColors(); - -$redId = $dao->addColor('Red', '#ff0000', 1); -$greenId = $dao->addColor('Green', '#00ff00', 1); -$blueId = $dao->addColor('Blue', '#0000ff', 1); -$dao->addColor('Yellow', '#ffff00', 1); -$purpleId = $dao->addColor('Purple', '#ff00ff', 1); -$cyanId = $dao->addColor('Cyan', '#00ffff', 1); - -$redId2 = $dao->addColor('Red2', '#ff0000', 2); -$greenId2 = $dao->addColor('Green2', '#00ff00', 2); -$blueId2 = $dao->addColor('Blue2', '#0000ff', 2); -$yellowId2 = $dao->addColor('Yellow2', '#ffff00', 2); - -$dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($greenId, $purpleId) { - $dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($redId, $cyanId) { - $dao->getOrderedStrategy()->moveAfter($redId, $cyanId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($purpleId, $redId) { - $dao->getOrderedStrategy()->moveBefore($purpleId, $redId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($blueId) { - $dao->getOrderedStrategy()->remove($blueId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($redId) { - $dao->getOrderedStrategy()->remove($redId); -}); - -/* - * == EXAMPLE : Ordered Dao (Doctrine) ============================================= - */ -$dao = $ctx->getBean('orderedColorsDaoDoctrine'); - -$dao->createTable(); -$dao->deleteAllColors(); - -$redId = $dao->addColor('Red', '#ff0000', 1); -$greenId = $dao->addColor('Green', '#00ff00', 1); -$blueId = $dao->addColor('Blue', '#0000ff', 1); -$dao->addColor('Yellow', '#ffff00', 1); -$purpleId = $dao->addColor('Purple', '#ff00ff', 1); -$cyanId = $dao->addColor('Cyan', '#00ffff', 1); - -$redId2 = $dao->addColor('Red2', '#ff0000', 2); -$greenId2 = $dao->addColor('Green2', '#00ff00', 2); -$blueId2 = $dao->addColor('Blue2', '#0000ff', 2); -$yellowId2 = $dao->addColor('Yellow2', '#ffff00', 2); - -$dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($greenId, $purpleId) { - $dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($redId, $cyanId) { - $dao->getOrderedStrategy()->moveAfter($redId, $cyanId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($purpleId, $redId) { - $dao->getOrderedStrategy()->moveBefore($purpleId, $redId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($blueId) { - $dao->getOrderedStrategy()->remove($blueId); -}); - -$dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($redId) { - $dao->getOrderedStrategy()->remove($redId); -}); - -/* - * == EXAMPLE : NestedSet Dao ============================================= - */ -$dao = $ctx->getBean('simpleHierarchyDao'); - -$dao->createTable(); -$dao->deleteAll(); - -$id1 = $dao->addEntry('Entry 1'); -$id2 = $dao->addEntry('Entry 2'); -$id3 = $dao->addEntry('Entry 3'); -$id4 = $dao->addEntry('Entry 4'); -$id5 = $dao->addEntry('Entry 5'); -$id6 = $dao->addEntry('Entry 6'); -$id7 = $dao->addEntry('Entry 7'); -$id8 = $dao->addEntry('Entry 8'); -$id9 = $dao->addEntry('Entry 9'); - - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id9, $id1) { - $dao->getNestedSetStrategy()->moveBefore($id9, $id1); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id5, $id4) { - $dao->getNestedSetStrategy()->moveAsFirstChild($id5, $id4); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id6, $id4) { - $dao->getNestedSetStrategy()->moveAsFirstChild($id6, $id4); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id8, $id6) { - $dao->getNestedSetStrategy()->moveAsLastChild($id8, $id6); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id1, $id8) { - $dao->getNestedSetStrategy()->moveAfter($id1, $id8); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id6) { - $dao->getNestedSetStrategy()->remove($id6); -}); - -$dao->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($id6, $id9) { - $dao->getNestedSetStrategy()->moveAsLastChild($id6, $id9); -}); - -/* - * == END OF EXAMPLES ============================================= - */ - -echo 'DONE<hr/>'; Deleted: trunk/examples/index2.php =================================================================== --- trunk/examples/index2.php 2013-06-28 14:49:43 UTC (rev 42) +++ trunk/examples/index2.php 2013-06-28 17:29:46 UTC (rev 43) @@ -1,83 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * User: mp - * Date: 21.06.13 - * Time: 14:17 - */ - -use Treetest\Node; -use Bee\Persistence\Behaviors\NestedSet\ITreeNode; - -require_once('bootstrap.php'); - -function addChild(ITreeNode $parent, Node $node) { - global $entityManager; - $entityManager->persist($node); - $parent->appendChild($node); -} - -$treeDao = $ctx->getBean('treeDao', 'Treetest\TreeDao'); - -$root = new Node('Root Node', 15); -$entityManager->persist($root); - -addChild($root, new Node('Child 1-1')); -addChild($root, new Node('Child 1-2')); - -$child13 = new Node('Child 1-3'); -addChild($root, $child13); - -addChild($child13, new Node('Child 1-3-1')); -addChild($child13, new Node('Child 1-3-2')); - -$treeDao->getNestedSetStrategy()->saveStructure($root); - -$entityManager->flush(); -$entityManager->close(); - -//exit(); - - -// new EM instance -$entityManager = $ctx->getBean('entityManager'); - -$c12 = $entityManager->getRepository('Treetest\Node')->findOneBy(array('name' => 'Child 1-2')); - -addChild($c12, new Node('Child 1-2-1')); -addChild($c12, new Node('Child 1-2-2')); - -$treeDao->getNestedSetStrategy()->saveStructure($c12); -$entityManager->flush(); -$entityManager->close(); - -//exit(); - -// new EM instance -$entityManager = $ctx->getBean('entityManager'); -//$entityManager = new \Doctrine\ORM\EntityManager(); - -$c12 = $entityManager->getRepository('Treetest\Node')->findOneBy(array('name' => 'Child 1-2')); - -$treeDao->getNestedSetStrategy()->saveStructure($c12); - -$entityManager->flush(); -$entityManager->close(); - -var_dump($treeDao->loadTree($root)); - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-06-28 14:49:47
|
Revision: 42 http://sourceforge.net/p/beeframework/code/42 Author: m_plomer Date: 2013-06-28 14:49:43 +0000 (Fri, 28 Jun 2013) Log Message: ----------- - Tree-based API of nested set behavior completed Modified Paths: -------------- trunk/examples/classes/Treetest/Node.php trunk/examples/classes/Treetest/TreeDao.php trunk/examples/index2.php trunk/framework/Bee/Persistence/Behaviors/NestedSet/IDelegate.php trunk/framework/Bee/Persistence/Behaviors/NestedSet/ITreeNode.php trunk/framework/Bee/Persistence/Behaviors/NestedSet/NodeInfo.php trunk/framework/Bee/Persistence/Behaviors/NestedSet/Strategy.php trunk/framework/Bee/Persistence/Behaviors/NestedSet/TreeStrategy.php trunk/framework/Bee/Persistence/Doctrine2/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Doctrine2/Behaviors/GenericNestedSetDelegate.php trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php trunk/tests/Bee/Persistence/Behaviors/NestedSet/DelegateMock.php trunk/tests/Bee/Persistence/Behaviors/NestedSet/TestTreeNode.php Modified: trunk/examples/classes/Treetest/Node.php =================================================================== --- trunk/examples/classes/Treetest/Node.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/examples/classes/Treetest/Node.php 2013-06-28 14:49:43 UTC (rev 42) @@ -25,11 +25,7 @@ * * @Entity * @Table( - * name="tree_test", - * uniqueConstraints={ - * @UniqueConstraint(name="grp_lft", columns={"root_id", "lft"}), - * @UniqueConstraint(name="grp_rgt", columns={"root_id", "rgt"}) - * } + * name="tree_test" * ) */ class Node implements ITreeNode { @@ -50,7 +46,7 @@ /** * @var int - * @Column(name="root_id", type="integer", nullable=false) + * @Column(name="root_id", type="integer", nullable=true) */ private $rootId; @@ -84,9 +80,11 @@ /** * @param $name string + * @param null $rootId */ - public function __construct($name) { + public function __construct($name, $rootId = null) { $this->name = $name; + $this->rootId = $rootId; } /** @@ -166,18 +164,18 @@ return $this->rootId; } - /** - * @return ITreeNode + * @return ITreeNode[] */ - public function getParent() { - return $this->parent; + public function getChildren() { + return $this->children; } /** - * @return ITreeNode[] + * @param ITreeNode $child + * @return void */ - public function &getChildren() { - return $this->children; + public function appendChild(ITreeNode $child) { + array_push($this->children, $child); } } Modified: trunk/examples/classes/Treetest/TreeDao.php =================================================================== --- trunk/examples/classes/Treetest/TreeDao.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/examples/classes/Treetest/TreeDao.php 2013-06-28 14:49:43 UTC (rev 42) @@ -28,15 +28,22 @@ class TreeDao extends DaoBase { + const ENTITY_CLASS_NAME = 'Treetest\Node'; + /** * @var NestedSetStrategy */ private $nestedSetStrategy; + /** + * @var GenericNestedSetDelegate + */ + private $nestedSetDelegate; + public function __construct(EntityManager $entityManager) { - $delagate = new GenericNestedSetDelegate($entityManager, 'Treetest\Node'); -// $delagate->setGroupFieldName('root_id'); - $this->nestedSetStrategy = new NestedSetStrategy($delagate); + $this->setEntityManager($entityManager); + $this->nestedSetDelegate = new GenericNestedSetDelegate($entityManager, self::ENTITY_CLASS_NAME); + $this->nestedSetStrategy = new NestedSetStrategy($this->nestedSetDelegate); } /** @@ -45,4 +52,22 @@ public function getNestedSetStrategy() { return $this->nestedSetStrategy; } + + public function loadTree($rootNodeIdOrEntity) { + if(!$rootNodeIdOrEntity instanceof Node) { + $rootNodeIdOrEntity = $this->getEntityManager()->find(self::ENTITY_CLASS_NAME, $rootNodeIdOrEntity); + } + + // obtain NodeInfo (left / right boundaries + group info) for the tree part rooted at given node + $rootNodeInfo = $this->nestedSetDelegate->getNodeInfo($rootNodeIdOrEntity); + + // construct our base query + $qb = $this->getEntityManager()->createQueryBuilder()->select('e')->from(self::ENTITY_CLASS_NAME, 'e'); + + // augment query with subtree limits + $this->nestedSetDelegate->augmentQueryWithSubtreeLimits($qb, $rootNodeInfo); + + // execute query and create tree structure from result + return $this->nestedSetStrategy->buildTreeStructure($qb->getQuery()->execute()); + } } Modified: trunk/examples/index2.php =================================================================== --- trunk/examples/index2.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/examples/index2.php 2013-06-28 14:49:43 UTC (rev 42) @@ -22,54 +22,62 @@ */ use Treetest\Node; +use Bee\Persistence\Behaviors\NestedSet\ITreeNode; require_once('bootstrap.php'); -function addChild(&$children, Node $node) { +function addChild(ITreeNode $parent, Node $node) { global $entityManager; $entityManager->persist($node); - array_push($children, $node); + $parent->appendChild($node); } -$root = new Node('Root Node'); +$treeDao = $ctx->getBean('treeDao', 'Treetest\TreeDao'); + +$root = new Node('Root Node', 15); $entityManager->persist($root); -addChild($root->getChildren(), new Node('Child 1-1')); -addChild($root->getChildren(), new Node('Child 1-2')); +addChild($root, new Node('Child 1-1')); +addChild($root, new Node('Child 1-2')); $child13 = new Node('Child 1-3'); -addChild($root->getChildren(), $child13); +addChild($root, $child13); -addChild($child13->getChildren(), new Node('Child 1-3-1')); -addChild($child13->getChildren(), new Node('Child 1-3-2')); +addChild($child13, new Node('Child 1-3-1')); +addChild($child13, new Node('Child 1-3-2')); -$treeDao = $ctx->getBean('treeDao', 'Treetest\TreeDao'); - $treeDao->getNestedSetStrategy()->saveStructure($root); $entityManager->flush(); $entityManager->close(); +//exit(); + + // new EM instance $entityManager = $ctx->getBean('entityManager'); $c12 = $entityManager->getRepository('Treetest\Node')->findOneBy(array('name' => 'Child 1-2')); -addChild($c12->getChildren(), new Node('Child 1-2-1')); -addChild($c12->getChildren(), new Node('Child 1-2-2')); +addChild($c12, new Node('Child 1-2-1')); +addChild($c12, new Node('Child 1-2-2')); $treeDao->getNestedSetStrategy()->saveStructure($c12); $entityManager->flush(); $entityManager->close(); +//exit(); + // new EM instance $entityManager = $ctx->getBean('entityManager'); +//$entityManager = new \Doctrine\ORM\EntityManager(); + $c12 = $entityManager->getRepository('Treetest\Node')->findOneBy(array('name' => 'Child 1-2')); -//array_pop($c12->getChildren()); +$treeDao->getNestedSetStrategy()->saveStructure($c12); -$treeDao->getNestedSetStrategy()->saveStructure($c12); $entityManager->flush(); $entityManager->close(); +var_dump($treeDao->loadTree($root)); Modified: trunk/framework/Bee/Persistence/Behaviors/NestedSet/IDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/NestedSet/IDelegate.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Behaviors/NestedSet/IDelegate.php 2013-06-28 14:49:43 UTC (rev 42) @@ -44,17 +44,23 @@ * @param NodeInfo $nodeInfo * @param bool|int $newLft * @param bool|int $newLvl - * @param mixed $restriction - * @return + * @return void */ - public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false, $restriction = false); + public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false); /** + * @param NodeInfo $parentNodeInfo + * @return void + */ + public function unsetChildGroupKeys(NodeInfo $parentNodeInfo); + + /** * @param mixed $nestedSetEntity * @param int $delta * @param int $lowerBoundIncl * @param int $upperBoundExcl - * @param mixed $restriction + * @param array $groupKey + * @return void */ - public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction = false); + public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, array $groupKey); } Modified: trunk/framework/Bee/Persistence/Behaviors/NestedSet/ITreeNode.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/NestedSet/ITreeNode.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Behaviors/NestedSet/ITreeNode.php 2013-06-28 14:49:43 UTC (rev 42) @@ -25,12 +25,13 @@ interface ITreeNode { /** - * @return ITreeNode + * @return ITreeNode[] */ - public function getParent(); + public function getChildren(); /** - * @return ITreeNode[] + * @param ITreeNode $child + * @return void */ - public function getChildren(); + public function appendChild(ITreeNode $child); } Modified: trunk/framework/Bee/Persistence/Behaviors/NestedSet/NodeInfo.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/NestedSet/NodeInfo.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Behaviors/NestedSet/NodeInfo.php 2013-06-28 14:49:43 UTC (rev 42) @@ -21,7 +21,6 @@ * Date: 07.05.13 * Time: 17:43 */ - class NodeInfo { const LEFT_KEY = 'lft'; @@ -43,6 +42,11 @@ */ public $lvl; + /** + * @var array + */ + public $groupKey; + public function __construct(array $tuple = null) { if(!is_null($tuple)) { $this->lft = is_numeric($tuple[self::LEFT_KEY]) ? $tuple[self::LEFT_KEY] : false; @@ -97,9 +101,21 @@ return $this->rgt > 0 && $this->lft > 0; } - function __toString() { - return "NodeInfo(lft:{$this->lft}|rgt:{$this->rgt}|lvl:{$this->lvl})"; + /** + * @return array + */ + public function getGroupKey() { + return $this->groupKey; } + /** + * @param array $groupKey + */ + public function setGroupKey($groupKey) { + $this->groupKey = $groupKey; + } + function __toString() { + return "NodeInfo(lft:{$this->lft}|rgt:{$this->rgt}|lvl:{$this->lvl}|group:[".implode(',', $this->groupKey)."])"; + } } Modified: trunk/framework/Bee/Persistence/Behaviors/NestedSet/Strategy.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/NestedSet/Strategy.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Behaviors/NestedSet/Strategy.php 2013-06-28 14:49:43 UTC (rev 42) @@ -178,7 +178,7 @@ if ($subjectInfo->isInTree()) { // ... temporarily move it to a neutral position, so as to avoid any conflicts (e.g. SQL constraints) // (keep its original level for now) - $this->delegate->setPosition($subject, $subjectInfo, -$subjectInfo->getSpan(), $subjectInfo->lvl, $groupRestriction); + $this->delegate->setPosition($subject, $subjectInfo, -$subjectInfo->getSpan(), $subjectInfo->lvl); $subjectInfo->update(-$subjectInfo->getSpan(), $subjectInfo->lvl); } @@ -189,7 +189,7 @@ self::getLog()->debug("setting final position of subject to lft = $newLeft, lvl = $level"); // move subject to final position - $this->delegate->setPosition($subject, $subjectInfo, $newLeft, $level, $groupRestriction); + $this->delegate->setPosition($subject, $subjectInfo, $newLeft, $level); $subjectInfo->update($newLeft, $level); } @@ -210,10 +210,10 @@ } // store the subtree in the negative area (in case we do not want to delete it, but rather move it to a different tree) - $this->delegate->setPosition($subject, $subjectInfo, -$subjectInfo->getSpan(), 0, $groupRestriction); + $this->delegate->setPosition($subject, $subjectInfo, -$subjectInfo->getSpan(), 0); // restore numbering consistency - $this->delegate->shift($subject, -$subjectInfo->getSpan(), $subjectInfo->rgt + 1, false, $groupRestriction); + $this->delegate->shift($subject, -$subjectInfo->getSpan(), $subjectInfo->rgt + 1, false, $subjectInfo->getGroupKey()); } /** Modified: trunk/framework/Bee/Persistence/Behaviors/NestedSet/TreeStrategy.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/NestedSet/TreeStrategy.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Behaviors/NestedSet/TreeStrategy.php 2013-06-28 14:49:43 UTC (rev 42) @@ -44,12 +44,13 @@ public function saveStructure(ITreeNode $structureRoot) { $rootNodeInfo = $this->nodeInfoCache->contains($structureRoot) ? $this->nodeInfoCache->offsetGet($structureRoot) : $this->delegate->getNodeInfo($structureRoot); + $this->delegate->unsetChildGroupKeys($rootNodeInfo); $oldNext = $rootNodeInfo->rgt + 1; - $next = $this->calculateNodeInfo($structureRoot, $rootNodeInfo->lft, $rootNodeInfo->lvl); + $next = $this->calculateNodeInfo($structureRoot, $rootNodeInfo->lft, $rootNodeInfo->lvl, $rootNodeInfo->getGroupKey()); $delta = $next - $oldNext; - $this->delegate->shift($structureRoot, $delta, $oldNext, false); + $this->delegate->shift($structureRoot, $delta, $oldNext, false, $rootNodeInfo->getGroupKey()); $myDelegate = $this->delegate; $this->walkTree($structureRoot, function(ITreeNode $currentNode, NodeInfo $nodeInfo) use ($myDelegate) { @@ -57,6 +58,11 @@ }); } + /** + * Walk the tree under $structureRoot iteratively in preorder and apply the given lambda $func to each node. + * @param ITreeNode $structureRoot + * @param $func + */ protected function walkTree(ITreeNode $structureRoot, $func) { $stack = array($structureRoot); while(count($stack) > 0) { @@ -72,9 +78,10 @@ * @param ITreeNode $currentNode * @param $lft * @param $lvl + * @param array $groupKey * @return mixed */ - protected function calculateNodeInfo(ITreeNode $currentNode, $lft, $lvl) { + protected function calculateNodeInfo(ITreeNode $currentNode, $lft, $lvl, array $groupKey) { $nodeInfo = new NodeInfo(); $this->nodeInfoCache->attach($currentNode, $nodeInfo); @@ -82,9 +89,10 @@ $nodeInfo->lft = $lft; $lft++; foreach($currentNode->getChildren() as $child) { - $lft = $this->calculateNodeInfo($child, $lft, $lvl + 1); + $lft = $this->calculateNodeInfo($child, $lft, $lvl + 1, $groupKey); } $nodeInfo->rgt = $lft; + $nodeInfo->setGroupKey($groupKey); return $nodeInfo->rgt + 1; } @@ -95,4 +103,46 @@ protected function getNodeInfoCache() { return $this->nodeInfoCache; } + + /** + * @param ITreeNode[] $nodesList + * @return ITreeNode + */ + public function buildTreeStructure(array $nodesList) { + $nodeStack = new \SplStack(); + + $lastNode = null; + $lastLevel = false; + + foreach ($nodesList as $node) { + $level = $this->delegate->getNodeInfo($node)->lvl; + + if ($lastLevel !== false) { + if ($level > $lastLevel) { + // dive exactly one level + // must be exactly 1 larger than last level (otherwise intermediate nodes are probably missing) + \Bee_Utils_Assert::isTrue($level == $lastLevel + 1, sprintf('Malformed nodes list, missing intermediate levels between %d and %d', $lastLevel, $level)); + // use last node as current parent + $nodeStack->push($lastNode); + } else { + // $lastLevel >= $level; emerge one or multiple levels + for ($i = $lastLevel; $i > $level; $i--) { + $nodeStack->pop(); + } + } + + // add to current parent (which must exist!!) + \Bee_Utils_Assert::isTrue(!$nodeStack->isEmpty(), sprintf('No current parent on level %d (if this happens on level 0, it usually means that your query returned multiple roots for this tree set)', $level)); + + $nodeStack->top()->appendChild($node); + } + + $lastLevel = $level; + $lastNode = $node; + } + + return $nodeStack->bottom(); + } + + } Modified: trunk/framework/Bee/Persistence/Doctrine2/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/Behaviors/DelegateBase.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Doctrine2/Behaviors/DelegateBase.php 2013-06-28 14:49:43 UTC (rev 42) @@ -31,11 +31,18 @@ private $entityName; /** + * @var array + */ + private $groupKeyFields; + + /** * @param string $entityName + * @param array $groupKeyFields */ - public function __construct($entityName) { + public function __construct($entityName, array $groupKeyFields) { \Bee_Utils_Assert::hasText($entityName, 'Entity name required, must not be empty'); $this->entityName = $entityName; + $this->groupKeyFields = $groupKeyFields; } /** @@ -44,4 +51,11 @@ public function getEntityName() { return $this->entityName; } + + /** + * @return array + */ + public function getGroupKeyFields() { + return $this->groupKeyFields; + } } Modified: trunk/framework/Bee/Persistence/Doctrine2/Behaviors/GenericNestedSetDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/Behaviors/GenericNestedSetDelegate.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Doctrine2/Behaviors/GenericNestedSetDelegate.php 2013-06-28 14:49:43 UTC (rev 42) @@ -16,6 +16,7 @@ * limitations under the License. */ use Bee\Persistence\Behaviors\NestedSet\IDelegate; +use Bee\Persistence\Behaviors\NestedSet\ITreeNode; use Bee\Persistence\Behaviors\NestedSet\NodeInfo; use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; @@ -25,7 +26,7 @@ * Date: 21.06.13 * Time: 16:01 */ - + class GenericNestedSetDelegate extends DelegateBase implements IDelegate { /** @@ -46,13 +47,13 @@ /** * @param EntityManager $entityManager * @param string $entityName + * @param array $rootKeyFields */ - public function __construct(EntityManager $entityManager, $entityName) { - parent::__construct($entityName); + public function __construct(EntityManager $entityManager, $entityName, array $rootKeyFields = array('rootId')) { + parent::__construct($entityName, $rootKeyFields); $this->setEntityManager($entityManager); } - /** * @param string $leftFieldName */ @@ -85,14 +86,30 @@ $result->lft = $bw->getPropertyValue($this->leftFieldName); $result->rgt = $bw->getPropertyValue($this->rightFieldName); $result->lvl = $bw->getPropertyValue($this->levelFieldName); - if(is_null($result->lft)) { + if (is_null($result->lft)) { $result->lft = 1; $result->lvl = 0; } + $result->setGroupKey($this->extractGroupKey($bw)); return $result; } /** + * @param mixed|\Bee_Beans_BeanWrapper $nestedSetEntityOrBeanWrapper + * @return array + */ + protected function extractGroupKey($nestedSetEntityOrBeanWrapper) { + if (!($nestedSetEntityOrBeanWrapper instanceof \Bee_Beans_BeanWrapper)) { + $nestedSetEntityOrBeanWrapper = new \Bee_Beans_BeanWrapper($nestedSetEntityOrBeanWrapper); + } + $groupKey = array(); + foreach ($this->getGroupKeyFields() as $groupFieldName) { + $groupKey[$groupFieldName] = $nestedSetEntityOrBeanWrapper->getPropertyValue($groupFieldName); + } + return $groupKey; + } + + /** * @param mixed $nestedSetEntity * @param mixed $restriction * @return NodeInfo @@ -106,41 +123,106 @@ * @param NodeInfo $nodeInfo * @param bool|int $newLft * @param bool|int $newLvl - * @param mixed $restriction */ - public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false, $restriction = false) { + public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false) { $bw = new \Bee_Beans_BeanWrapper($nestedSetEntity); $bw->setPropertyValue($this->leftFieldName, $nodeInfo->lft); $bw->setPropertyValue($this->rightFieldName, $nodeInfo->rgt); $bw->setPropertyValue($this->levelFieldName, $nodeInfo->lvl); + + $grpKey = $nodeInfo->getGroupKey(); + foreach ($this->getGroupKeyFields() as $groupKeyField) { + $bw->setPropertyValue($groupKeyField, $grpKey[$groupKeyField]); + } // todo: implement the other cases (i.e. for the non-tree strategy API) } /** + * @param NodeInfo $parentNodeInfo + * @return void + */ + public function unsetChildGroupKeys(NodeInfo $parentNodeInfo) { + $qb = $this->createUpdateBaseQueryBuilder($parentNodeInfo->getGroupKey()); + + // set group key to null... + foreach ($this->getGroupKeyFields() as $groupKeyField) { + $qb->set("e.$groupKeyField", 'NULL'); + } + + // .. on all children of the parent node given by the NodeInfo + $qb->andWhere("e.{$this->leftFieldName} > :parentLft") + ->setParameter('parentLft', $parentNodeInfo->lft) + ->andWhere("e.{$this->rightFieldName} < :parentRgt") + ->setParameter('parentRgt', $parentNodeInfo->rgt); + $qb->getQuery()->execute(); + } + + /** * @param mixed $nestedSetEntity * @param int $delta * @param int $lowerBoundIncl * @param int $upperBoundExcl - * @param mixed $restriction + * @param array $groupKey */ - public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction = false) { - $this->buildShiftQuery($this->leftFieldName, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction)->execute(); - $this->buildShiftQuery($this->rightFieldName, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction)->execute(); + public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, array $groupKey) { + $this->buildShiftQuery($this->leftFieldName, $delta, $lowerBoundIncl, $upperBoundExcl, $groupKey)->execute(); + $this->buildShiftQuery($this->rightFieldName, $delta, $lowerBoundIncl, $upperBoundExcl, $groupKey)->execute(); // todo: implement the other cases (i.e. for the non-tree strategy API) } /** + * @param QueryBuilder $qb + * @param NodeInfo $rootNodeInfo + * @param string $rootEntityAlias + * @param bool $maxLvl + */ + public function augmentQueryWithSubtreeLimits(QueryBuilder $qb, NodeInfo $rootNodeInfo, $rootEntityAlias = 'e', $maxLvl = false) { + if ($rootEntityAlias) { + $rootEntityAlias = $rootEntityAlias . '.'; + } + + // limit to subtree of this root node + $qb->andWhere("$rootEntityAlias{$this->leftFieldName} >= :limitLft") + ->setParameter('limitLft', $rootNodeInfo->lft) + ->andWhere("$rootEntityAlias{$this->rightFieldName} <= :limitRgt") + ->setParameter('limitRgt', $rootNodeInfo->rgt); + + // make sure we get only results from current group + $this->augmentQueryWithGroupLimits($qb, $rootNodeInfo->getGroupKey()); + + // apply max level restriction if needed + if ($maxLvl) { + $qb->andWhere("$rootEntityAlias{$this->leftFieldName} <= :maxLvl")->setParameter('maxLvl', $maxLvl); + } + + // proper ordering + $qb->orderBy("$rootEntityAlias{$this->leftFieldName}", 'ASC'); + } + + /** * @param string $fieldName * @param int $delta * @param int $lowerBoundIncl * @param int $upperBoundExcl - * @param mixed $restriction + * @param array $groupKey * @return \Doctrine\ORM\Query */ - protected function buildShiftQuery($fieldName, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction = false) { - return $this->getEntityManager()->createQueryBuilder()->update($this->getEntityName(), 'e') - ->set('e.'.$fieldName, 'e.'.$fieldName .' + :delta')->setParameter('delta', $delta) - ->where('e.'.$fieldName . ' >= :lbIncl')->setParameter('lbIncl', $lowerBoundIncl)->getQuery(); -// ->orderBy('e.'.$fieldName, $delta > 0 ? 'DESC' : 'ASC')->getQuery(); + protected function buildShiftQuery($fieldName, $delta, $lowerBoundIncl, $upperBoundExcl, array $groupKey) { + $qb = $this->createUpdateBaseQueryBuilder($groupKey); + $qb->set("e.$fieldName", "e.$fieldName + :delta")->setParameter('delta', $delta) + ->andWhere("e.$fieldName >= :lbIncl")->setParameter('lbIncl', $lowerBoundIncl); + return $qb->getQuery(); } + + protected function createUpdateBaseQueryBuilder(array $groupKey) { + $qb = $this->getEntityManager()->createQueryBuilder()->update($this->getEntityName(), 'e'); + return $this->augmentQueryWithGroupLimits($qb, $groupKey); + } + + protected function augmentQueryWithGroupLimits(QueryBuilder $qb, array $groupKey) { + foreach ($this->getGroupKeyFields() as $groupFieldName) { + $qb->andWhere("e.$groupFieldName = :$groupFieldName")->setParameter($groupFieldName, $groupKey[$groupFieldName]); + } + return $qb; + } } Modified: trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php 2013-06-28 14:49:43 UTC (rev 42) @@ -46,7 +46,7 @@ * @return void */ public function startQuery($sql, array $params = null, array $types = null) { - self::getLog()->trace('SQL : [' . $sql . '] PARAMS : [' . serialize($params) . '] TYPES: ['. serialize($types) . ']'); + self::getLog()->trace('SQL : [' . $sql . '] PARAMS : [' . implode(', ', $params) . '] TYPES: ['. implode(', ', $types) . ']'); $this->startTime = microtime(true); } Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-06-28 14:49:43 UTC (rev 42) @@ -79,9 +79,10 @@ * @param bool $restriction * @return string */ - protected function getDomainRestrictionString($entity, array &$params, $restriction = false) { + protected function getDomainRestrictionString($entity, array &$params, array $groupKey = array()) { $result = '1=1'; if ($this->getGroupFieldName()) { + //todo: fix this! if ($restriction === false) { // determine group value $restriction = $this->getGroup($entity); Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php 2013-06-28 14:49:43 UTC (rev 42) @@ -102,21 +102,20 @@ /** * @param mixed $nestedSetEntity * @param NodeInfo $nodeInfo - * @param int $newLft - * @param int $newLvl - * @param mixed $restriction + * @param bool|int $newLft + * @param bool|int $newLvl */ - public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false, $restriction = false) { + public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false) { if ($nodeInfo->hasStructure()) { $params = array(':pos_delta' => $newLft - $nodeInfo->lft, ':lvl_delta' => $newLvl - $nodeInfo->lvl, ':lft' => $nodeInfo->lft, ':rgt' => $nodeInfo->rgt); $qryString = sprintf(self::SET_POSITION_QUERY_TEMPLATE, $this->leftFieldName, $this->rightFieldName, $this->levelFieldName, - $this->getQueryDomain(), $this->getDomainRestrictionString($nestedSetEntity, $params, $restriction)); + $this->getQueryDomain(), $this->getDomainRestrictionString($nestedSetEntity, $params, $nodeInfo->getGroupKey())); } else { $params = array(':lft' => $newLft, ':rgt' => $newLft + $nodeInfo->getSpan() - 1, ':lvl' => $newLvl); $qryString = sprintf(self::SET_POSITION_QUERY_BY_ID_TEMPLATE, $this->leftFieldName, $this->rightFieldName, $this->levelFieldName, $this->getQueryDomain(), $this->getIdentityRestrictionString($nestedSetEntity, $params), - $this->getDomainRestrictionString($nestedSetEntity, $params, $restriction)); + $this->getDomainRestrictionString($nestedSetEntity, $params, $nodeInfo->getGroupKey())); } $this->getPdo()->prepare($qryString)->execute($params); } @@ -126,9 +125,9 @@ * @param int $delta * @param int $lowerBoundIncl * @param int $upperBoundExcl - * @param mixed $restriction + * @param array $groupKey */ - public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction = false) { + public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, array $groupKey) { $params = array(':delta' => $delta, ':lower_bound' => $lowerBoundIncl); if ($upperBoundExcl !== false) { $params[':upper_bound'] = $upperBoundExcl; @@ -136,7 +135,7 @@ $qryTempl = $upperBoundExcl !== false ? self::SHIFT_QUERY_TEMPLATE : self::SHIFT_QUERY_OPEN_TEMPLATE; $qryDomain = $this->getQueryDomain(); - $domRes = $this->getDomainRestrictionString($nestedSetEntity, $params, $restriction); + $domRes = $this->getDomainRestrictionString($nestedSetEntity, $params, $groupKey); // order updates only if supported by the driver and not operating on a joined relation $orderUpdate = $this->pdoSupportsFeature(FeatureDetector::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false; Modified: trunk/tests/Bee/Persistence/Behaviors/NestedSet/DelegateMock.php =================================================================== --- trunk/tests/Bee/Persistence/Behaviors/NestedSet/DelegateMock.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/tests/Bee/Persistence/Behaviors/NestedSet/DelegateMock.php 2013-06-28 14:49:43 UTC (rev 42) @@ -58,10 +58,9 @@ * @param NodeInfo $nodeInfo * @param bool|int $newLft * @param bool|int $newLvl - * @param mixed $restriction */ - public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false, $restriction = false) { - array_push($this->protocol, sprintf('id=%s; lft=%d; rgt=%d; lvl=%d;', $nestedSetEntity->getId(), $nodeInfo->lft, $nodeInfo->rgt, $nodeInfo->lvl)); + public function setPosition($nestedSetEntity, NodeInfo $nodeInfo, $newLft = false, $newLvl = false) { + array_push($this->protocol, sprintf('id=%s; lft=%d; rgt=%d; lvl=%d; grp=[%s]', $nestedSetEntity->getId(), $nodeInfo->lft, $nodeInfo->rgt, $nodeInfo->lvl, implode(',', $nodeInfo->getGroupKey()))); } /** @@ -69,9 +68,17 @@ * @param int $delta * @param int $lowerBoundIncl * @param int $upperBoundExcl - * @param mixed $restriction + * @param array $groupKey */ - public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, $restriction = false) { - array_push($this->protocol, sprintf('delta=%d; %d<=lft/rgt%s;', $delta, $lowerBoundIncl, $upperBoundExcl !== false ? '<'.$upperBoundExcl : '')); + public function shift($nestedSetEntity, $delta, $lowerBoundIncl, $upperBoundExcl, array $groupKey) { + array_push($this->protocol, sprintf('delta=%d; %d<=lft/rgt%s; grp=[%s]', $delta, $lowerBoundIncl, $upperBoundExcl !== false ? '<'.$upperBoundExcl : '', implode(',', $groupKey))); } + + /** + * @param NodeInfo $parentNodeInfo + * @return void + */ + public function unsetChildGroupKeys(NodeInfo $parentNodeInfo) { + // TODO: Implement unsetChildGroupKeys() method. + } } Modified: trunk/tests/Bee/Persistence/Behaviors/NestedSet/TestTreeNode.php =================================================================== --- trunk/tests/Bee/Persistence/Behaviors/NestedSet/TestTreeNode.php 2013-06-27 03:18:25 UTC (rev 41) +++ trunk/tests/Bee/Persistence/Behaviors/NestedSet/TestTreeNode.php 2013-06-28 14:49:43 UTC (rev 42) @@ -40,33 +40,18 @@ private $children; /** + * @param array $id * @param TestTreeNode[] $children * @param array $nodeInfo + * @return \Bee\Persistence\Behaviors\NestedSet\TestTreeNode */ public function __construct($id, $children, array $nodeInfo) { parent::__construct($nodeInfo); $this->id = $id; $this->children = $children; - foreach($this->children as $child) { - $child->setParent($this); - } } /** - * @return ITreeNode - */ - public function getParent() { - return $this->parent; - } - - /** - * @param \Bee\Persistence\Behaviors\NestedSet\ITreeNode $parent - */ - public function setParent($parent) { - $this->parent = $parent; - } - - /** * @return ITreeNode[] */ public function getChildren() { @@ -79,4 +64,12 @@ public function getId() { return $this->id; } + + /** + * @param ITreeNode $child + * @return void + */ + public function appendChild(ITreeNode $child) { + array_push($this->children, $child); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-06-25 11:44:14
|
Revision: 40 http://sourceforge.net/p/beeframework/code/40 Author: m_plomer Date: 2013-06-25 11:44:09 +0000 (Tue, 25 Jun 2013) Log Message: ----------- - updated Doctrine2 DaoBase - Doctrine2 Log4PHP implementation of SQLLogger - minor fix in Context\ParserDelegate Modified Paths: -------------- trunk/framework/Bee/Context/Xml/ParserDelegate.php trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php Added Paths: ----------- trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php Modified: trunk/framework/Bee/Context/Xml/ParserDelegate.php =================================================================== --- trunk/framework/Bee/Context/Xml/ParserDelegate.php 2013-06-12 14:14:12 UTC (rev 39) +++ trunk/framework/Bee/Context/Xml/ParserDelegate.php 2013-06-25 11:44:09 UTC (rev 40) @@ -462,7 +462,9 @@ if (!$this->isDefaultNamespace($ele->namespaceURI)) { // todo MP: why is this missing? prevents XMLs with e.g. nested <util:array/> elements from being parsed - return $this->parseNestedCustomElement($ele, $bd); +// return $this->parseNestedCustomElement($ele, $bd); +// return $this->parseCustomElement($ele, $bd); + throw new Bee_Context_BeanCreationException($bd->getBeanClassName(), 'Namespaced nested elements are currently not supported'); } else if (Bee_Utils_Dom::nodeNameEquals($ele, self::BEAN_ELEMENT)) { @@ -630,7 +632,8 @@ /** * Enter description here... * - * @param DOMElement $root + * @param DOMElement $ele + * @param Bee_Context_Config_IBeanDefinition $containingBd * @return Bee_Context_Config_IBeanDefinition */ public function parseCustomElement(DOMElement $ele, Bee_Context_Config_IBeanDefinition $containingBd = null) { Modified: trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php 2013-06-12 14:14:12 UTC (rev 39) +++ trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php 2013-06-25 11:44:09 UTC (rev 40) @@ -13,20 +13,133 @@ /** * @var EntityManager */ - private $em; + private $entityManager; /** - * @return EntityManager + * @return EntityManager $entityManager */ - public function getEm() { - return $this->em; + public function getEntityManager() { + return $this->entityManager; } /** - * @param EntityManager $em + * @param $entityManager EntityManager */ - public function setEm(EntityManager $em) { - $this->em = $em; + public function setEntityManager(EntityManager $entityManager) { + $this->entityManager = $entityManager; + } + + + + + /** + * @param \Doctrine\ORM\QueryBuilder $query + * @param \Bee_Persistence_IRestrictionHolder $restrictionHolder + * @param \Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder + * @param array $defaultOrderMapping + * + * @return array + */ + public function executeListQuery(\Doctrine\ORM\QueryBuilder $queryBuilder, \Bee_Persistence_IRestrictionHolder $restrictionHolder = null, \Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder = null, array $defaultOrderMapping) { + $this->applyFilterRestrictions($queryBuilder, $restrictionHolder); + $this->applyOrderAndLimit($queryBuilder, $orderAndLimitHolder, $defaultOrderMapping); + return $queryBuilder->getQuery()->execute(); + } + + /** + * @param \Doctrine\ORM\QueryBuilder $query + * @param \Bee_Persistence_IRestrictionHolder $restrictionHolder + */ + protected final function applyFilterRestrictions(\Doctrine\ORM\QueryBuilder &$queryBuilder, \Bee_Persistence_IRestrictionHolder $restrictionHolder = null) { + if (is_null($restrictionHolder)) { + return; + } + + if (!\Bee_Utils_Strings::hasText($restrictionHolder->getFilterString())) { + return; + } + + $filterTokens = \Bee_Utils_Strings::tokenizeToArray($restrictionHolder->getFilterString(), ' '); + foreach ($filterTokens as $no => $token) { + $andWhereString = ''; + $params = array(); + + foreach ($restrictionHolder->getFilterableFields() as $fieldName) { + // $fieldName MUST BE A DOCTRINE NAME + if (\Bee_Utils_Strings::hasText($andWhereString)) { + $andWhereString .= ' OR '; + } + + $tokenName = 'filtertoken'.$no; + $andWhereString .= $fieldName.' LIKE :'.$tokenName; + $params[$tokenName] = '%'.$token.'%'; + } + + if (\Bee_Utils_Strings::hasText($andWhereString)) { + $queryBuilder->andWhere($andWhereString); + + foreach ($params as $key => $value) { + $queryBuilder->setParameter($key, $value); + } + } + } + } + + /** + * @param \Doctrine\ORM\QueryBuilder $query + * @param \Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder + * @param array $defaultOrderMapping + */ + protected final function applyOrderAndLimit(\Doctrine\ORM\QueryBuilder &$queryBuilder, \Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder = null, array $defaultOrderMapping = array()) { + if (is_null($orderAndLimitHolder)) { + $orderMapping = $defaultOrderMapping; + } else { + $orderMapping = count($orderAndLimitHolder->getOrderMapping()) > 0 ? $orderAndLimitHolder->getOrderMapping() : $defaultOrderMapping; + } + + foreach ($orderMapping as $orderField => $orderDir) { + $queryBuilder->addOrderBy($orderField, $orderDir); + } + + if (is_null($orderAndLimitHolder)) { + return; + } + + if ($orderAndLimitHolder->getPageSize() > 0) { + $queryBuilder->setMaxResults($orderAndLimitHolder->getPageSize()); + + // TODO: build a performant count-query! This is simply bullshit! + $pageCount = ceil(count($queryBuilder->getQuery()->execute()) / $orderAndLimitHolder->getPageSize()); + $orderAndLimitHolder->setPageCount($pageCount); + + if ($orderAndLimitHolder->getCurrentPage() > $pageCount) { + $orderAndLimitHolder->setCurrentPage($pageCount); + } + $queryBuilder->setFirstResult($orderAndLimitHolder->getCurrentPage() * $orderAndLimitHolder->getPageSize()); + $queryBuilder->setMaxResults($orderAndLimitHolder->getPageSize()); + } + } + + /** + * @param callback $func + * @throws \Exception + * @return mixed + */ + public function doInTransaction($func) { + $this->getDoctrineConnection()->beginTransaction(); + try { + $result = $func($this, self::getLog()); + + $this->getDoctrineConnection()->commit(); + $this->getDoctrineConnection()->flush(); + + return $result; + } catch(\Exception $e) { + self::getLog()->debug('exception caught', $e); + $this->getDoctrineConnection()->rollBack(); + throw $e; + } + } } Added: trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php (rev 0) +++ trunk/framework/Bee/Persistence/Doctrine2/Log4PHPLogger.php 2013-06-25 11:44:09 UTC (rev 40) @@ -0,0 +1,72 @@ +<?php +namespace Bee\Persistence\Doctrine2; + +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +use Doctrine\DBAL\Logging\SQLLogger; + +/** + * User: mp + * Date: 21.06.13 + * Time: 16:23 + * + * Implementation of the Doctrine 2 SQLLogger interface that logs to Log4PHP + */ +class Log4PHPLogger implements SQLLogger { + + /** + * @var \Logger + */ + private static $log; + + /** + * @var int + */ + private $startTime; + + /** + * Logs a SQL statement somewhere. + * + * @param string $sql The SQL to be executed. + * @param array $params The SQL parameters. + * @param array $types The SQL parameter types. + * @return void + */ + public function startQuery($sql, array $params = null, array $types = null) { + self::getLog()->trace('SQL : [' . $sql . '] PARAMS : [' . serialize($params) . '] TYPES: ['. serialize($types) . ']'); + $this->startTime = microtime(true); + } + + /** + * Mark the last started query as stopped. This can be used for timing of queries. + * + * @return void + */ + public function stopQuery() { + $dur = microtime(true) - $this->startTime; + self::getLog()->trace('.. completed in '. ($dur*1000) . ' ms'); + } + + /** + * @return \Logger + */ + protected static function getLog() { + if (!self::$log) { + self::$log = \Bee_Framework::getLoggerForClass(__CLASS__); + } + return self::$log; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-06-12 14:14:15
|
Revision: 39 http://sourceforge.net/p/beeframework/code/39 Author: m_plomer Date: 2013-06-12 14:14:12 +0000 (Wed, 12 Jun 2013) Log Message: ----------- - minor fixes Modified Paths: -------------- trunk/framework/Bee/Context/Xml/BeanDefinitionReader.php trunk/framework/Bee/Utils/Env.php Modified: trunk/framework/Bee/Context/Xml/BeanDefinitionReader.php =================================================================== --- trunk/framework/Bee/Context/Xml/BeanDefinitionReader.php 2013-06-06 14:40:44 UTC (rev 38) +++ trunk/framework/Bee/Context/Xml/BeanDefinitionReader.php 2013-06-12 14:14:12 UTC (rev 39) @@ -63,7 +63,10 @@ try { $document = new DOMDocument(); $document->load($location); - $this->registerBeanDefinitions($document); + if (is_null($document->documentElement)) { + throw new Exception('Failed to load XML document: '.$location); + } + $this->registerBeanDefinitions($document); } catch (Exception $ex) { unset($this->resourcesBeingLoaded[$location]); throw $ex; Modified: trunk/framework/Bee/Utils/Env.php =================================================================== --- trunk/framework/Bee/Utils/Env.php 2013-06-06 14:40:44 UTC (rev 38) +++ trunk/framework/Bee/Utils/Env.php 2013-06-12 14:14:12 UTC (rev 39) @@ -23,25 +23,24 @@ */ class Bee_Utils_Env { - const PATH_INFO = 'PATH_INFO'; - const ORIG_PATH_INFO = 'ORIG_PATH_INFO'; + const PATH_INFO = 'PATH_INFO'; + const ORIG_PATH_INFO = 'ORIG_PATH_INFO'; - public static $USER_AGENTS = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko'); - + public static $USER_AGENTS = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko'); + private static $pathInfo; private static $absoluteBasePath; private static $basePath; private static $dispatcher; private static $applicationPath; private static $php_self; - /** - * @var Bee_Utils_UserAgent - */ - private static $userAgent; - - - /** + * @var Bee_Utils_UserAgent + */ + private static $userAgent; + + + /** * The basePath is the path to the root of the webserver. * It is likely to be extended by a customer-id or user- * name. @@ -50,14 +49,14 @@ */ public static final function getAbsoluteBasePath() { if (is_null(self::$absoluteBasePath)) { - self::$absoluteBasePath = self::getWebserverDocumentRoot().'/'; - $basePath = self::getBasePath(); + self::$absoluteBasePath = self::getWebserverDocumentRoot() . '/'; + $basePath = self::getBasePath(); - if (Bee_Utils_Strings::hasText(self::$absoluteBasePath) && Bee_Utils_Strings::hasText($basePath) && !preg_match('#'.DIRECTORY_SEPARATOR.'$#i', self::$absoluteBasePath) && !preg_match('#^'.DIRECTORY_SEPARATOR.'#i', $basePath)) { - echo 'MUST ADD THE THING!!!!<br/>'; - self::$absoluteBasePath .= DIRECTORY_SEPARATOR; - } - self::$absoluteBasePath .= $basePath; + if (Bee_Utils_Strings::hasText(self::$absoluteBasePath) && Bee_Utils_Strings::hasText($basePath) && !preg_match('#' . DIRECTORY_SEPARATOR . '$#i', self::$absoluteBasePath) && !preg_match('#^' . DIRECTORY_SEPARATOR . '#i', $basePath)) { + echo 'MUST ADD THE THING!!!!<br/>'; + self::$absoluteBasePath .= DIRECTORY_SEPARATOR; + } + self::$absoluteBasePath .= $basePath; } return self::$absoluteBasePath; } @@ -72,18 +71,16 @@ public static final function getBasePath() { if (is_null(self::$basePath)) { self::$basePath = dirname(self::getPhpSelf()); - if (self::$basePath[0]==DIRECTORY_SEPARATOR) { + if (self::$basePath[0] == DIRECTORY_SEPARATOR) { self::$basePath = substr(self::$basePath, 1); } - if (self::$basePath==false) { + if (self::$basePath == false) { self::$basePath = ''; } } return self::$basePath; } - - /** * The applicationIndex is the .php file that will be the * entry page for the application @@ -92,31 +89,32 @@ */ public static final function getDispatcher() { if (is_null(self::$dispatcher)) { - self::$dispatcher = pathinfo(self::getPhpSelf(), PATHINFO_FILENAME).'.'.pathinfo(self::getPhpSelf(), PATHINFO_EXTENSION); + self::$dispatcher = pathinfo(self::getPhpSelf(), PATHINFO_FILENAME) . '.' . pathinfo(self::getPhpSelf(), PATHINFO_EXTENSION); } return self::$dispatcher; } - public static final function getApplicationIndex() { - return self::getDispatcher(); - } + public static final function getApplicationIndex() { + return self::getDispatcher(); + } - /** * The applicationPath is the path where the customized * application components and views lie. * + * @param bool $absolute * @return String */ - public static final function getApplicationPath() { + public static final function getApplicationPath($absolute = false) { if (is_null(self::$applicationPath)) { - self::$applicationPath = pathinfo(self::getPhpSelf(), PATHINFO_FILENAME); + self::$applicationPath = pathinfo(self::getPhpSelf(), PATHINFO_DIRNAME); } - return self::$applicationPath; + if (!$absolute) { + return self::$applicationPath; + } + return preg_replace('#' . DIRECTORY_SEPARATOR . '+#', DIRECTORY_SEPARATOR, self::getWebserverDocumentRoot() . DIRECTORY_SEPARATOR . self::$applicationPath); } - - /** * The webserverDocumentRoot is the path to the document * root directory of the webserver. @@ -127,8 +125,6 @@ return $_SERVER['DOCUMENT_ROOT']; } - - /** * The URL to the server * @@ -136,11 +132,11 @@ */ public static final function getProtocol() { $protocol = $_SERVER['HTTP_REFERER']; - $pos = strpos($protocol, '://'); - if ($pos===false) { - return 'http'; - } - return substr($protocol, 0, $pos); + $pos = strpos($protocol, '://'); + if ($pos === false) { + return 'http'; + } + return substr($protocol, 0, $pos); } /** @@ -163,7 +159,7 @@ // strip port number from host name (this should probably only be necessary when HTTP_HOST was used) $colPos = strpos($host, ':'); - if($colPos !== false) { + if ($colPos !== false) { $host = substr($host, 0, $colPos); } @@ -172,19 +168,18 @@ public static function getPhpSelf() { if (is_null(self::$php_self)) { - self::$php_self = substr($_SERVER["PHP_SELF"], 0, stripos($_SERVER["PHP_SELF"], '.php')+4); + self::$php_self = substr($_SERVER["PHP_SELF"], 0, stripos($_SERVER["PHP_SELF"], '.php') + 4); } return self::$php_self; } - - + /** - * Usage of this method is really discouraged, since + * Usage of this method is really discouraged, since * * @return String */ public static function getHtmlBase() { - $base = 'http://'; + $base = 'http://'; $base .= self::getHost(); $base .= '/'; try { @@ -195,8 +190,8 @@ } return $base; } - - + + /** * Returns the PATH_INFO (i.e. any additional path trailing the actual PHP file) * @@ -206,102 +201,101 @@ /** * Original code: * $pathInfo = $_SERVER['PATH_INFO']; - * - * + * + * * On some servers "PATH_INFO" is set in $_SERVER['ORIG_PATH_INFO']. If there is no * extra path set, $_SERVER['ORIG_PATH_INFO'] will contain the script name, which - * is also set in $_SERVER['ORIG_SCRIPT_NAME'] or $_SERVER['SCRIPT_NAME']. + * is also set in $_SERVER['ORIG_SCRIPT_NAME'] or $_SERVER['SCRIPT_NAME']. */ if (is_null(self::$pathInfo)) { - $pathInfo = array_key_exists(self::PATH_INFO, $_SERVER) ? $_SERVER[self::PATH_INFO] : null; - if(Bee_Utils_Strings::hasText($pathInfo)) { + $pathInfo = array_key_exists(self::PATH_INFO, $_SERVER) ? $_SERVER[self::PATH_INFO] : null; + if (Bee_Utils_Strings::hasText($pathInfo)) { self::$pathInfo = $pathInfo; - + } else { - $pathInfo = array_key_exists(self::ORIG_PATH_INFO, $_SERVER) ? $_SERVER[self::ORIG_PATH_INFO] : null; - if(Bee_Utils_Strings::hasText($pathInfo)) { - if ($pathInfo == $_SERVER['ORIG_SCRIPT_NAME']) { - return ''; - } - if ($pathInfo == $_SERVER['SCRIPT_NAME']) { - return ''; - } - self::$pathInfo = $pathInfo; - } - } + $pathInfo = array_key_exists(self::ORIG_PATH_INFO, $_SERVER) ? $_SERVER[self::ORIG_PATH_INFO] : null; + if (Bee_Utils_Strings::hasText($pathInfo)) { + if ($pathInfo == $_SERVER['ORIG_SCRIPT_NAME']) { + return ''; + } + if ($pathInfo == $_SERVER['SCRIPT_NAME']) { + return ''; + } + self::$pathInfo = $pathInfo; + } + } } return self::$pathInfo; } - + public static function getRequestHeaders($uppercaseKeys = false) { - if(function_exists('apache_request_headers')) { + if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); } else { - $phpSupportedHeaders = array ( + $phpSupportedHeaders = array( 'HTTP_ACCEPT' => 'Accept', 'HTTP_ACCEPT_CHARSET' => 'Accept-Charset', 'HTTP_ACCEPT_ENCODING' => 'Accept-Encoding', - 'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language', - 'HTTP_CONNECTION' => 'Connection', - 'HTTP_HOST' => 'Host', - 'HTTP_REFERER' => 'Referer', - 'HTTP_USER_AGENT' => 'User-Agent' + 'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language', + 'HTTP_CONNECTION' => 'Connection', + 'HTTP_HOST' => 'Host', + 'HTTP_REFERER' => 'Referer', + 'HTTP_USER_AGENT' => 'User-Agent' ); $headers = array(); - foreach($phpSupportedHeaders as $key => $val) { - if(array_key_exists($key, $_SERVER)) { + foreach ($phpSupportedHeaders as $key => $val) { + if (array_key_exists($key, $_SERVER)) { $headers[$val] = $_SERVER[$key]; } } } - if($uppercaseKeys) { + if ($uppercaseKeys) { $headers = array_change_key_case($headers, CASE_UPPER); } return $headers; } - /** - * @static - * @return Bee_Utils_UserAgent - */ - public static function getUserAgent() { - if (!self::$userAgent) { - // Clean up agent and build regex that matches phrases for known browsers - // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor - // version numbers. E.g. "2.0.0.6" is parsed as simply "2.0" + /** + * @static + * @return Bee_Utils_UserAgent + */ + public static function getUserAgent() { + if (!self::$userAgent) { + // Clean up agent and build regex that matches phrases for known browsers + // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor + // version numbers. E.g. "2.0.0.6" is parsed as simply "2.0" - self::$userAgent = new Bee_Utils_UserAgent(); + self::$userAgent = new Bee_Utils_UserAgent(); - $userAgents = self::$USER_AGENTS; - $userAgents[] = 'version'; - $agent = ''; + $userAgents = self::$USER_AGENTS; + $userAgents[] = 'version'; + $agent = ''; - $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']); - $pattern = '#(?<browser>'.join('|', $userAgents).')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#'; + $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']); + $pattern = '#(?<browser>' . join('|', $userAgents) . ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#'; - // Find all phrases (or return empty array if none found) - if (!preg_match_all($pattern, $agent, $matches)) { - self::$userAgent->setName('unknown'); - self::$userAgent->setVersion(0); - } else { + // Find all phrases (or return empty array if none found) + if (!preg_match_all($pattern, $agent, $matches)) { + self::$userAgent->setName('unknown'); + self::$userAgent->setVersion(0); + } else { - // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase, - // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one - // in the UA). That's usually the most correct. - $i = count($matches['browser'])-1; + // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase, + // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one + // in the UA). That's usually the most correct. + $i = count($matches['browser']) - 1; - self::$userAgent->setName($matches['browser'][$i]); + self::$userAgent->setName($matches['browser'][$i]); - $version = $matches['version'][$i]; - if (in_array('version', $matches['browser'])) { - $version = $matches['version'][$i-1]; - } + $version = $matches['version'][$i]; + if (in_array('version', $matches['browser'])) { + $version = $matches['version'][$i - 1]; + } - self::$userAgent->setVersion($version); - } - } - return self::$userAgent; - } + self::$userAgent->setVersion($version); + } + } + return self::$userAgent; + } } -?> \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-06-06 14:40:46
|
Revision: 38 http://sourceforge.net/p/beeframework/code/38 Author: m_plomer Date: 2013-06-06 14:40:44 +0000 (Thu, 06 Jun 2013) Log Message: ----------- - merged changes from private AH version Modified Paths: -------------- trunk/framework/Bee/Security/PasswordEncoder/Crypt.php trunk/framework/Bee/Security/Provider/ISaltSource.php trunk/framework/Bee/Text/Normalization/PEARNormalizer.php Added Paths: ----------- trunk/framework/Bee/Security/Provider/UsernameSaltSource.php trunk/framework/BeeFramework.php Modified: trunk/framework/Bee/Security/PasswordEncoder/Crypt.php =================================================================== --- trunk/framework/Bee/Security/PasswordEncoder/Crypt.php 2013-05-21 14:20:15 UTC (rev 37) +++ trunk/framework/Bee/Security/PasswordEncoder/Crypt.php 2013-06-06 14:40:44 UTC (rev 38) @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + class Bee_Security_PasswordEncoder_Crypt implements Bee_Security_IPasswordEncoder { public function encodePassword($rawPass, $salt) { - return crypt($rawPass); + return crypt($rawPass, $salt); } public function isPasswordValid($encPass, $rawPass, $salt) { - return $encPass === crypt($rawPass); + return $encPass === $this->encodePassword($rawPass, $salt); } - } -?> \ No newline at end of file Modified: trunk/framework/Bee/Security/Provider/ISaltSource.php =================================================================== --- trunk/framework/Bee/Security/Provider/ISaltSource.php 2013-05-21 14:20:15 UTC (rev 37) +++ trunk/framework/Bee/Security/Provider/ISaltSource.php 2013-06-06 14:40:44 UTC (rev 38) @@ -26,5 +26,4 @@ * @return String the salt to use for this <code>Bee_Security_IUserDetails</code> */ public function getSalt(Bee_Security_IUserDetails $user); -} -?> \ No newline at end of file +} \ No newline at end of file Added: trunk/framework/Bee/Security/Provider/UsernameSaltSource.php =================================================================== --- trunk/framework/Bee/Security/Provider/UsernameSaltSource.php (rev 0) +++ trunk/framework/Bee/Security/Provider/UsernameSaltSource.php 2013-06-06 14:40:44 UTC (rev 38) @@ -0,0 +1,31 @@ +<?php +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides alternative sources of the salt to use for encoding passwords. + */ +class Bee_Security_Provider_UsernameSaltSource implements Bee_Security_Provider_ISaltSource { + /** + * Returns the salt to use for the indicated user. + * + * @param Bee_Security_IUserDetails $user from the <code>AuthenticationDao</code> + * @return String the salt to use for this <code>Bee_Security_IUserDetails</code> + */ + public function getSalt(Bee_Security_IUserDetails $user) { + return $user->getUsername(); + } +} \ No newline at end of file Modified: trunk/framework/Bee/Text/Normalization/PEARNormalizer.php =================================================================== --- trunk/framework/Bee/Text/Normalization/PEARNormalizer.php 2013-05-21 14:20:15 UTC (rev 37) +++ trunk/framework/Bee/Text/Normalization/PEARNormalizer.php 2013-06-06 14:40:44 UTC (rev 38) @@ -34,7 +34,7 @@ * @return string */ public function normalize($input, $form = self::UNICODE_NORMALIZATION_COMPOSED) { - $this->normalizer->normalize($input, $form); + return $this->normalizer->normalize($input, $form); } public function __construct() { Added: trunk/framework/BeeFramework.php =================================================================== --- trunk/framework/BeeFramework.php (rev 0) +++ trunk/framework/BeeFramework.php 2013-06-06 14:40:44 UTC (rev 38) @@ -0,0 +1,7 @@ +<?php + +include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'Bee'.DIRECTORY_SEPARATOR.'Framework.php'; + +class BeeFramework extends Bee_Framework { + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-21 14:20:18
|
Revision: 37 http://sourceforge.net/p/beeframework/code/37 Author: m_plomer Date: 2013-05-21 14:20:15 +0000 (Tue, 21 May 2013) Log Message: ----------- - updated ordered behavior with proper group handling Modified Paths: -------------- trunk/examples/classes/Persistence/Doctrine/OrderedColorsDao.php trunk/examples/classes/Persistence/Doctrine/OrderedColorsEntity.php trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php trunk/examples/classes/Persistence/Pdo/SimpleHierarchyDao.php trunk/examples/conf/context.xml trunk/examples/index.php trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php trunk/framework/Bee/Persistence/Doctrine/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Doctrine/Behaviors/GenericOrderedDelegate.php trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php trunk/framework/Bee/Persistence/Pdo/SimpleDaoBase.php Added Paths: ----------- trunk/framework/Bee/Persistence/Behaviors/AbstractFieldBasedDelegate.php Modified: trunk/examples/classes/Persistence/Doctrine/OrderedColorsDao.php =================================================================== --- trunk/examples/classes/Persistence/Doctrine/OrderedColorsDao.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/classes/Persistence/Doctrine/OrderedColorsDao.php 2013-05-21 14:20:15 UTC (rev 37) @@ -35,8 +35,9 @@ public function __construct(\Doctrine_Connection $conn) { $this->setDoctrineConnection($conn); - $pdoOrderedDelagate = new GenericOrderedDelegate(self::ENTITY_CLASS_NAME, $conn); - $this->orderedStrategy = new OrderedStrategy($pdoOrderedDelagate); + $delagate = new GenericOrderedDelegate(self::ENTITY_CLASS_NAME, $conn); + $delagate->setGroupFieldName('color_grp'); + $this->orderedStrategy = new OrderedStrategy($delagate); } /** @@ -57,19 +58,20 @@ }); } - public function addColor($colorName, $colorHex) { - self::getLog()->info("adding color ($colorName, $colorHex)"); - return $this->doInTransaction(function(OrderedColorsDao $dao, \Logger $log) use ($colorName, $colorHex) { + public function addColor($colorName, $colorHex, $grpId) { + self::getLog()->info("adding color ($colorName, $colorHex, $grpId)"); + return $this->doInTransaction(function(OrderedColorsDao $dao, \Logger $log) use ($colorName, $colorHex, $grpId) { $log->debug('inserting'); $entity = new OrderedColorsEntity(); $entity->setName($colorName); $entity->setHexValue($colorHex); + $entity->setColorGrp($grpId); $entity->save($dao->getDoctrineConnection()); $log->debug('moving to end of list'); $pos = $dao->getOrderedStrategy()->moveToEnd($entity); - $log->debug("committing ($entity->id, $colorName, $colorHex, $pos)"); + $log->debug("committing ($entity->id, $colorName, $colorHex, $grpId, $pos)"); return $entity; }); } Modified: trunk/examples/classes/Persistence/Doctrine/OrderedColorsEntity.php =================================================================== --- trunk/examples/classes/Persistence/Doctrine/OrderedColorsEntity.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/classes/Persistence/Doctrine/OrderedColorsEntity.php 2013-05-21 14:20:15 UTC (rev 37) @@ -1,20 +1,20 @@ <?php namespace Persistence\Doctrine; -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + /* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * User: mp @@ -31,46 +31,73 @@ $this->hasColumn('name', 'string', 255); $this->hasColumn('hex_value', 'string', 10); + $this->hasColumn('color_grp', 'int'); $this->hasColumn('pos', 'int'); + + $drvName = \Doctrine_Manager::connection()->getAttribute(\PDO::ATTR_DRIVER_NAME); + if($drvName == 'mysql') { + // sqlite does generally not support ordered updates + $this->index('grp_pos', array( + 'fields' => array( + 'color_grp', + 'pos' => array('sorting' => 'ASC') + ), + 'type' => 'unique', + )); + } } /** - * @param mixed $hexValue + * @param string $hexValue */ public function setHexValue($hexValue) { $this->hex_value = $hexValue; } /** - * @return mixed + * @return string */ public function getHexValue() { return $this->hex_value; } /** - * @param mixed $name + * @param string $name */ public function setName($name) { $this->name = $name; } /** - * @return mixed + * @return string */ public function getName() { return $this->name; } /** - * @param mixed $pos + * @param int $colorGrp */ + public function setColorGrp($colorGrp) { + $this->color_grp = $colorGrp; + } + + /** + * @return int + */ + public function getColorGrp() { + return $this->color_grp; + } + + /** + * @param int $pos + */ public function setPos($pos) { $this->pos = $pos; } /** - * @return mixed + * @return int */ public function getPos() { return $this->pos; Modified: trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php =================================================================== --- trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php 2013-05-21 14:20:15 UTC (rev 37) @@ -26,7 +26,7 @@ * Date: 07.05.13 * Time: 12:12 */ - + class OrderedColorsDao extends SimpleDaoBase { /** @@ -36,20 +36,39 @@ public function __construct(\PDO $pdoConnection) { parent::__construct($pdoConnection); - $pdoOrderedDelagate = new GenericOrderedDelegate('ordered_colors_pdo', $pdoConnection); - $this->orderedStrategy = new OrderedStrategy($pdoOrderedDelagate); + $delagate = new GenericOrderedDelegate('ordered_colors_pdo', $pdoConnection); + $delagate->setGroupFieldName('color_grp'); + $this->orderedStrategy = new OrderedStrategy($delagate); } /** * */ public function createTable() { - $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS "ordered_colors_pdo" ( - "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, - "name" text NOT NULL, - "hex_value" text NOT NULL, - "pos" integer DEFAULT NULL)' - ); + $drvName = $this->getPdoConnection()->getAttribute(\PDO::ATTR_DRIVER_NAME); + switch ($drvName) { + case 'mysql': + $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS `ordered_colors_pdo` ( + id bigint(20) NOT NULL AUTO_INCREMENT, + name varchar(255) NOT NULL, + hex_value varchar(7) NOT NULL, + color_grp int(11) NOT NULL, + pos int(11) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY grp_pos_idx (color_grp, pos)) + ENGINE=InnoDB CHARSET=utf8' + ); + break; + case 'sqlite': + $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS "ordered_colors_pdo" ( + "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" text NOT NULL, + "hex_value" text NOT NULL, + "color_grp" integer NOT NULL, + "pos" integer DEFAULT NULL)' + ); + break; + } } /** @@ -60,24 +79,24 @@ } public function deleteAllColors() { - $this->doInTransaction(function(OrderedColorsDao $dao, \Logger $log) { + $this->doInTransaction(function (OrderedColorsDao $dao, \Logger $log) { $log->debug('deleting all colors'); $dao->getPdoConnection()->exec('DELETE FROM ordered_colors_pdo'); }); } - public function addColor($colorName, $colorHex) { - self::getLog()->info("adding color ($colorName, $colorHex)"); - return $this->doInTransaction(function(OrderedColorsDao $dao, \Logger $log) use ($colorName, $colorHex) { + public function addColor($colorName, $colorHex, $grpId) { + self::getLog()->info("adding color ($colorName, $colorHex, $grpId)"); + return $this->doInTransaction(function (OrderedColorsDao $dao, \Logger $log) use ($colorName, $colorHex, $grpId) { $log->debug('inserting'); - $insertStmt = $dao->getPdoConnection()->prepare('INSERT INTO ordered_colors_pdo (name, hex_value) VALUES (:name, :hex_value)'); - $insertStmt->execute(array(':name' => $colorName, ':hex_value' => $colorHex)); + $insertStmt = $dao->getPdoConnection()->prepare('INSERT INTO ordered_colors_pdo (name, hex_value, color_grp) VALUES (:name, :hex_value, :grp_id)'); + $insertStmt->execute(array(':name' => $colorName, ':hex_value' => $colorHex, ':grp_id' => $grpId)); $id = $dao->getPdoConnection()->lastInsertId(); $log->debug('moving to end of list'); $pos = $dao->getOrderedStrategy()->moveToEnd($id); - $log->debug("committing ($id, $colorName, $colorHex, $pos)"); + $log->debug("committing ($id, $colorName, $colorHex, $grpId, $pos)"); return $id; }); Modified: trunk/examples/classes/Persistence/Pdo/SimpleHierarchyDao.php =================================================================== --- trunk/examples/classes/Persistence/Pdo/SimpleHierarchyDao.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/classes/Persistence/Pdo/SimpleHierarchyDao.php 2013-05-21 14:20:15 UTC (rev 37) @@ -35,27 +35,48 @@ public function __construct(\PDO $pdoConnection) { parent::__construct($pdoConnection); - $pdoNestedSetDelagate = new GenericNestedSetDelegate('simple_hierarchy', $pdoConnection); - $this->nestedSetStrategy = new NestedSetStrategy($pdoNestedSetDelagate); + $delagate = new GenericNestedSetDelegate('simple_hierarchy_pdo', $pdoConnection); + $delagate->setGroupFieldName('root_id'); + $this->nestedSetStrategy = new NestedSetStrategy($delagate); } /** * */ public function createTable() { - $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS "simple_hierarchy" ( - "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, - "name" text NOT NULL, - "lft" integer DEFAULT NULL, - "rgt" integer DEFAULT NULL, - "lvl" integer DEFAULT NULL)' - ); + $drvName = $this->getPdoConnection()->getAttribute(\PDO::ATTR_DRIVER_NAME); + switch ($drvName) { + case 'mysql': + $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS `simple_hierarchy_pdo` ( + id bigint(20) NOT NULL AUTO_INCREMENT, + name varchar(255) NOT NULL, + root_id int(11) NOT NULL, + lft int(11) DEFAULT NULL, + rgt int(11) DEFAULT NULL, + lvl int(11) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY grp_lft (root_id, lft), + UNIQUE KEY grp_rgt (root_id, rgt)) + ENGINE=InnoDB CHARSET=utf8' + ); + break; + case 'sqlite': + $this->getPdoConnection()->exec('CREATE TABLE IF NOT EXISTS "simple_hierarchy_pdo" ( + "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" text NOT NULL, + "root_id" integer NOT NULL, + "lft" integer DEFAULT NULL, + "rgt" integer DEFAULT NULL, + "lvl" integer DEFAULT NULL)' + ); + break; + } } public function deleteAll() { $this->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) { $log->debug('deleting all hierarchy entries'); - $dao->getPdoConnection()->exec('DELETE FROM simple_hierarchy'); + $dao->getPdoConnection()->exec('DELETE FROM simple_hierarchy_pdo'); }); } @@ -70,7 +91,7 @@ return $this->doInTransaction(function(SimpleHierarchyDao $dao, \Logger $log) use ($name) { $log->info("adding entry ($name)"); $log->debug('inserting'); - $insertStmt = $dao->getPdoConnection()->prepare('INSERT INTO simple_hierarchy (name) VALUES (:name)'); + $insertStmt = $dao->getPdoConnection()->prepare('INSERT INTO simple_hierarchy_pdo (name) VALUES (:name)'); $insertStmt->execute(array(':name' => $name)); $id = $dao->getPdoConnection()->lastInsertId(); Modified: trunk/examples/conf/context.xml =================================================================== --- trunk/examples/conf/context.xml 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/conf/context.xml 2013-05-21 14:20:15 UTC (rev 37) @@ -8,10 +8,10 @@ <!-- Persistence - PDO Connection --> <bean id="pdoConnection" class="PDO"> <!-- LOCAL DB --> - <constructor-arg index="0" value="sqlite:db/examples.sqlite" /> - <constructor-arg index="1" value="sa" /> - <!--<constructor-arg index="0" value="mysql:host=127.0.0.1;dbname=bee_test" />--> - <!--<constructor-arg index="1" value="root" />--> + <!--<constructor-arg index="0" value="sqlite:db/examples.sqlite" />--> + <!--<constructor-arg index="1" value="sa" />--> + <constructor-arg index="0" value="mysql:host=127.0.0.1;dbname=bee_test" /> + <constructor-arg index="1" value="root" /> <constructor-arg index="2" value="" /> </bean> Modified: trunk/examples/index.php =================================================================== --- trunk/examples/index.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/examples/index.php 2013-05-21 14:20:15 UTC (rev 37) @@ -24,6 +24,8 @@ * Time: 12:25 */ +unlink('db/examples.sqlite'); + require_once '../framework/Bee/Framework.php'; require_once 'vendor/autoload.php'; @@ -51,13 +53,18 @@ $dao->createTable(); $dao->deleteAllColors(); -$redId = $dao->addColor('Red', '#ff0000'); -$greenId = $dao->addColor('Green', '#00ff00'); -$blueId = $dao->addColor('Blue', '#0000ff'); -$dao->addColor('Yellow', '#ffff00'); -$purpleId = $dao->addColor('Purple', '#ff00ff'); -$cyanId = $dao->addColor('Cyan', '#00ffff'); +$redId = $dao->addColor('Red', '#ff0000', 1); +$greenId = $dao->addColor('Green', '#00ff00', 1); +$blueId = $dao->addColor('Blue', '#0000ff', 1); +$dao->addColor('Yellow', '#ffff00', 1); +$purpleId = $dao->addColor('Purple', '#ff00ff', 1); +$cyanId = $dao->addColor('Cyan', '#00ffff', 1); +$redId2 = $dao->addColor('Red2', '#ff0000', 2); +$greenId2 = $dao->addColor('Green2', '#00ff00', 2); +$blueId2 = $dao->addColor('Blue2', '#0000ff', 2); +$yellowId2 = $dao->addColor('Yellow2', '#ffff00', 2); + $dao->doInTransaction(function(OrderedColorsDaoPdo $dao, \Logger $log) use ($greenId, $purpleId) { $dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); }); @@ -86,13 +93,18 @@ $dao->createTable(); $dao->deleteAllColors(); -$redId = $dao->addColor('Red', '#ff0000'); -$greenId = $dao->addColor('Green', '#00ff00'); -$blueId = $dao->addColor('Blue', '#0000ff'); -$dao->addColor('Yellow', '#ffff00'); -$purpleId = $dao->addColor('Purple', '#ff00ff'); -$cyanId = $dao->addColor('Cyan', '#00ffff'); +$redId = $dao->addColor('Red', '#ff0000', 1); +$greenId = $dao->addColor('Green', '#00ff00', 1); +$blueId = $dao->addColor('Blue', '#0000ff', 1); +$dao->addColor('Yellow', '#ffff00', 1); +$purpleId = $dao->addColor('Purple', '#ff00ff', 1); +$cyanId = $dao->addColor('Cyan', '#00ffff', 1); +$redId2 = $dao->addColor('Red2', '#ff0000', 2); +$greenId2 = $dao->addColor('Green2', '#00ff00', 2); +$blueId2 = $dao->addColor('Blue2', '#0000ff', 2); +$yellowId2 = $dao->addColor('Yellow2', '#ffff00', 2); + $dao->doInTransaction(function(OrderedColorsDaoDoctrine $dao, \Logger $log) use ($greenId, $purpleId) { $dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); }); Added: trunk/framework/Bee/Persistence/Behaviors/AbstractFieldBasedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/AbstractFieldBasedDelegate.php (rev 0) +++ trunk/framework/Bee/Persistence/Behaviors/AbstractFieldBasedDelegate.php 2013-05-21 14:20:15 UTC (rev 37) @@ -0,0 +1,85 @@ +<?php +namespace Bee\Persistence\Behaviors; +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +use Bee\Persistence\Pdo\FeatureDetector; + +/** + * User: mp + * Date: 21.05.13 + * Time: 10:19 + */ + +abstract class AbstractFieldBasedDelegate { + + /** + * @var string + */ + private $idFieldName = 'id'; + + /** + * @var string + */ + private $groupFieldName; + + /** + * @var string + */ + private $queryDomain; + + /** + * @param string $queryDomain + */ + public function __construct($queryDomain) { + \Bee_Utils_Assert::hasText($queryDomain, 'Query domain (table / entity name) required, must not be empty'); + $this->queryDomain = $queryDomain; + } + + /** + * @param string $idFieldName + */ + public function setIdFieldName($idFieldName) { + $this->idFieldName = $idFieldName; + } + + /** + * @return string + */ + public function getIdFieldName() { + return $this->idFieldName; + } + + /** + * @param string $domainFieldName + */ + public function setGroupFieldName($domainFieldName) { + $this->groupFieldName = $domainFieldName; + } + + /** + * @return string + */ + public function getGroupFieldName() { + return $this->groupFieldName; + } + + /** + * @return string + */ + public function getQueryDomain() { + return $this->queryDomain; + } +} Modified: trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php 2013-05-21 14:20:15 UTC (rev 37) @@ -97,6 +97,7 @@ * @return int */ public function moveRelative($subject, $ref, $before = true, $groupRestriction = false) { + // determine previous position of subject $oldPos = $this->delegate->getPosition($subject, $groupRestriction); @@ -113,10 +114,10 @@ } } else { // no, "move behind nothing" means "move to beginning", "move before nothing" means "move to the end" - $newPos = 0; + $newPos = 1; if ($before) { $maxPos = $this->delegate->getMaxPosition($subject, $groupRestriction); - $newPos = $maxPos !== false ? $maxPos + 1 : 0; + $newPos = $maxPos !== false ? $maxPos + 1 : 1; } } Modified: trunk/framework/Bee/Persistence/Doctrine/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine/Behaviors/DelegateBase.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Doctrine/Behaviors/DelegateBase.php 2013-05-21 14:20:15 UTC (rev 37) @@ -15,7 +15,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use Bee\Persistence\Behaviors\AbstractFieldBasedDelegate; use Bee\Persistence\Pdo\FeatureDetector; +use Bee\Persistence\Pdo\Utils; /** * User: mp @@ -23,29 +25,20 @@ * Time: 02:19 */ -class DelegateBase extends FeatureDetector { +class DelegateBase extends AbstractFieldBasedDelegate { + /** * @var \Doctrine_Connection */ private $doctrineConnection; /** - * @var string - */ - private $entityClass; - - /** - * @var string - */ - private $idFieldName = 'id'; - - /** * @param string $entityClass * @param \Doctrine_Connection $doctrineConnection * @return \Bee\Persistence\Doctrine\Behaviors\DelegateBase */ public function __construct($entityClass, \Doctrine_Connection $doctrineConnection) { - $this->entityClass = $entityClass; + parent::__construct($entityClass); $this->doctrineConnection = $doctrineConnection; } @@ -57,38 +50,17 @@ } /** - * @return string - */ - public function getEntityClass() { - return $this->entityClass; - } - - /** - * @param string $idFieldName - */ - public function setIdFieldName($idFieldName) { - $this->idFieldName = $idFieldName; - } - - /** - * @return string - */ - public function getIdFieldName() { - return $this->idFieldName; - } - - /** * @return \Doctrine_Query */ protected function getEntityBaseQuery() { - return $this->getDoctrineConnection()->createQuery()->from($this->entityClass); + return $this->getDoctrineConnection()->createQuery()->from($this->getQueryDomain()); } /** * @return \Doctrine_Query */ protected function getEntityUpdateBaseQuery() { - return $this->getDoctrineConnection()->createQuery()->update($this->entityClass); + return $this->getDoctrineConnection()->createQuery()->update($this->getQueryDomain()); } /** @@ -99,7 +71,7 @@ */ protected function addIdentityRestriction(\Doctrine_Query $qry, $orderedEntity) { if($orderedEntity instanceof \Doctrine_Record) { - $id = $orderedEntity->get($this->idFieldName); + $id = $orderedEntity->get($this->getIdFieldName()); } else if(is_numeric($orderedEntity)) { $id = $orderedEntity; } else { @@ -108,11 +80,34 @@ return $qry->addWhere('id = :id', array(':id' => $id)); } + protected function addGroupRestriction(\Doctrine_Query $qry, $orderedEntity, $restriction = false) { + if ($this->getGroupFieldName()) { + if ($restriction === false) { + $restriction = $this->getGroup($orderedEntity); + } + $this->doAddGroupRestriction($qry, $restriction); + } + return $qry; + } + + protected function doAddGroupRestriction(\Doctrine_Query $qry, $restriction = false) { + return $qry->addWhere($this->getGroupFieldName().' = :grp_id', array(':grp_id' => $restriction)); + } + /** * @param string $feature * @return bool */ protected function pdoSupportsFeature($feature) { - return self::supports($feature, $this->getDoctrineConnection()->getDbh()); + return FeatureDetector::supports($feature, $this->getDoctrineConnection()->getDbh()); } + + /** + * @param $entity + * @return mixed + */ + protected function getGroup($entity) { + $grpQry = $this->getDoctrineConnection()->createQuery()->select($this->getGroupFieldName())->from($this->getQueryDomain()); + return $this->addIdentityRestriction($grpQry, $entity)->fetchOne(array(), \Doctrine_Core::HYDRATE_SINGLE_SCALAR); + } } Modified: trunk/framework/Bee/Persistence/Doctrine/Behaviors/GenericOrderedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine/Behaviors/GenericOrderedDelegate.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Doctrine/Behaviors/GenericOrderedDelegate.php 2013-05-21 14:20:15 UTC (rev 37) @@ -16,6 +16,7 @@ * limitations under the License. */ use Bee\Persistence\Behaviors\Ordered\IDelegate; +use Bee\Persistence\Pdo\FeatureDetector; use Bee\Persistence\Pdo\Utils; /** @@ -61,7 +62,7 @@ * @return int */ public function getMaxPosition($orderedEntity, $restriction = false) { - $qry = $this->addCustomRestricitons($this->getEntityBaseQuery($orderedEntity, $restriction), $restriction); + $qry = $this->addGroupRestriction($this->getEntityBaseQuery($orderedEntity, $restriction), $orderedEntity, $restriction); $result = $this->addMaxPositionSelect($qry)->fetchOne(array(), \Doctrine_Core::HYDRATE_SINGLE_SCALAR); return Utils::numericOrFalse($result); } @@ -76,7 +77,7 @@ public function shiftPosition($orderedEntity, $newPos, $oldPos, $restriction = false) { $params = array(); - $qry = $this->addCustomRestricitons($this->getEntityUpdateBaseQuery(), $restriction); + $qry = $this->addGroupRestriction($this->getEntityUpdateBaseQuery(), $orderedEntity, $restriction); if($oldPos !== false) { if($newPos !== false) { @@ -108,8 +109,8 @@ // if this is a single table update, add ORDER clause to avoid unique constraint violation (if driver supports it) - if ($oldPos !== false && $this->pdoSupportsFeature(self::FEATURE_ORDERED_UPDATE) /*&& stripos($qryDomain, ' JOIN ') === false*/) { - $qry->orderBy($this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC')); + if ($oldPos !== false && $this->pdoSupportsFeature(FeatureDetector::FEATURE_ORDERED_UPDATE) /*&& stripos($qryDomain, ' JOIN ') === false*/) { + $qry->orderBy($this->getPosExpression() . ($newPos !== false && ($newPos < $oldPos) ? ' DESC' : ' ASC')); } $qry->execute($params); @@ -121,7 +122,7 @@ * @param mixed $restriction */ public function setPosition($orderedEntity, $newPos, $restriction = false) { - $qry = $this->addCustomRestricitons($this->getEntityUpdateBaseQuery(), $restriction); + $qry = $this->addGroupRestriction($this->getEntityUpdateBaseQuery(), $orderedEntity, $restriction); $this->addIdentityRestriction($qry, $orderedEntity); $qry->set($this->getPosExpression(), is_null($newPos) ? 'NULL' : $newPos)->execute(); } @@ -134,7 +135,7 @@ protected function getIdentityBaseQuery($orderedEntity, $restriction = false) { $qry = $this->getEntityBaseQuery(); $this->addIdentityRestriction($qry, $orderedEntity); - return $this->addCustomRestricitons($qry, $restriction); + return $this->addGroupRestriction($qry, $orderedEntity, $restriction); } /** @@ -152,14 +153,4 @@ protected function addMaxPositionSelect(\Doctrine_Query $qry) { return $qry->select('MAX('.$this->getPosExpression().')'); } - - /** - * @param \Doctrine_Query $qry - * @param mixed $restriction - * @return \Doctrine_Query - */ - protected function addCustomRestricitons(\Doctrine_Query $qry, $restriction = false) { - // no default implementation - return $qry; - } } Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-05-21 14:20:15 UTC (rev 37) @@ -1,6 +1,7 @@ <?php namespace Bee\Persistence\Pdo\Behaviors; +use Bee\Persistence\Behaviors\AbstractFieldBasedDelegate; use Bee\Persistence\Pdo\FeatureDetector; use Bee\Persistence\Pdo\Utils; @@ -27,7 +28,7 @@ * Date: 05.05.13 * Time: 23:52 */ -abstract class DelegateBase extends FeatureDetector { +abstract class DelegateBase extends AbstractFieldBasedDelegate { const GROUP_QUERY_TEMPLATE = 'SELECT %1$s FROM %2$s WHERE %3$s'; @@ -37,28 +38,12 @@ private $pdo; /** - * @var string - */ - private $queryDomain; - - /** - * @var string - */ - private $idFieldName = 'id'; - - /** - * @var string - */ - private $groupFieldName; - - /** * @param string $queryDomain * @param \PDO $pdo * @return \Bee\Persistence\Pdo\Behaviors\DelegateBase */ public function __construct($queryDomain, \PDO $pdo) { - \Bee_Utils_Assert::hasText($queryDomain, 'Query domain (table name / table joins) required, must not be empty'); - $this->queryDomain = $queryDomain; + parent::__construct($queryDomain); $this->pdo = $pdo; } @@ -70,46 +55,11 @@ } /** - * @return string - */ - public function getQueryDomain() { - return $this->queryDomain; - } - - /** - * @param string $idFieldName - */ - public function setIdFieldName($idFieldName) { - $this->idFieldName = $idFieldName; - } - - /** - * @return string - */ - public function getIdFieldName() { - return $this->idFieldName; - } - - /** - * @param string $domainFieldName - */ - public function setGroupFieldName($domainFieldName) { - $this->groupFieldName = $domainFieldName; - } - - /** - * @return string - */ - public function getGroupFieldName() { - return $this->groupFieldName; - } - - /** * @param string $feature * @return bool */ protected function pdoSupportsFeature($feature) { - return self::supports($feature, $this->getPdo()); + return FeatureDetector::supports($feature, $this->getPdo()); } /** @@ -120,7 +70,7 @@ */ protected function getIdentityRestrictionString($entity, array &$params) { $params[':id'] = $entity; - return $this->idFieldName . ' = :id'; + return $this->getIdFieldName() . ' = :id'; } /** @@ -134,9 +84,7 @@ if ($this->getGroupFieldName()) { if ($restriction === false) { // determine group value - $grpParams = array(); - $qryString = sprintf(self::GROUP_QUERY_TEMPLATE, $this->getGroupFieldName(), $this->getQueryDomain(), $this->getIdentityRestrictionString($entity, $params)); - $restriction = Utils::fetchOne($this->getPdo()->prepare($qryString), $grpParams); + $restriction = $this->getGroup($entity); } $result = $this->doCreateRestrictionString($params, $restriction); } @@ -152,4 +100,15 @@ $params[':group_id'] = $restriction; return $this->getGroupFieldName() . ' = :group_id'; } + + /** + * @param $entity + * @return mixed + */ + protected function getGroup($entity) { + // determine group value + $params = array(); + $qryString = sprintf(self::GROUP_QUERY_TEMPLATE, $this->getGroupFieldName(), $this->getQueryDomain(), $this->getIdentityRestrictionString($entity, $params)); + return Utils::fetchOne($this->getPdo()->prepare($qryString), $params); + } } Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericNestedSetDelegate.php 2013-05-21 14:20:15 UTC (rev 37) @@ -3,6 +3,7 @@ use Bee\Persistence\Behaviors\NestedSet\IDelegate; use Bee\Persistence\Behaviors\NestedSet\NodeInfo; +use Bee\Persistence\Pdo\FeatureDetector; use Bee\Persistence\Pdo\Utils; /* @@ -138,7 +139,7 @@ $domRes = $this->getDomainRestrictionString($nestedSetEntity, $params, $restriction); // order updates only if supported by the driver and not operating on a joined relation - $orderUpdate = $this->pdoSupportsFeature(self::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false; + $orderUpdate = $this->pdoSupportsFeature(FeatureDetector::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false; // update left positions $qryString = sprintf($qryTempl, $qryDomain, $this->leftFieldName, $domRes); Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-21 14:20:15 UTC (rev 37) @@ -2,6 +2,7 @@ namespace Bee\Persistence\Pdo\Behaviors; use Bee\Persistence\Behaviors\Ordered\IDelegate; +use Bee\Persistence\Pdo\FeatureDetector; use Bee\Persistence\Pdo\Utils; /* @@ -69,7 +70,7 @@ /** * @param $orderedEntity * @param $restriction - * @return mixed + * @return int|bool */ public function getMaxPosition($orderedEntity, $restriction = false) { $params = array(); @@ -103,8 +104,8 @@ $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); // if this is a single table update, add ORDER clause to avoid unique constraint violation (if driver supports it) - if ($oldPos !== false && $this->pdoSupportsFeature(self::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false) { - $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); + if ($oldPos !== false && $this->pdoSupportsFeature(FeatureDetector::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false) { + $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos !== false && ($newPos < $oldPos) ? ' DESC' : ' ASC'); } $this->getPdo()->prepare($qryString)->execute($params); Modified: trunk/framework/Bee/Persistence/Pdo/SimpleDaoBase.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/SimpleDaoBase.php 2013-05-20 19:06:48 UTC (rev 36) +++ trunk/framework/Bee/Persistence/Pdo/SimpleDaoBase.php 2013-05-21 14:20:15 UTC (rev 37) @@ -75,6 +75,5 @@ $this->pdoConnection->rollBack(); throw $e; } - } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 13:23:29
|
Revision: 34 http://sourceforge.net/p/beeframework/code/34 Author: m_plomer Date: 2013-05-07 13:23:23 +0000 (Tue, 07 May 2013) Log Message: ----------- - intermediate commit: basic feature detection framework for PDO Modified Paths: -------------- trunk/examples/conf/log4php.xml trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php Added Paths: ----------- trunk/framework/Bee/Persistence/Pdo/FeatureDetector.php Modified: trunk/examples/conf/log4php.xml =================================================================== --- trunk/examples/conf/log4php.xml 2013-05-07 11:44:44 UTC (rev 33) +++ trunk/examples/conf/log4php.xml 2013-05-07 13:23:23 UTC (rev 34) @@ -18,7 +18,7 @@ <appender_ref ref="default" /> </root> <logger name="Bee" additivity="false"> - <level value="warn" /> + <level value="info" /> <appender_ref ref="framework" /> </logger> </configuration> \ No newline at end of file Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-05-07 11:44:44 UTC (rev 33) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-05-07 13:23:23 UTC (rev 34) @@ -1,5 +1,8 @@ <?php namespace Bee\Persistence\Pdo\Behaviors; + +use Bee\Persistence\Pdo\FeatureDetector; + /* * Copyright 2008-2010 the original author or authors. * @@ -23,7 +26,7 @@ * Date: 05.05.13 * Time: 23:52 */ -abstract class DelegateBase { +abstract class DelegateBase extends FeatureDetector { /** * @var \PDO @@ -69,4 +72,12 @@ $res = $qry->fetch(\PDO::FETCH_NUM); return $res [0]; } + + /** + * @param string $feature + * @return bool + */ + protected function pdoSupportsFeature($feature) { + return self::supports($feature, $this->getPdo()); + } } Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-07 11:44:44 UTC (rev 33) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-07 13:23:23 UTC (rev 34) @@ -166,11 +166,12 @@ $qryDomain = $this->getQueryDomain(); $qryString = sprintf($newPos < $oldPos ? self::SHIFT_UP_QUERY_TEMPLATE : self::SHIFT_DOWN_QUERY_TEMPLATE, $this->getPosExpression(), $qryDomain, $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); - // if this is a single table update, add ORDER clause to avoid unique constraint violation -// if (stripos($qryDomain, ' JOIN ') === false) { -// $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); -// } -// var_dump($qryString); + + // if this is a single table update, add ORDER clause to avoid unique constraint violation (if driver supports it) + if ($this->pdoSupportsFeature(self::FEATURE_ORDERED_UPDATE) && stripos($qryDomain, ' JOIN ') === false) { + $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); + } + $this->getPdo()->prepare($qryString)->execute($params); } Added: trunk/framework/Bee/Persistence/Pdo/FeatureDetector.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/FeatureDetector.php (rev 0) +++ trunk/framework/Bee/Persistence/Pdo/FeatureDetector.php 2013-05-07 13:23:23 UTC (rev 34) @@ -0,0 +1,82 @@ +<?php +namespace Bee\Persistence\Pdo; + /* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 07.05.13 + * Time: 14:42 + */ + +class FeatureDetector { + + const FEATURE_ORDERED_UPDATE = 'ORDERED_UPDATE'; + + private static $FEATURE_CACHE = array(); + + private static $DETECTORS; + + /** + * @var \Logger + */ + private static $log; + + /** + * @return \Logger + */ + protected static function getLog() { + if (!self::$log) { + self::$log = \Bee_Framework::getLoggerForClass(__CLASS__); + } + return self::$log; + } + + /** + * @param string $feature + * @param \PDO $pdoConnection + * @return bool + */ + public static function supports($feature, \PDO $pdoConnection) { + self::init(); + $connKey = spl_object_hash($pdoConnection); + if (!array_key_exists($connKey, self::$FEATURE_CACHE)) { + self::$FEATURE_CACHE[$connKey] = array(); + } + if (!array_key_exists($feature, self::$FEATURE_CACHE[$connKey])) { + $detector = self::$DETECTORS[$feature]; + $result = $detector($pdoConnection); + self::$FEATURE_CACHE[$connKey][$feature] = $result; + self::getLog()->info("PDO connection $connKey supports feature $feature : " . ($result ? "YES" : "NO")); + } + return self::$FEATURE_CACHE[$connKey][$feature]; + } + + private static function init() { + if (!self::$DETECTORS) { + self::$DETECTORS = array( + self::FEATURE_ORDERED_UPDATE => function (\PDO $pdoConnection) { + switch ($pdoConnection->getAttribute(\PDO::ATTR_DRIVER_NAME)) { + case 'mysql': + return true; + } + return false; + } + ); + } + } +} + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 11:44:48
|
Revision: 33 http://sourceforge.net/p/beeframework/code/33 Author: m_plomer Date: 2013-05-07 11:44:44 +0000 (Tue, 07 May 2013) Log Message: ----------- - pdo ordering examples Modified Paths: -------------- trunk/examples/index.php Modified: trunk/examples/index.php =================================================================== --- trunk/examples/index.php 2013-05-07 11:15:59 UTC (rev 32) +++ trunk/examples/index.php 2013-05-07 11:44:44 UTC (rev 33) @@ -51,4 +51,4 @@ $dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); -//BeeFramework::dispatchRequestUsingSerializedContext('conf/context.serialized'); +echo 'DONE<hr/>'; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 11:16:03
|
Revision: 32 http://sourceforge.net/p/beeframework/code/32 Author: m_plomer Date: 2013-05-07 11:15:59 +0000 (Tue, 07 May 2013) Log Message: ----------- - pdo ordering examples Modified Paths: -------------- trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php trunk/examples/index.php Modified: trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php =================================================================== --- trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php 2013-05-07 11:13:57 UTC (rev 31) +++ trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php 2013-05-07 11:15:59 UTC (rev 32) @@ -61,6 +61,19 @@ } /** + * + */ + public function createTable() { + $this->pdoConnection->exec('CREATE TABLE "ordered_colors" ( + "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" text NOT NULL, + "hex_value" text NOT NULL, + "pos" integer DEFAULT NULL, + UNIQUE (pos ASC) + )'); + } + + /** * @return \Bee\Persistence\Behaviors\Ordered\Strategy */ public function getOrderedStrategy() { Modified: trunk/examples/index.php =================================================================== --- trunk/examples/index.php 2013-05-07 11:13:57 UTC (rev 31) +++ trunk/examples/index.php 2013-05-07 11:15:59 UTC (rev 32) @@ -38,17 +38,10 @@ $ctx = new Bee_Context_Xml('conf/context.xml'); -$pdoConn = $ctx->getBean('pdoConnection'); -$pdoConn->exec('CREATE TABLE "ordered_colors" ( - "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, - "name" text NOT NULL, - "hex_value" text NOT NULL, - "pos" integer DEFAULT NULL, - UNIQUE (pos ASC) -)'); - $dao = $ctx->getBean('orderedColorsDao'); +$dao->createTable(); + $dao->addColor('Red', '#ff0000'); $greenId = $dao->addColor('Green', '#00ff00'); $dao->addColor('Blue', '#0000ff'); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 11:14:02
|
Revision: 31 http://sourceforge.net/p/beeframework/code/31 Author: m_plomer Date: 2013-05-07 11:13:57 +0000 (Tue, 07 May 2013) Log Message: ----------- - pdo ordering examples Modified Paths: -------------- trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php Modified: trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php 2013-05-07 11:13:24 UTC (rev 30) +++ trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php 2013-05-07 11:13:57 UTC (rev 31) @@ -28,7 +28,7 @@ * @param mixed $restriction * @return int */ - public function getPosition($orderedEntity, $restriction); + public function getPosition($orderedEntity, $restriction = false); /** * @param mixed $orderedEntity @@ -43,12 +43,12 @@ * @param int $oldPos * @param $restriction */ - public function shiftPosition($orderedEntity, $newPos, $oldPos, $restriction); + public function shiftPosition($orderedEntity, $newPos, $oldPos, $restriction = false); /** * @param mixed $orderedEntity * @param int $newPos * @param mixed $restriction */ - public function setPosition($orderedEntity, $newPos, $restriction); + public function setPosition($orderedEntity, $newPos, $restriction = false); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 11:13:27
|
Revision: 30 http://sourceforge.net/p/beeframework/code/30 Author: m_plomer Date: 2013-05-07 11:13:24 +0000 (Tue, 07 May 2013) Log Message: ----------- - pdo ordering examples Modified Paths: -------------- trunk/framework/Bee/Framework.php trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php Added Paths: ----------- trunk/examples/ trunk/examples/classes/ trunk/examples/classes/Persistence/ trunk/examples/classes/Persistence/Pdo/ trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php trunk/examples/conf/ trunk/examples/conf/context.xml trunk/examples/conf/log4php.xml trunk/examples/db/ trunk/examples/index.php trunk/examples/logs/ Added: trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php =================================================================== --- trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php (rev 0) +++ trunk/examples/classes/Persistence/Pdo/OrderedColorsDao.php 2013-05-07 11:13:24 UTC (rev 30) @@ -0,0 +1,93 @@ +<?php +namespace Persistence\Pdo; + +use Bee\Persistence\Behaviors\Ordered\Strategy as OrderedStrategy; +use Bee\Persistence\Pdo\Behaviors\GenericOrderedDelegate; + +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 07.05.13 + * Time: 12:12 + */ + +class OrderedColorsDao { + + /** + * @var \Logger + */ + private static $log; + + /** + * @return \Logger + */ + protected static function getLog() { + if (!self::$log) { + self::$log = \Bee_Framework::getLoggerForClass(__CLASS__); + } + return self::$log; + } + + /** + * @var \PDO + */ + private $pdoConnection; + + /** + * @var OrderedStrategy + */ + private $orderedStrategy; + + public function __construct(\PDO $pdoConnection) { + self::getLog()->info('DAO constructed, got PDO connection'); + $this->pdoConnection = $pdoConnection; + $pdoOrderedDelagate = new GenericOrderedDelegate('ordered_colors', $pdoConnection); + $this->orderedStrategy = new OrderedStrategy($pdoOrderedDelagate); + } + + /** + * @return \Bee\Persistence\Behaviors\Ordered\Strategy + */ + public function getOrderedStrategy() { + return $this->orderedStrategy; + } + + public function addColor($colorName, $colorHex) { + self::getLog()->info("adding color ($colorName, $colorHex)"); + + $this->pdoConnection->beginTransaction(); + try { + + self::getLog()->debug('inserting'); + $insertStmt = $this->pdoConnection->prepare('INSERT INTO ordered_colors (name, hex_value) VALUES (:name, :hex_value)'); + $insertStmt->execute(array(':name' => $colorName, ':hex_value' => $colorHex)); + + $id = $this->pdoConnection->lastInsertId(); + self::getLog()->debug('moving to end of list'); + $pos = $this->orderedStrategy->moveToEnd($id); + + self::getLog()->debug("committing ($id, $colorName, $colorHex, $pos)"); + $this->pdoConnection->commit(); + return $id; + } catch(\Exception $e) { + self::getLog()->debug('exception caught', $e); + $this->pdoConnection->rollBack(); + throw $e; + } + } +} Added: trunk/examples/conf/context.xml =================================================================== --- trunk/examples/conf/context.xml (rev 0) +++ trunk/examples/conf/context.xml 2013-05-07 11:13:24 UTC (rev 30) @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.beeframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:security="http://www.beeframework.org/schema/security" + xsi:schemaLocation="http://www.beeframework.org/schema/beans http://www.beeframework.org/schema/beans/bee-beans-1.2.xsd + http://www.beeframework.org/schema/security http://www.beeframework.org/schema/security/bee-security-1.0.xsd"> + + <!-- Persistence - PDO Connection --> + <bean id="pdoConnection" class="PDO"> + <!-- LOCAL DB --> + <constructor-arg index="0" value="sqlite:db/examples.sqlite" /> + <constructor-arg index="1" value="sa" /> + <constructor-arg index="2" value="" /> + </bean> + + <bean id="orderedColorsDao" class="Persistence\Pdo\OrderedColorsDao"> + <constructor-arg index="0" ref="pdoConnection" /> + </bean> + +</beans> Added: trunk/examples/conf/log4php.xml =================================================================== --- trunk/examples/conf/log4php.xml (rev 0) +++ trunk/examples/conf/log4php.xml 2013-05-07 11:13:24 UTC (rev 30) @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<configuration xmlns="http://logging.apache.org/log4php/"> + <appender name="default" class="LoggerAppenderFile"> + <layout class="LoggerLayoutPattern"> + <param name="conversionPattern" value="%date %logger %-5level %msg%n" /> + </layout> + <param name="file" value="logs/application.log" /> + <param name="append" value="true" /> + </appender> + <appender name="framework" class="LoggerAppenderFile"> + <layout class="LoggerLayoutPattern"> + <param name="conversionPattern" value="%date %logger %-5level %msg%n" /> + </layout> + <param name="file" value="logs/framework.log" /> + <param name="append" value="true" /> + </appender> + <root> + <appender_ref ref="default" /> + </root> + <logger name="Bee" additivity="false"> + <level value="warn" /> + <appender_ref ref="framework" /> + </logger> +</configuration> \ No newline at end of file Index: trunk/examples/db =================================================================== --- trunk/examples/db 2013-05-07 07:25:49 UTC (rev 29) +++ trunk/examples/db 2013-05-07 11:13:24 UTC (rev 30) Property changes on: trunk/examples/db ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +examples.sqlite Added: trunk/examples/index.php =================================================================== --- trunk/examples/index.php (rev 0) +++ trunk/examples/index.php 2013-05-07 11:13:24 UTC (rev 30) @@ -0,0 +1,61 @@ +<?php +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 07.05.13 + * Time: 12:25 + */ + +require_once '../framework/Bee/Framework.php'; + +// Verzeichnis mit Applikations-Klassen zum Classpath hinzufügen +Bee_Framework::addApplicationIncludePath('classes'); + +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/helpers'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/pattern'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/layouts'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/appenders'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/configurators'); +Bee_Framework::addApplicationIncludePath('../libs/apache-log4php-2.3.0/renderers'); + +Logger::configure('conf/log4php.xml'); + +$ctx = new Bee_Context_Xml('conf/context.xml'); + +$pdoConn = $ctx->getBean('pdoConnection'); +$pdoConn->exec('CREATE TABLE "ordered_colors" ( + "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" text NOT NULL, + "hex_value" text NOT NULL, + "pos" integer DEFAULT NULL, + UNIQUE (pos ASC) +)'); + +$dao = $ctx->getBean('orderedColorsDao'); + +$dao->addColor('Red', '#ff0000'); +$greenId = $dao->addColor('Green', '#00ff00'); +$dao->addColor('Blue', '#0000ff'); +$dao->addColor('Yellow', '#ffff00'); +$purpleId = $dao->addColor('Purple', '#ff00ff'); +$dao->addColor('Cyan', '#00ffff'); + +$dao->getOrderedStrategy()->moveAfter($greenId, $purpleId); + +//BeeFramework::dispatchRequestUsingSerializedContext('conf/context.serialized'); Index: trunk/examples/logs =================================================================== --- trunk/examples/logs 2013-05-07 07:25:49 UTC (rev 29) +++ trunk/examples/logs 2013-05-07 11:13:24 UTC (rev 30) Property changes on: trunk/examples/logs ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +*.log Modified: trunk/framework/Bee/Framework.php =================================================================== --- trunk/framework/Bee/Framework.php 2013-05-07 07:25:49 UTC (rev 29) +++ trunk/framework/Bee/Framework.php 2013-05-07 11:13:24 UTC (rev 30) @@ -78,7 +78,7 @@ * @return void */ static function init() { - self::$beeHiveLocation = dirname(__FILE__); + self::$beeHiveLocation = dirname(dirname(__FILE__)); self::addApplicationIncludePath(self::$beeHiveLocation); require_once dirname(__FILE__) . '/Cache/Manager.php'; Modified: trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php 2013-05-07 07:25:49 UTC (rev 29) +++ trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php 2013-05-07 11:13:24 UTC (rev 30) @@ -29,29 +29,54 @@ */ private $delegate; + public function __construct(IDelegate $delgate) { + $this->delegate = $delgate; + } + /** * @param mixed $subject * @param mixed $ref * @param mixed $groupRestriction + * @return int */ public function moveBefore($subject, $ref, $groupRestriction = false) { - $this->moveRelative($subject, $ref, true, $groupRestriction); + return $this->moveRelative($subject, $ref, true, $groupRestriction); } /** * @param mixed $subject * @param mixed $ref * @param mixed $groupRestriction + * @return int */ - public function moveBehind($subject, $ref, $groupRestriction = false) { - $this->moveRelative($subject, $ref, false, $groupRestriction); + public function moveAfter($subject, $ref, $groupRestriction = false) { + return $this->moveRelative($subject, $ref, false, $groupRestriction); } /** * @param mixed $subject + * @param mixed $groupRestriction + * @return int + */ + public function moveToStart($subject, $groupRestriction = false) { + return $this->moveAfter($subject, false, $groupRestriction); + } + + /** + * @param mixed $subject + * @param mixed $groupRestriction + * @return int + */ + public function moveToEnd($subject, $groupRestriction = false) { + return $this->moveBefore($subject, false, $groupRestriction); + } + + /** + * @param mixed $subject * @param mixed $ref * @param bool $before * @param mixed $groupRestriction + * @return int */ public function moveRelative($subject, $ref, $before = true, $groupRestriction = false) { // determine previous position of subject @@ -83,5 +108,7 @@ $this->delegate->setPosition($subject, $newPos, $groupRestriction); } // that's all, folks! + + return $newPos; } } Modified: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-07 07:25:49 UTC (rev 29) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-07 11:13:24 UTC (rev 30) @@ -167,9 +167,10 @@ $qryString = sprintf($newPos < $oldPos ? self::SHIFT_UP_QUERY_TEMPLATE : self::SHIFT_DOWN_QUERY_TEMPLATE, $this->getPosExpression(), $qryDomain, $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); // if this is a single table update, add ORDER clause to avoid unique constraint violation - if (stripos($qryDomain, ' JOIN ') === false) { - $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); - } +// if (stripos($qryDomain, ' JOIN ') === false) { +// $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); +// } +// var_dump($qryString); $this->getPdo()->prepare($qryString)->execute($params); } @@ -178,7 +179,7 @@ * @param int $newPos * @param mixed $restriction */ - public function setPosition($orderedEntity, $newPos, $restriction) { + public function setPosition($orderedEntity, $newPos, $restriction = false) { $params = array(':newPos' => $newPos); $qryString = sprintf(self::SET_POS_QUERY_TEMPLATE, $this->getPosExpression(), $this->getQueryDomain(), $this->getIdentityRestrictionString($orderedEntity, $params), $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-07 07:25:52
|
Revision: 29 http://sourceforge.net/p/beeframework/code/29 Author: m_plomer Date: 2013-05-07 07:25:49 +0000 (Tue, 07 May 2013) Log Message: ----------- - intermediate commit Modified Paths: -------------- trunk/framework/Bee/Annotations/Utils.php trunk/framework/Bee/Framework.php trunk/framework/Bee/Persistence/Doctrine/DaoBase.php trunk/framework/Bee/Persistence/Pdo/Template.php trunk/framework/composer.json Added Paths: ----------- trunk/framework/Bee/Persistence/Behaviors/ trunk/framework/Bee/Persistence/Behaviors/Ordered/ trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php trunk/framework/Bee/Persistence/Doctrine2/ trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php trunk/framework/Bee/Persistence/Pdo/Behaviors/ trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php Modified: trunk/framework/Bee/Annotations/Utils.php =================================================================== --- trunk/framework/Bee/Annotations/Utils.php 2013-05-02 13:54:25 UTC (rev 28) +++ trunk/framework/Bee/Annotations/Utils.php 2013-05-07 07:25:49 UTC (rev 29) @@ -16,6 +16,7 @@ */ use Addendum\ReflectionAnnotatedClass; +use Addendum\ReflectionAnnotatedMethod; /** * User: mp * Date: Feb 19, 2010 @@ -56,5 +57,3 @@ return new ReflectionAnnotatedMethod($method->getDeclaringClass(), $method->getName()); } } - -?> \ No newline at end of file Modified: trunk/framework/Bee/Framework.php =================================================================== --- trunk/framework/Bee/Framework.php 2013-05-02 13:54:25 UTC (rev 28) +++ trunk/framework/Bee/Framework.php 2013-05-07 07:25:49 UTC (rev 29) @@ -338,6 +338,10 @@ return self::$productionMode; } + /** + * @param string $className + * @return Logger + */ public static function getLoggerForClass($className) { return Logger::getLogger(str_replace('_', '.', str_replace('\\', '.', $className))); } Added: trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php (rev 0) +++ trunk/framework/Bee/Persistence/Behaviors/Ordered/IDelegate.php 2013-05-07 07:25:49 UTC (rev 29) @@ -0,0 +1,54 @@ +<?php +namespace Bee\Persistence\Behaviors\Ordered; +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 05.05.13 + * Time: 23:07 + */ +interface IDelegate { + + /** + * @param mixed $orderedEntity + * @param mixed $restriction + * @return int + */ + public function getPosition($orderedEntity, $restriction); + + /** + * @param mixed $orderedEntity + * @param mixed $restriction + * @return int + */ + public function getMaxPosition($orderedEntity, $restriction = false); + + /** + * @param mixed $orderedEntity + * @param int $newPos + * @param int $oldPos + * @param $restriction + */ + public function shiftPosition($orderedEntity, $newPos, $oldPos, $restriction); + + /** + * @param mixed $orderedEntity + * @param int $newPos + * @param mixed $restriction + */ + public function setPosition($orderedEntity, $newPos, $restriction); +} Added: trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php =================================================================== --- trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php (rev 0) +++ trunk/framework/Bee/Persistence/Behaviors/Ordered/Strategy.php 2013-05-07 07:25:49 UTC (rev 29) @@ -0,0 +1,87 @@ +<?php +namespace Bee\Persistence\Behaviors\Ordered; + + /* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 05.05.13 + * Time: 23:08 + */ +class Strategy { + + /** + * @var IDelegate + */ + private $delegate; + + /** + * @param mixed $subject + * @param mixed $ref + * @param mixed $groupRestriction + */ + public function moveBefore($subject, $ref, $groupRestriction = false) { + $this->moveRelative($subject, $ref, true, $groupRestriction); + } + + /** + * @param mixed $subject + * @param mixed $ref + * @param mixed $groupRestriction + */ + public function moveBehind($subject, $ref, $groupRestriction = false) { + $this->moveRelative($subject, $ref, false, $groupRestriction); + } + + /** + * @param mixed $subject + * @param mixed $ref + * @param bool $before + * @param mixed $groupRestriction + */ + public function moveRelative($subject, $ref, $before = true, $groupRestriction = false) { + // determine previous position of subject + $oldPos = $this->delegate->getPosition($subject, $groupRestriction); + + // is there a reference element given? + if ($ref) { + // yes, drop on the position following the referenced element (or on its position proper, in case the moved + // element preceded the reference element in the list + $newPos = $this->delegate->getPosition($ref, $groupRestriction); + + if (!$before && $oldPos > $newPos) { + $newPos += 1; + } else if ($before && $oldPos < $newPos) { + $newPos -= 1; + } + } else { + // no, "move behind nothing" means "move to beginning", "move before nothing" means "move to the end" + $newPos = $before ? $this->delegate->getMaxPosition($subject, $groupRestriction) + 1 : 0; + } + + // actual move? + if ($oldPos != $newPos) { + // temporarily move the subject to a neutral position, so as to avoid any conflicts (e.g. SQL constraints) + $this->delegate->setPosition($subject, -1, $groupRestriction); + // shift remaining entries (possibly including reference element) + $this->delegate->shiftPosition($subject, $newPos, $oldPos, $groupRestriction); + // set final position on subject + $this->delegate->setPosition($subject, $newPos, $groupRestriction); + } + // that's all, folks! + } +} Modified: trunk/framework/Bee/Persistence/Doctrine/DaoBase.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine/DaoBase.php 2013-05-02 13:54:25 UTC (rev 28) +++ trunk/framework/Bee/Persistence/Doctrine/DaoBase.php 2013-05-07 07:25:49 UTC (rev 29) @@ -112,11 +112,12 @@ } } - /** - * @param Doctrine_Query $query - * @param array $params - * @param Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder - */ + /** + * @param Doctrine_Query $query + * @param array $params + * @param Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder + * @param array $defaultOrderMapping + */ protected final function applyOrderAndLimit(Doctrine_Query &$query, array &$params, Bee_Persistence_IOrderAndLimitHolder $orderAndLimitHolder = null, array $defaultOrderMapping = array()) { if (is_null($orderAndLimitHolder)) { $orderMapping = $defaultOrderMapping; Added: trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php =================================================================== --- trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php (rev 0) +++ trunk/framework/Bee/Persistence/Doctrine2/DaoBase.php 2013-05-07 07:25:49 UTC (rev 29) @@ -0,0 +1,32 @@ +<?php +namespace Bee\Persistence\Doctrine2; + +use \Doctrine\ORM\EntityManager; + +/** + * User: mp + * Date: 05.05.13 + * Time: 17:26 + */ +class DaoBase { + + /** + * @var EntityManager + */ + private $em; + + /** + * @return EntityManager + */ + public function getEm() { + return $this->em; + } + + /** + * @param EntityManager $em + */ + public function setEm(EntityManager $em) { + $this->em = $em; + } + +} Added: trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php (rev 0) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/DelegateBase.php 2013-05-07 07:25:49 UTC (rev 29) @@ -0,0 +1,72 @@ +<?php +namespace Bee\Persistence\Pdo\Behaviors; +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use \PDOStatement; + +/** + * User: mp + * Date: 05.05.13 + * Time: 23:52 + */ +abstract class DelegateBase { + + /** + * @var \PDO + */ + private $pdo; + + /** + * @var string + */ + private $queryDomain; + + /** + * @param string $queryDomain + * @param \PDO $pdo + */ + public function __construct($queryDomain, \PDO $pdo) { + \Bee_Utils_Assert::hasText($queryDomain, 'Query domain (table name / table joins) required, must not be empty'); + $this->queryDomain = $queryDomain; + $this->pdo = $pdo; + } + + /** + * @return \PDO + */ + public function getPdo() { + return $this->pdo; + } + + /** + * @return string + */ + public function getQueryDomain() { + return $this->queryDomain; + } + + /** + * @param PDOStatement $qry + * @param array $params + * @return mixed + */ + public static function fetchOne(PDOStatement $qry, array $params) { + $qry->execute($params); + $res = $qry->fetch(\PDO::FETCH_NUM); + return $res [0]; + } +} Added: trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php (rev 0) +++ trunk/framework/Bee/Persistence/Pdo/Behaviors/GenericOrderedDelegate.php 2013-05-07 07:25:49 UTC (rev 29) @@ -0,0 +1,187 @@ +<?php +namespace Bee\Persistence\Pdo\Behaviors; + +use Bee\Persistence\Behaviors\Ordered\IDelegate; + +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * User: mp + * Date: 05.05.13 + * Time: 23:23 + */ +class GenericOrderedDelegate extends DelegateBase implements IDelegate { + + const GET_POS_QUERY_TEMPLATE = 'SELECT %1$s FROM %2$s WHERE %3$s AND %4$s'; + const MAX_POS_QUERY_TEMPLATE = 'SELECT MAX(%1$s) FROM %2$s WHERE %3$s'; + const GROUP_QUERY_TEMPLATE = 'SELECT %1$s FROM %2$s WHERE %3$s'; + const SHIFT_UP_QUERY_TEMPLATE = 'UPDATE %2$s SET %1$s = %1$s + 1 WHERE %1$s >= :newPos AND %1$s < :oldPos AND %3$s'; + const SHIFT_DOWN_QUERY_TEMPLATE = 'UPDATE %2$s SET %1$s = %1$s - 1 WHERE %1$s <= :newPos AND %1$s > :oldPos AND %3$s'; + const SET_POS_QUERY_TEMPLATE = 'UPDATE %2$s SET %1$s = :newPos WHERE %3$s AND %4$s'; + + /** + * @var string + */ + private $posExpression = 'pos'; + + /** + * @var string + */ + private $idFieldName = 'id'; + + /** + * @var string + */ + private $groupFieldName; + + /** + * @param string $posFieldName + */ + public function setPosExpression($posFieldName) { + $this->posExpression = $posFieldName; + } + + /** + * @return string + */ + public function getPosExpression() { + return $this->posExpression; + } + + /** + * @param string $idFieldName + */ + public function setIdFieldName($idFieldName) { + $this->idFieldName = $idFieldName; + } + + /** + * @return string + */ + public function getIdFieldName() { + return $this->idFieldName; + } + + /** + * @param string $domainFieldName + */ + public function setGroupFieldName($domainFieldName) { + $this->groupFieldName = $domainFieldName; + } + + /** + * @return string + */ + public function getGroupFieldName() { + return $this->groupFieldName; + } + + /** + * @param $orderedEntity + * @param array $params + * @param bool $restriction + * @return string + */ + protected function getDomainRestrictionString($orderedEntity, array &$params, $restriction = false) { + $result = '1=1'; + if ($this->getGroupFieldName()) { + if ($restriction === false) { + // determine group value + $grpParams = array(); + $qryString = sprintf(self::GROUP_QUERY_TEMPLATE, $this->getGroupFieldName(), $this->getQueryDomain(), $this->getIdentityRestrictionString($orderedEntity, $params)); + $restriction = self::fetchOne($this->getPdo()->prepare($qryString), $grpParams); + } + $result = $this->doCreateRestrictionString($params, $restriction); + } + return $result; + } + + /** + * @param array $params + * @param $restriction + * @return string + */ + protected function doCreateRestrictionString(array &$params, $restriction) { + $params[':group_id'] = $restriction; + return $this->getGroupFieldName() . ' = :group_id'; + } + + /** + * @param $orderedEntity object representing the entity to be manipulated. Default implementation assumes that this + * is the actual id as stored in the database + * @param array $params + * @return string + */ + protected function getIdentityRestrictionString($orderedEntity, array &$params) { + $params[':id'] = $orderedEntity; + return $this->getIdFieldName() . ' = :id'; + } + + /** + * @param $orderedEntity + * @param $restriction + * @return mixed + */ + public function getPosition($orderedEntity, $restriction = false) { + $params = array(); + $qryString = sprintf(self::GET_POS_QUERY_TEMPLATE, $this->getPosExpression(), $this->getQueryDomain(), + $this->getIdentityRestrictionString($orderedEntity, $params), $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); + return self::fetchOne($this->getPdo()->prepare($qryString), $params); + } + + /** + * @param $orderedEntity + * @param $restriction + * @return mixed + */ + public function getMaxPosition($orderedEntity, $restriction = false) { + $params = array(); + $qryString = sprintf(self::MAX_POS_QUERY_TEMPLATE, $this->getPosExpression(), $this->getQueryDomain(), + $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); + return self::fetchOne($this->getPdo()->prepare($qryString), $params); + } + + /** + * @param $orderedEntity + * @param int $newPos + * @param int $oldPos + * @param mixed $restriction + */ + public function shiftPosition($orderedEntity, $newPos, $oldPos, $restriction = false) { + $params = array(':newPos' => $newPos, ':oldPos' => $oldPos); + $qryDomain = $this->getQueryDomain(); + $qryString = sprintf($newPos < $oldPos ? self::SHIFT_UP_QUERY_TEMPLATE : self::SHIFT_DOWN_QUERY_TEMPLATE, + $this->getPosExpression(), $qryDomain, $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); + // if this is a single table update, add ORDER clause to avoid unique constraint violation + if (stripos($qryDomain, ' JOIN ') === false) { + $qryString .= ' ORDER BY ' . $this->getPosExpression() . ($newPos < $oldPos ? ' DESC' : ' ASC'); + } + $this->getPdo()->prepare($qryString)->execute($params); + } + + /** + * @param mixed $orderedEntity + * @param int $newPos + * @param mixed $restriction + */ + public function setPosition($orderedEntity, $newPos, $restriction) { + $params = array(':newPos' => $newPos); + $qryString = sprintf(self::SET_POS_QUERY_TEMPLATE, $this->getPosExpression(), $this->getQueryDomain(), + $this->getIdentityRestrictionString($orderedEntity, $params), $this->getDomainRestrictionString($orderedEntity, $params, $restriction)); + $this->getPdo()->prepare($qryString)->execute($params); + } +} Modified: trunk/framework/Bee/Persistence/Pdo/Template.php =================================================================== --- trunk/framework/Bee/Persistence/Pdo/Template.php 2013-05-02 13:54:25 UTC (rev 28) +++ trunk/framework/Bee/Persistence/Pdo/Template.php 2013-05-07 07:25:49 UTC (rev 29) @@ -28,6 +28,11 @@ */ private $pdoConnection; + /** + * @var Logger + */ + private static $log; + /** * Gets the PdoConnection * @@ -47,6 +52,16 @@ $this->pdoConnection = $pdoConnection; } + /** + * @return \Logger + */ + public static function getLog() { + if(!self::$log) { + self::$log = Bee_Framework::getLoggerForClass(__CLASS__); + } + return self::$log; + } + public function __construct(PDO $pdoConnection) { $this->pdoConnection = $pdoConnection; } @@ -90,7 +105,7 @@ Bee_Persistence_Pdo_IResultSetExtractor $rse) { Bee_Utils_Assert::notNull($rse, 'ResultSetExtractor must not be null'); - Bee_Utils_Logger::debug('Executing prepared SQL query'); + self::getLog()->debug('Executing prepared SQL query'); return $this->execute($psc, new Bee_Persistence_Pdo_Template_QueryCallback($pss, $rse)); } @@ -104,7 +119,7 @@ } public function update(Bee_Persistence_Pdo_IStatementCreator $psc, Bee_Persistence_Pdo_IStatementSetter $pss) { - Bee_Utils_Logger::debug('Executing prepared SQL update'); + self::getLog()->debug('Executing prepared SQL update'); return $this->execute($psc, new Bee_Persistence_Pdo_Template_UpdateCallback($pss)); } @@ -113,7 +128,7 @@ } public function batchUpdate(Bee_Persistence_Pdo_IStatementCreator $psc, Bee_Persistence_Pdo_IBatchStatementSetter $bss) { - Bee_Utils_Logger::debug('Executing prepared SQL batch update'); + self::getLog()->debug('Executing prepared SQL batch update'); return $this->execute($psc, new Bee_Persistence_Pdo_Template_BatchUpdateCallback($bss)); } @@ -126,9 +141,9 @@ Bee_Utils_Assert::notNull($psc, 'PreparedStatementCreator must not be null'); Bee_Utils_Assert::notNull($action, 'Callback object must not be null'); - if (Bee_Utils_Logger::isDebugEnabled()) { + if (self::getLog()->isDebugEnabled()) { $sql = self::getSql($psc); - Bee_Utils_Logger::debug('Executing prepared SQL statement' . (!is_null($sql) ? " [" . $sql . "]" : "")); + self::getLog()->debug('Executing prepared SQL statement' . (!is_null($sql) ? " [" . $sql . "]" : "")); } $ps = null; @@ -197,18 +212,30 @@ */ private $pss; + /** + * @var Logger + */ + private static $log; + public function __construct(Bee_Persistence_Pdo_IStatementSetter $pss) { $this->pss = $pss; } + public static function getLog() { + if(!self::$log) { + self::$log = Bee_Framework::getLoggerForClass(__CLASS__); + } + return self::$log; + } + function doInPreparedStatement(PDOStatement $ps) { if ($this->pss != null) { $this->pss->setValues($ps); } if($ps->execute()) { $rows = $ps->rowCount(); - if(Bee_Utils_Logger::isDebugEnabled()) { - Bee_Utils_Logger::debug('SQL update affected '.$rows.' rows'); + if(self::getLog()->isDebugEnabled()) { + self::getLog()->debug('SQL update affected '.$rows.' rows'); } return $rows; } Modified: trunk/framework/composer.json =================================================================== --- trunk/framework/composer.json 2013-05-02 13:54:25 UTC (rev 28) +++ trunk/framework/composer.json 2013-05-07 07:25:49 UTC (rev 29) @@ -15,7 +15,7 @@ } ], "require": { - "php": ">=5.2.3", + "php": ">=5.3", "niktux/addendum": "0.4.1", "apache/log4php": "2.3.0" }, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-02 13:54:28
|
Revision: 28 http://sourceforge.net/p/beeframework/code/28 Author: m_plomer Date: 2013-05-02 13:54:25 +0000 (Thu, 02 May 2013) Log Message: ----------- - updated composer.json Modified Paths: -------------- trunk/framework/composer.json Modified: trunk/framework/composer.json =================================================================== --- trunk/framework/composer.json 2013-05-02 13:22:26 UTC (rev 27) +++ trunk/framework/composer.json 2013-05-02 13:54:25 UTC (rev 28) @@ -21,7 +21,7 @@ }, "autoload": { "psr-0": { - "Bee": "framework/" + "Bee": "" } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-02 13:22:29
|
Revision: 27 http://sourceforge.net/p/beeframework/code/27 Author: m_plomer Date: 2013-05-02 13:22:26 +0000 (Thu, 02 May 2013) Log Message: ----------- - further PHP 5.3 related changes Modified Paths: -------------- trunk/framework/Bee/Annotations/Utils.php trunk/framework/Bee/Cache/Manager.php trunk/framework/Bee/Cache/Provider/File.php trunk/framework/Bee/Context/Xml/ReaderContext.php trunk/framework/Bee/Context/Xml.php trunk/framework/Bee/MVC/Controller/Multiaction/MethodNameResolver/AnnotationBased.php trunk/framework/Bee/MVC/Controller/Multiaction/RequestHandler.php trunk/framework/Bee/Security/Annotations/SecuredMethodDefinitionSource.php trunk/framework/Bee/Weaving/Enhancer.php trunk/tests/bootstrap.php Added Paths: ----------- trunk/framework/Bee/Framework.php trunk/framework/composer.json Removed Paths: ------------- trunk/composer.json trunk/framework/BeeFramework.php Deleted: trunk/composer.json =================================================================== --- trunk/composer.json 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/composer.json 2013-05-02 13:22:26 UTC (rev 27) @@ -1,22 +0,0 @@ -{ - "name": "bee-framework/bee-framework", - "type": "library", - "description": "Bee Framework - PHP 5 DI/IoC application framework", - "keywords": ["framework"], - "homepage": "http://sourceforge.net/projects/beeframework/", - "license": "Apache License V2.0", - "authors": [ - { - "name": "Michael Plomer", - "email": "mic...@it..." - }, - { - "name": "Benjamin Hartmann" - } - ], - "require": { - "php": ">=5.2.3", - "niktux/addendum": "0.4.1", - "apache/log4php": "2.3.0" - } -} \ No newline at end of file Modified: trunk/framework/Bee/Annotations/Utils.php =================================================================== --- trunk/framework/Bee/Annotations/Utils.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Annotations/Utils.php 2013-05-02 13:22:26 UTC (rev 27) @@ -15,6 +15,7 @@ * limitations under the License. */ +use Addendum\ReflectionAnnotatedClass; /** * User: mp * Date: Feb 19, 2010 Modified: trunk/framework/Bee/Cache/Manager.php =================================================================== --- trunk/framework/Bee/Cache/Manager.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Cache/Manager.php 2013-05-02 13:22:26 UTC (rev 27) @@ -79,7 +79,7 @@ } private static function initProviderClass($providerClass) { - $loc = BeeFramework::getClassFileLocations($providerClass); + $loc = Bee_Framework::getClassFileLocations($providerClass); require_once $loc[0]; self::$provider = new $providerClass(); } @@ -191,7 +191,7 @@ } private static function getQualifiedKey($key) { - return (BeeFramework::getApplicationId()!==false ? BeeFramework::getApplicationId().'_' : '') . $key; + return (Bee_Framework::getApplicationId()!==false ? Bee_Framework::getApplicationId().'_' : '') . $key; } public static function clearCache() { Modified: trunk/framework/Bee/Cache/Provider/File.php =================================================================== --- trunk/framework/Bee/Cache/Provider/File.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Cache/Provider/File.php 2013-05-02 13:22:26 UTC (rev 27) @@ -81,7 +81,7 @@ if (Bee_Utils_Strings::hasText($dir) && !preg_match('#'.DIRECTORY_SEPARATOR.'$#i', $dir)) { $dir .= DIRECTORY_SEPARATOR; } - $tmpName = $dir . $this->cacheFile . (BeeFramework::getApplicationId() ? '_'.BeeFramework::getApplicationId() : ''); + $tmpName = $dir . $this->cacheFile . (Bee_Framework::getApplicationId() ? '_'.Bee_Framework::getApplicationId() : ''); return $tmpName; } Modified: trunk/framework/Bee/Context/Xml/ReaderContext.php =================================================================== --- trunk/framework/Bee/Context/Xml/ReaderContext.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Context/Xml/ReaderContext.php 2013-05-02 13:22:26 UTC (rev 27) @@ -47,7 +47,7 @@ Bee_Context_Config_IBeanDefinitionRegistry $registry, Bee_Context_Xml_Namespace_IHandlerResolver $namespaceHandlerResolver) { - $this->log = BeeFramework::getLoggerForClass(__CLASS__); + $this->log = Bee_Framework::getLoggerForClass(__CLASS__); $this->registry = $registry; $this->namespaceHandlerResolver = $namespaceHandlerResolver; Modified: trunk/framework/Bee/Context/Xml.php =================================================================== --- trunk/framework/Bee/Context/Xml.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Context/Xml.php 2013-05-02 13:22:26 UTC (rev 27) @@ -80,7 +80,7 @@ } public function getModificationTimestamp() { - if(BeeFramework::getProductionMode()) { + if(Bee_Framework::getProductionMode()) { return 0; } if($this->modificationTimestamp === false) { Copied: trunk/framework/Bee/Framework.php (from rev 25, trunk/framework/BeeFramework.php) =================================================================== --- trunk/framework/Bee/Framework.php (rev 0) +++ trunk/framework/Bee/Framework.php 2013-05-02 13:22:26 UTC (rev 27) @@ -0,0 +1,351 @@ +<?php +/* + * Copyright 2008-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Bee_Framework { + + const WEAVING_PACKAGE_PREFIX = 'Bee_'; + + const CLASS_FILE_CACHE_PREFIX = '__BeeClassFileCache_'; + + const GENERATED_CLASS_CODE_MARKER = '__CLASS_IS_GENERATED'; + + private static $beeHiveLocation; + + private static $applicationId = false; + + /** + * @var Bee_Weaving_IEnhancedClassesStore + */ + private static $enhancedClassesStore = null; + + /** + * todo: quick n dirty + * @var array + */ + private static $weavingExcludedClasses = array(); + + private static $weaveDuringClassloading = false; + + private static $missedClassNames = array(); + + private static $classFileMap; + + private static $productionMode = false; + + /** + * @param Bee_Weaving_IEnhancedClassesStore $enhancedClassesStore + */ + public static function setEnhancedClassesStore(Bee_Weaving_IEnhancedClassesStore $enhancedClassesStore) { + self::$enhancedClassesStore = $enhancedClassesStore; + } + + /** + * @return Bee_Weaving_IEnhancedClassesStore + */ + public static function getEnhancedClassesStore() { + return self::$enhancedClassesStore; + } + + public static function excludeFromWeaving($className) { + self::$weavingExcludedClasses[$className] = true; + } + + public static function setApplicationId($applicationId) { + self::$applicationId = $applicationId; + } + + public static function getApplicationId() { + return self::$applicationId; + } + + /** + * Main bootstrap method for the framework. Basically just initializes the framework classloader. + * + * @return void + */ + static function init() { + self::$beeHiveLocation = dirname(__FILE__); + self::addApplicationIncludePath(self::$beeHiveLocation); + + require_once dirname(__FILE__) . '/Cache/Manager.php'; + + spl_autoload_register(array(__CLASS__, 'autoload')); + + register_shutdown_function(array(__CLASS__, 'shutdown')); +// Bee_Cache_Manager::init(); + } + + public static function handleError($errno, $errstr, $errfile, $errline) { + error_log("HANDLING ERROR $errno"); + if((E_ERROR | E_RECOVERABLE_ERROR) & $errno) { + + error_log($errno .' : ' . $errstr); + throw new ErrorException($errstr, 0, $errno, $errfile, $errline); + } else if (E_ALL & ~E_NOTICE & ~E_WARNING & $errno) { + error_log($errno .' : ' . $errstr); + } + } + + /** + * Register application-specific include path with the framework classloader. + * + * @param String $includePath + * @return void + */ + public static function addApplicationIncludePath($includePath) { + $incPath = get_include_path(); + set_include_path($includePath . PATH_SEPARATOR . $incPath); + } + + + /** + * Main SPL autoloader function for the framework + * + * @param string $className + * @return boolean + */ + public static function autoload($className) { + + if (class_exists($className, false) || interface_exists($className, false)) { + return false; + } + + if(self::$productionMode) { + if(!is_array(self::$classFileMap)) { + self::$classFileMap = Bee_Cache_Manager::retrieve(self::CLASS_FILE_CACHE_PREFIX); + if(!is_array(self::$classFileMap)) { + self::$classFileMap = array(); + } + } + + if(array_key_exists($className, self::$classFileMap)) { + $cachedPath = self::$classFileMap[$className]; + if($cachedPath === self::GENERATED_CLASS_CODE_MARKER) { + return false; + } + + include $cachedPath; + if (class_exists($className, false) || interface_exists($className, false)) { + return false; + } + } + + if (class_exists($className)) { + array_push(self::$missedClassNames, $className); + } + // TODO: What to do if class-loading fails?? + } + + if(self::$enhancedClassesStore != null && !array_key_exists($className, self::$weavingExcludedClasses) && substr($className, 0, strlen(self::WEAVING_PACKAGE_PREFIX)) != self::WEAVING_PACKAGE_PREFIX) { + // possibly a woven class + + if(self::$enhancedClassesStore->loadClass($className)) { + return true; + } + + if(self::$weaveDuringClassloading) { + require_once dirname(__FILE__) . 'Bee/Weaving/Enhancer.php'; + + $enhancer = new Bee_Weaving_Enhancer($className); + if($enhancer->createEnhancedClass() !== false) { + return true; + } + } + } + + foreach(self::getClassFileLocations($className) as $loc) { + include $loc; + if (class_exists($className, false) || interface_exists($className, false)) { + return true; + } + } + + return false; + } + + public static function getClassFileLocations($className) { + return array( + str_replace('_', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, $className)) . '.php', + $className . '.php' + ); + } + + public static function shutdown() { + if(self::$productionMode) { + foreach(self::$missedClassNames as $missedClassName) { + $ref = new ReflectionClass($missedClassName); + self::$classFileMap[$missedClassName] = file_exists($ref->getFileName()) ? $ref->getFileName() : self::GENERATED_CLASS_CODE_MARKER; + } + Bee_Cache_Manager::store(self::CLASS_FILE_CACHE_PREFIX, self::$classFileMap); + } + + Bee_Cache_Manager::shutdown(); + } + + /** + * Convenience method, dispatches current request using a dispatcher context configured from the + * given set of XML config locations. + * + * @param String $configLocation comma-separated string XML config files to load the bean definitions from + * @return void + */ + public static function dispatchRequestUsingXmlContext($configLocation) { + try { + Bee_Utils_Assert::notNull($configLocation); + $ctx = new Bee_Context_Xml($configLocation); + self::dispatchRequestUsingContext($ctx); + } catch (Exception $e) { + self::handleException($e); + } + } + + /** + * Convenience method, dispatches current request using the given dispatcher context. + * + * @param Bee_IContext $ctx + * @return void + */ + public static function dispatchRequestUsingContext(Bee_IContext $ctx) { + try { + Bee_Utils_Assert::notNull($ctx); + $dp = new Bee_MVC_Dispatcher($ctx); + $dp->dispatch(); + } catch (Exception $e) { + self::handleException($e); + } + } + + public static function handleException(Exception $e) { + $topLevelMessage = $e->getMessage(); + + $js = '<script>'."\n"; + $js .= 'function toggle(event) {'."\n"; + + $js .= 'console.dir(event)'."\n"; + $js .= 'event.cancelBubble = true;'."\n"; + $js .= 'event.stopImmediatePropagation();'."\n"; + $js .= 'var ele = event.target.nextElementSibling;'."\n"; + $js .= 'if (ele.style.display == "none") {'."\n"; + $js .= 'ele.style.display = "block";'."\n"; + $js .= '} else {'."\n"; + $js .= 'ele.style.display = "none";'."\n"; + $js .= '}'."\n"; + $js .= '}'."\n"; + $js .= '</script>'."\n"; + + echo $js; + + + $excCnt = 0; + + while (!is_null($e)) { + $excCnt += 1; + echo '<div style="padding: 0 0 2px 0; margin: 0 2px 10px 2px; border: solid 1px #666;">'; + echo '<div style="background-color: #666; color: #fff; margin-bottom: 5px; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">'.$excCnt.'. Exception: "'.get_class($e).'"</div>'; + + echo '<div>'; + echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; + echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Message</div>'; + echo '<div style="padding: 5px;">'; + echo $e->getMessage(); + echo '</div>'; + echo '</div>'; + + echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; + echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Stracktrace</div>'; + echo '<div style="padding: 5px; font-size: 10px; display: none;">'; + self::printArray($e->getTrace()); + echo '</div>'; + echo '</div>'; + echo '</div>'; + echo '</div>'; + + +// echo 'Root-Cause: '; + if ($e instanceof Bee_Exceptions_Base) { + $e = $e->getCause(); + } else { + $e = null; + } + + } + + error_log($topLevelMessage, E_USER_WARNING); + } + + private static function printSpaces($count) { + for ($i=0; $i<$count; $i++) { + echo ' '; + } + } + + public static function printArray($output, $level=0) { + if (is_array($output)) { + foreach ($output as $key => $value) { + self::printSpaces($level*4); + echo $key; + if (is_array($value)) { + echo '<br/>'; + } + self::printArray($value, $level+1); + } + } else { + self::printSpaces($level*4); + if (is_object($output)) { + echo 'Object - Class: '; + echo get_class($output); + } else { + echo $output; + } + echo '<br/>'; + } + if ($level==1) { + echo '<hr/>'; + } + } + + + /** + * The applicationName is an identifier that can be used + * to uniquely identify the application - e.g. in the + * SessionContext - even from a different entry page. + * + * @return String + */ + public static final function getApplicationName() { + return self::$applicationName; + } + + public static function setProductionMode($productionMode) { + self::$productionMode = $productionMode; + } + + public static function getProductionMode() { + return self::$productionMode; + } + + public static function getLoggerForClass($className) { + return Logger::getLogger(str_replace('_', '.', str_replace('\\', '.', $className))); + } +} + +Bee_Framework::init(); + +//require_once dirname(__FILE__) . '/Utils/ITypeDefinitions.php'; + +interface TYPES extends Bee_Utils_ITypeDefinitions { +} \ No newline at end of file Modified: trunk/framework/Bee/MVC/Controller/Multiaction/MethodNameResolver/AnnotationBased.php =================================================================== --- trunk/framework/Bee/MVC/Controller/Multiaction/MethodNameResolver/AnnotationBased.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/MVC/Controller/Multiaction/MethodNameResolver/AnnotationBased.php 2013-05-02 13:22:26 UTC (rev 27) @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use Addendum\ReflectionAnnotatedClass; /** * Method name resolver implementation based on Addendum Annotations. This is a very powerful implementation, capable of invoking different @@ -68,7 +69,7 @@ $delegateClassName = get_class($this->getController()->getDelegate()); - if(BeeFramework::getProductionMode()) { + if(Bee_Framework::getProductionMode()) { $this->methodResolvers = Bee_Cache_Manager::retrieve(self::CACHE_KEY_PREFIX.$delegateClassName); } @@ -110,7 +111,7 @@ } } - if(BeeFramework::getProductionMode()) { + if(Bee_Framework::getProductionMode()) { Bee_Cache_Manager::store(self::CACHE_KEY_PREFIX.$delegateClassName, $this->methodResolvers); } } Modified: trunk/framework/Bee/MVC/Controller/Multiaction/RequestHandler.php =================================================================== --- trunk/framework/Bee/MVC/Controller/Multiaction/RequestHandler.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/MVC/Controller/Multiaction/RequestHandler.php 2013-05-02 13:22:26 UTC (rev 27) @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use Addendum\Annotation; /** * Addendum annotation for the annotation-based method name resolver. Modified: trunk/framework/Bee/Security/Annotations/SecuredMethodDefinitionSource.php =================================================================== --- trunk/framework/Bee/Security/Annotations/SecuredMethodDefinitionSource.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Security/Annotations/SecuredMethodDefinitionSource.php 2013-05-02 13:22:26 UTC (rev 27) @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use Addendum\ReflectionAnnotatedClass; /** * Created by IntelliJ IDEA. Modified: trunk/framework/Bee/Weaving/Enhancer.php =================================================================== --- trunk/framework/Bee/Weaving/Enhancer.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/Bee/Weaving/Enhancer.php 2013-05-02 13:22:26 UTC (rev 27) @@ -98,15 +98,15 @@ return $classNameToCreate; } - if(!BeeFramework::getEnhancedClassesStore()->hasStoredClass($classNameToCreate)) { + if(!Bee_Framework::getEnhancedClassesStore()->hasStoredClass($classNameToCreate)) { $incPaths = explode(PATH_SEPARATOR, get_include_path()); - foreach(BeeFramework::getClassFileLocations($templateClassName) as $loc) { + foreach(Bee_Framework::getClassFileLocations($templateClassName) as $loc) { foreach($incPaths as $incPath) { $classFile = $incPath . DIRECTORY_SEPARATOR . $loc; if(file_exists($classFile)) { $this->enhanceClass(file_get_contents($classFile)); - BeeFramework::getEnhancedClassesStore()->storeClass($classNameToCreate, $this->toSourceCode()); + Bee_Framework::getEnhancedClassesStore()->storeClass($classNameToCreate, $this->toSourceCode()); // file_put_contents($enhancedClassLocation, $this->toSourceCode()); break 2; } @@ -114,7 +114,7 @@ } } - if (BeeFramework::getEnhancedClassesStore()->loadClass($classNameToCreate)) { + if (Bee_Framework::getEnhancedClassesStore()->loadClass($classNameToCreate)) { return $classNameToCreate; } return false; Deleted: trunk/framework/BeeFramework.php =================================================================== --- trunk/framework/BeeFramework.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/framework/BeeFramework.php 2013-05-02 13:22:26 UTC (rev 27) @@ -1,353 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//require_once dirname(__FILE__).'/../libs/addendum/annotations.php'; - -class BeeFramework { - - const WEAVING_PACKAGE_PREFIX = 'Bee_'; - - const CLASS_FILE_CACHE_PREFIX = '__BeeClassFileCache_'; - - const GENERATED_CLASS_CODE_MARKER = '__CLASS_IS_GENERATED'; - - private static $beeHiveLocation; - - private static $applicationId = false; - - /** - * @var Bee_Weaving_IEnhancedClassesStore - */ - private static $enhancedClassesStore = null; - - /** - * todo: quick n dirty - * @var array - */ - private static $weavingExcludedClasses = array(); - - private static $weaveDuringClassloading = false; - - private static $missedClassNames = array(); - - private static $classFileMap; - - private static $productionMode = false; - - /** - * @param Bee_Weaving_IEnhancedClassesStore $enhancedClassesStore - */ - public static function setEnhancedClassesStore(Bee_Weaving_IEnhancedClassesStore $enhancedClassesStore) { - self::$enhancedClassesStore = $enhancedClassesStore; - } - - /** - * @return Bee_Weaving_IEnhancedClassesStore - */ - public static function getEnhancedClassesStore() { - return self::$enhancedClassesStore; - } - - public static function excludeFromWeaving($className) { - self::$weavingExcludedClasses[$className] = true; - } - - public static function setApplicationId($applicationId) { - self::$applicationId = $applicationId; - } - - public static function getApplicationId() { - return self::$applicationId; - } - - /** - * Main bootstrap method for the framework. Basically just initializes the framework classloader. - * - * @return void - */ - static function init() { - self::$beeHiveLocation = dirname(__FILE__); - self::addApplicationIncludePath(self::$beeHiveLocation); - - require_once dirname(__FILE__).'/Bee/Cache/Manager.php'; - - spl_autoload_register(array(__CLASS__, 'autoload')); - - register_shutdown_function(array(__CLASS__, 'shutdown')); -// Bee_Cache_Manager::init(); - } - - public static function handleError($errno, $errstr, $errfile, $errline) { - error_log("HANDLING ERROR $errno"); - if((E_ERROR | E_RECOVERABLE_ERROR) & $errno) { - - error_log($errno .' : ' . $errstr); - throw new ErrorException($errstr, 0, $errno, $errfile, $errline); - } else if (E_ALL & ~E_NOTICE & ~E_WARNING & $errno) { - error_log($errno .' : ' . $errstr); - } - } - - /** - * Register application-specific include path with the framework classloader. - * - * @param String $includePath - * @return void - */ - public static function addApplicationIncludePath($includePath) { - $incPath = get_include_path(); - set_include_path($includePath . PATH_SEPARATOR . $incPath); - } - - - /** - * Main SPL autoloader function for the framework - * - * @param string $className - * @return boolean - */ - public static function autoload($className) { - - if (class_exists($className, false) || interface_exists($className, false)) { - return false; - } - - if(self::$productionMode) { - if(!is_array(self::$classFileMap)) { - self::$classFileMap = Bee_Cache_Manager::retrieve(self::CLASS_FILE_CACHE_PREFIX); - if(!is_array(self::$classFileMap)) { - self::$classFileMap = array(); - } - } - - if(array_key_exists($className, self::$classFileMap)) { - $cachedPath = self::$classFileMap[$className]; - if($cachedPath === self::GENERATED_CLASS_CODE_MARKER) { - return false; - } - - include $cachedPath; - if (class_exists($className, false) || interface_exists($className, false)) { - return false; - } - } - - if (class_exists($className)) { - array_push(self::$missedClassNames, $className); - } - // TODO: What to do if class-loading fails?? - } - - if(self::$enhancedClassesStore != null && !array_key_exists($className, self::$weavingExcludedClasses) && substr($className, 0, strlen(self::WEAVING_PACKAGE_PREFIX)) != self::WEAVING_PACKAGE_PREFIX) { - // possibly a woven class - - if(self::$enhancedClassesStore->loadClass($className)) { - return true; - } - - if(self::$weaveDuringClassloading) { - require_once dirname(__FILE__).'Bee/Weaving/Enhancer.php'; - - $enhancer = new Bee_Weaving_Enhancer($className); - if($enhancer->createEnhancedClass() !== false) { - return true; - } - } - } - - foreach(self::getClassFileLocations($className) as $loc) { - include $loc; - if (class_exists($className, false) || interface_exists($className, false)) { - return true; - } - } - - return false; - } - - public static function getClassFileLocations($className) { - return array( - str_replace('_', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, $className)) . '.php', - $className . '.php' - ); - } - - public static function shutdown() { - if(self::$productionMode) { - foreach(self::$missedClassNames as $missedClassName) { - $ref = new ReflectionClass($missedClassName); - self::$classFileMap[$missedClassName] = file_exists($ref->getFileName()) ? $ref->getFileName() : self::GENERATED_CLASS_CODE_MARKER; - } - Bee_Cache_Manager::store(self::CLASS_FILE_CACHE_PREFIX, self::$classFileMap); - } - - Bee_Cache_Manager::shutdown(); - } - - /** - * Convenience method, dispatches current request using a dispatcher context configured from the - * given set of XML config locations. - * - * @param String $configLocation comma-separated string XML config files to load the bean definitions from - * @return void - */ - public static function dispatchRequestUsingXmlContext($configLocation) { - try { - Bee_Utils_Assert::notNull($configLocation); - $ctx = new Bee_Context_Xml($configLocation); - self::dispatchRequestUsingContext($ctx); - } catch (Exception $e) { - self::handleException($e); - } - } - - /** - * Convenience method, dispatches current request using the given dispatcher context. - * - * @param Bee_IContext $ctx - * @return void - */ - public static function dispatchRequestUsingContext(Bee_IContext $ctx) { - try { - Bee_Utils_Assert::notNull($ctx); - $dp = new Bee_MVC_Dispatcher($ctx); - $dp->dispatch(); - } catch (Exception $e) { - self::handleException($e); - } - } - - public static function handleException(Exception $e) { - $topLevelMessage = $e->getMessage(); - - $js = '<script>'."\n"; - $js .= 'function toggle(event) {'."\n"; - - $js .= 'console.dir(event)'."\n"; - $js .= 'event.cancelBubble = true;'."\n"; - $js .= 'event.stopImmediatePropagation();'."\n"; - $js .= 'var ele = event.target.nextElementSibling;'."\n"; - $js .= 'if (ele.style.display == "none") {'."\n"; - $js .= 'ele.style.display = "block";'."\n"; - $js .= '} else {'."\n"; - $js .= 'ele.style.display = "none";'."\n"; - $js .= '}'."\n"; - $js .= '}'."\n"; - $js .= '</script>'."\n"; - - echo $js; - - - $excCnt = 0; - - while (!is_null($e)) { - $excCnt += 1; - echo '<div style="padding: 0 0 2px 0; margin: 0 2px 10px 2px; border: solid 1px #666;">'; - echo '<div style="background-color: #666; color: #fff; margin-bottom: 5px; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">'.$excCnt.'. Exception: "'.get_class($e).'"</div>'; - - echo '<div>'; - echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; - echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Message</div>'; - echo '<div style="padding: 5px;">'; - echo $e->getMessage(); - echo '</div>'; - echo '</div>'; - - echo '<div style="padding: 0 0 2px 0; margin: 10px; border: solid 1px #aaa; color: #aaa;">'; - echo '<div style="background-color: #aaa; color: #666; padding: 5px; cursor: pointer;" onclick="javascript:toggle(event);">Stracktrace</div>'; - echo '<div style="padding: 5px; font-size: 10px; display: none;">'; - self::printArray($e->getTrace()); - echo '</div>'; - echo '</div>'; - echo '</div>'; - echo '</div>'; - - -// echo 'Root-Cause: '; - if ($e instanceof Bee_Exceptions_Base) { - $e = $e->getCause(); - } else { - $e = null; - } - - } - - error_log($topLevelMessage, E_USER_WARNING); - } - - private static function printSpaces($count) { - for ($i=0; $i<$count; $i++) { - echo ' '; - } - } - - public static function printArray($output, $level=0) { - if (is_array($output)) { - foreach ($output as $key => $value) { - self::printSpaces($level*4); - echo $key; - if (is_array($value)) { - echo '<br/>'; - } - self::printArray($value, $level+1); - } - } else { - self::printSpaces($level*4); - if (is_object($output)) { - echo 'Object - Class: '; - echo get_class($output); - } else { - echo $output; - } - echo '<br/>'; - } - if ($level==1) { - echo '<hr/>'; - } - } - - - /** - * The applicationName is an identifier that can be used - * to uniquely identify the application - e.g. in the - * SessionContext - even from a different entry page. - * - * @return String - */ - public static final function getApplicationName() { - return self::$applicationName; - } - - public static function setProductionMode($productionMode) { - self::$productionMode = $productionMode; - } - - public static function getProductionMode() { - return self::$productionMode; - } - - public static function getLoggerForClass($className) { - return Logger::getLogger(str_replace('_', '.', str_replace('\\', '.', $className))); - } -} - -BeeFramework::init(); - -require_once dirname(__FILE__).'/Bee/Utils/ITypeDefinitions.php'; - -interface TYPES extends Bee_Utils_ITypeDefinitions { -} \ No newline at end of file Copied: trunk/framework/composer.json (from rev 26, trunk/composer.json) =================================================================== --- trunk/framework/composer.json (rev 0) +++ trunk/framework/composer.json 2013-05-02 13:22:26 UTC (rev 27) @@ -0,0 +1,27 @@ +{ + "name": "bee-framework/bee-framework", + "type": "library", + "description": "Bee Framework - PHP 5 DI/IoC application framework", + "keywords": ["framework"], + "homepage": "http://sourceforge.net/projects/beeframework/", + "license": "Apache License V2.0", + "authors": [ + { + "name": "Michael Plomer", + "email": "mic...@it..." + }, + { + "name": "Benjamin Hartmann" + } + ], + "require": { + "php": ">=5.2.3", + "niktux/addendum": "0.4.1", + "apache/log4php": "2.3.0" + }, + "autoload": { + "psr-0": { + "Bee": "framework/" + } + } +} \ No newline at end of file Property changes on: trunk/framework/composer.json ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Modified: trunk/tests/bootstrap.php =================================================================== --- trunk/tests/bootstrap.php 2013-05-02 10:50:42 UTC (rev 26) +++ trunk/tests/bootstrap.php 2013-05-02 13:22:26 UTC (rev 27) @@ -22,6 +22,6 @@ */ require_once '../libs/addendum-0.4.1/annotations.php'; -require_once '../libs/log4php-2.1.0/Logger.php'; -require_once '../framework/BeeFramework.php'; +require_once '../libs/apache-log4php-2.3.0/Logger.php'; +require_once '../framework/Bee/Framework.php'; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-02 10:50:47
|
Revision: 26 http://sourceforge.net/p/beeframework/code/26 Author: m_plomer Date: 2013-05-02 10:50:42 +0000 (Thu, 02 May 2013) Log Message: ----------- - updated composer.json Modified Paths: -------------- trunk/composer.json Modified: trunk/composer.json =================================================================== --- trunk/composer.json 2013-05-02 10:40:45 UTC (rev 25) +++ trunk/composer.json 2013-05-02 10:50:42 UTC (rev 26) @@ -18,11 +18,5 @@ "php": ">=5.2.3", "niktux/addendum": "0.4.1", "apache/log4php": "2.3.0" - }//, -// "autoload": { -// "classmap": [ -// "distribution/libs/Smarty.class.php", -// "distribution/libs/SmartyBC.class.php" -// ] -// } + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-02 10:40:48
|
Revision: 25 http://sourceforge.net/p/beeframework/code/25 Author: m_plomer Date: 2013-05-02 10:40:45 +0000 (Thu, 02 May 2013) Log Message: ----------- - PHP 5.3 class loading - minor fixes Modified Paths: -------------- trunk/framework/Bee/Cache/Manager.php trunk/framework/Bee/Context/Xml/ReaderContext.php trunk/framework/Bee/MVC/View/Smarty3Adapter.php trunk/framework/BeeFramework.php Added Paths: ----------- trunk/composer.json Added: trunk/composer.json =================================================================== --- trunk/composer.json (rev 0) +++ trunk/composer.json 2013-05-02 10:40:45 UTC (rev 25) @@ -0,0 +1,28 @@ +{ + "name": "bee-framework/bee-framework", + "type": "library", + "description": "Bee Framework - PHP 5 DI/IoC application framework", + "keywords": ["framework"], + "homepage": "http://sourceforge.net/projects/beeframework/", + "license": "Apache License V2.0", + "authors": [ + { + "name": "Michael Plomer", + "email": "mic...@it..." + }, + { + "name": "Benjamin Hartmann" + } + ], + "require": { + "php": ">=5.2.3", + "niktux/addendum": "0.4.1", + "apache/log4php": "2.3.0" + }//, +// "autoload": { +// "classmap": [ +// "distribution/libs/Smarty.class.php", +// "distribution/libs/SmartyBC.class.php" +// ] +// } +} \ No newline at end of file Property changes on: trunk/composer.json ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Modified: trunk/framework/Bee/Cache/Manager.php =================================================================== --- trunk/framework/Bee/Cache/Manager.php 2013-05-02 10:34:07 UTC (rev 24) +++ trunk/framework/Bee/Cache/Manager.php 2013-05-02 10:40:45 UTC (rev 25) @@ -135,8 +135,9 @@ public static function &retrieveCachable(Bee_Cache_ICachableResource $resource, $returnInfoArray = false) { if(is_null(self::$provider)) { // no cache provider found, no caching or unsupported cache type installed - $data =& $resource->createContent(); - return $returnInfoArray ? array(self::INFO_NO_CACHE_KEY => true, self::INFO_CACHE_HIT_KEY => false, self::INFO_IN_CACHE_SINCE_KEY => false, self::INFO_DATA_KEY => $data) : $data; + $data =& $resource->createContent(); + $result = $returnInfoArray ? array(self::INFO_NO_CACHE_KEY => true, self::INFO_CACHE_HIT_KEY => false, self::INFO_IN_CACHE_SINCE_KEY => false, self::INFO_DATA_KEY => &$data) : $data; + return $result; } // caching supported, check if in cache and not stale @@ -197,4 +198,3 @@ return self::$provider->clearCache(); } } -?> \ No newline at end of file Modified: trunk/framework/Bee/Context/Xml/ReaderContext.php =================================================================== --- trunk/framework/Bee/Context/Xml/ReaderContext.php 2013-05-02 10:34:07 UTC (rev 24) +++ trunk/framework/Bee/Context/Xml/ReaderContext.php 2013-05-02 10:40:45 UTC (rev 25) @@ -47,7 +47,7 @@ Bee_Context_Config_IBeanDefinitionRegistry $registry, Bee_Context_Xml_Namespace_IHandlerResolver $namespaceHandlerResolver) { - $this->log = Logger::getLogger(__CLASS__); + $this->log = BeeFramework::getLoggerForClass(__CLASS__); $this->registry = $registry; $this->namespaceHandlerResolver = $namespaceHandlerResolver; @@ -87,4 +87,3 @@ $this->log->info($message); } } -?> \ No newline at end of file Modified: trunk/framework/Bee/MVC/View/Smarty3Adapter.php =================================================================== --- trunk/framework/Bee/MVC/View/Smarty3Adapter.php 2013-05-02 10:34:07 UTC (rev 24) +++ trunk/framework/Bee/MVC/View/Smarty3Adapter.php 2013-05-02 10:40:45 UTC (rev 25) @@ -15,7 +15,11 @@ * limitations under the License. */ -class Bee_MVC_View_Smarty3Adapter extends Smarty implements Bee_Context_Config_IInitializingBean { +/** + * Class Bee_MVC_View_Smarty3Adapter + * @deprecated probably not needed for Smarty3? + */ +class Bee_MVC_View_Smarty3Adapter extends Smarty /*implements Bee_Context_Config_IInitializingBean*/ { // /** // * @@ -92,5 +96,4 @@ $this->config_load($configFile); } } -} -?> \ No newline at end of file +} \ No newline at end of file Modified: trunk/framework/BeeFramework.php =================================================================== --- trunk/framework/BeeFramework.php 2013-05-02 10:34:07 UTC (rev 24) +++ trunk/framework/BeeFramework.php 2013-05-02 10:40:45 UTC (rev 25) @@ -171,7 +171,6 @@ foreach(self::getClassFileLocations($className) as $loc) { include $loc; - if (class_exists($className, false) || interface_exists($className, false)) { return true; } @@ -182,7 +181,7 @@ public static function getClassFileLocations($className) { return array( - str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php', + str_replace('_', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, $className)) . '.php', $className . '.php' ); } @@ -215,13 +214,13 @@ self::handleException($e); } } - - /** - * Convenience method, dispatches current request using the given dispatcher context. - * - * @param String $configLocation comma-separated string XML config files to load the bean definitions from - * @return void - */ + + /** + * Convenience method, dispatches current request using the given dispatcher context. + * + * @param Bee_IContext $ctx + * @return void + */ public static function dispatchRequestUsingContext(Bee_IContext $ctx) { try { Bee_Utils_Assert::notNull($ctx); @@ -340,6 +339,10 @@ public static function getProductionMode() { return self::$productionMode; } + + public static function getLoggerForClass($className) { + return Logger::getLogger(str_replace('_', '.', str_replace('\\', '.', $className))); + } } BeeFramework::init(); @@ -347,5 +350,4 @@ require_once dirname(__FILE__).'/Bee/Utils/ITypeDefinitions.php'; interface TYPES extends Bee_Utils_ITypeDefinitions { -} -?> \ No newline at end of file +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-05-02 10:34:09
|
Revision: 24 http://sourceforge.net/p/beeframework/code/24 Author: m_plomer Date: 2013-05-02 10:34:07 +0000 (Thu, 02 May 2013) Log Message: ----------- - ignoring .idea directory Property Changed: ---------------- trunk/ Index: trunk =================================================================== --- trunk 2013-04-30 20:10:29 UTC (rev 23) +++ trunk 2013-05-02 10:34:07 UTC (rev 24) Property changes on: trunk ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +.idea This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2013-04-30 20:10:32
|
Revision: 23 http://sourceforge.net/p/beeframework/code/23 Author: m_plomer Date: 2013-04-30 20:10:29 +0000 (Tue, 30 Apr 2013) Log Message: ----------- - merge with private version Removed Paths: ------------- trunk/framework/Bee/Beans/PropertyEditor/Float.php trunk/framework/Bee/Beans/PropertyEditor/Integer.php trunk/framework/Bee/Beans/ValueHolder.php Deleted: trunk/framework/Bee/Beans/PropertyEditor/Float.php =================================================================== --- trunk/framework/Bee/Beans/PropertyEditor/Float.php 2013-04-30 19:47:54 UTC (rev 22) +++ trunk/framework/Bee/Beans/PropertyEditor/Float.php 2013-04-30 20:10:29 UTC (rev 23) @@ -1,49 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Enter description here... - * - * @author Benjamin Hartmann - */ -class Bee_Beans_PropertyEditor_Float implements Bee_Beans_IPropertyEditor { - - /** - * Enter description here... - * - * @param int $value - * @return String - */ - public function toString($value) { - Bee_Utils_Assert::isTrue(is_float($value) || is_int($value)); - return strval($value); - } - - - - /** - * Enter description here... - * - * @param String $value - * @return int - */ - public function fromString($value) { - Bee_Utils_Assert::isTrue(is_string($value) && is_numeric($value)); - return floatval($value); - } -} -?> \ No newline at end of file Deleted: trunk/framework/Bee/Beans/PropertyEditor/Integer.php =================================================================== --- trunk/framework/Bee/Beans/PropertyEditor/Integer.php 2013-04-30 19:47:54 UTC (rev 22) +++ trunk/framework/Bee/Beans/PropertyEditor/Integer.php 2013-04-30 20:10:29 UTC (rev 23) @@ -1,54 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Enter description here... - * - * @author Benjamin Hartmann - */ -class Bee_Beans_PropertyEditor_Integer implements Bee_Beans_IPropertyEditor { - - /** - * Enter description here... - * - * @param int $value - * @return String - */ - public function toString($value) { - Bee_Utils_Assert::isTrue(is_int($value)); - return strval($value); - } - - - - /** - * Enter description here... - * - * @param String $value - * @return int - */ - public function fromString($value) { - Bee_Utils_Assert::isTrue(is_string($value) && is_numeric($value)); - $fResult = floatval($value); - $iResult = intval($fResult); - if ($iResult!=$fResult) { - throw new Exception('Cannot convert type '.gettype($value).' to integer.'); - } - return $iResult; - } -} -?> \ No newline at end of file Deleted: trunk/framework/Bee/Beans/ValueHolder.php =================================================================== --- trunk/framework/Bee/Beans/ValueHolder.php 2013-04-30 19:47:54 UTC (rev 22) +++ trunk/framework/Bee/Beans/ValueHolder.php 2013-04-30 20:10:29 UTC (rev 23) @@ -1,46 +0,0 @@ -<?php -/* - * Copyright 2008-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class Bee_Beans_ValueHolder { - - /** - * Enter description here... - * - * @var mixed - */ - private $value; - - /** - * Enter description here... - * - * @return mixed - */ - public final function getValue() { - return $this->value; - } - - /** - * Enter description here... - * - * @param mixed $value - * @return void - */ - public final function setValue($value) { - $this->value = $value; - } -} -?> \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2011-12-12 21:41:26
|
Revision: 20 http://beeframework.svn.sourceforge.net/beeframework/?rev=20&view=rev Author: m_plomer Date: 2011-12-12 21:41:20 +0000 (Mon, 12 Dec 2011) Log Message: ----------- Modified Paths: -------------- trunk/tests/Bee/Cache/Provider/AbstractSerializingTest.php trunk/tests/Bee/Cache/Provider/FileTest.php Modified: trunk/tests/Bee/Cache/Provider/AbstractSerializingTest.php =================================================================== --- trunk/tests/Bee/Cache/Provider/AbstractSerializingTest.php 2011-12-12 21:40:16 UTC (rev 19) +++ trunk/tests/Bee/Cache/Provider/AbstractSerializingTest.php 2011-12-12 21:41:20 UTC (rev 20) @@ -129,6 +129,12 @@ $this->assertEquals('bar', $this->provider->retrieve('foo')); } + /** + * @test + */ + public function incomplete() { + $this->markTestIncomplete(); + } } Modified: trunk/tests/Bee/Cache/Provider/FileTest.php =================================================================== --- trunk/tests/Bee/Cache/Provider/FileTest.php 2011-12-12 21:40:16 UTC (rev 19) +++ trunk/tests/Bee/Cache/Provider/FileTest.php 2011-12-12 21:41:20 UTC (rev 20) @@ -83,4 +83,11 @@ // delete file here } + /** + * @test + */ + public function incomplete() { + $this->markTestIncomplete(); + } + } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2011-12-12 21:40:22
|
Revision: 19 http://beeframework.svn.sourceforge.net/beeframework/?rev=19&view=rev Author: m_plomer Date: 2011-12-12 21:40:16 +0000 (Mon, 12 Dec 2011) Log Message: ----------- Modified Paths: -------------- trunk/tests/Bee/Cache/Provider/FileTest.php Modified: trunk/tests/Bee/Cache/Provider/FileTest.php =================================================================== --- trunk/tests/Bee/Cache/Provider/FileTest.php 2011-12-12 21:36:05 UTC (rev 18) +++ trunk/tests/Bee/Cache/Provider/FileTest.php 2011-12-12 21:40:16 UTC (rev 19) @@ -21,7 +21,7 @@ * Time: 15:16 */ -class Bee_Utils_AssertTest extends PHPUnit_Framework_TestCase { +class Bee_Cache_Provider_FileTest extends PHPUnit_Framework_TestCase { // /** // * Initialize the cache provider if necessary. Called once per request, before the first cache access is made. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2011-12-12 19:05:54
|
Revision: 15 http://beeframework.svn.sourceforge.net/beeframework/?rev=15&view=rev Author: m_plomer Date: 2011-12-12 19:05:48 +0000 (Mon, 12 Dec 2011) Log Message: ----------- Property Changed: ---------------- trunk/libs/ Property changes on: trunk/libs ___________________________________________________________________ Modified: svn:externals - log4php-2.1.0 https://svn.apache.org/repos/asf/logging/log4php/tags/apache-log4php-2.1.0/src/main/php addendum-0.4.1 http://svn.iter8.de/bee_dev/vendor/addendum-0.4.1 php-aop http://php-aop.googlecode.com/svn/trunk/aop + log4php-2.1.0 https://svn.apache.org/repos/asf/logging/log4php/tags/apache-log4php-2.1.0/src/main/php php-aop http://php-aop.googlecode.com/svn/trunk/aop This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_p...@us...> - 2011-12-12 18:42:20
|
Revision: 13 http://beeframework.svn.sourceforge.net/beeframework/?rev=13&view=rev Author: m_plomer Date: 2011-12-12 18:42:14 +0000 (Mon, 12 Dec 2011) Log Message: ----------- Property Changed: ---------------- trunk/libs/ Property changes on: trunk/libs ___________________________________________________________________ Modified: svn:externals - log4php-2.1.0 https://svn.apache.org/repos/asf/logging/log4php/tags/apache-log4php-2.1.0/src/main/php + log4php-2.1.0 https://svn.apache.org/repos/asf/logging/log4php/tags/apache-log4php-2.1.0/src/main/php addendum-0.4.1 http://svn.iter8.de/bee_dev/vendor/addendum-0.4.1 php-aop http://php-aop.googlecode.com/svn/trunk/aop This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |