From efb2a5ea7db5ac4c7d52bc7bcb126aba3bd91563 Mon Sep 17 00:00:00 2001 From: drigato Date: Wed, 23 Jul 2014 15:34:00 -0400 Subject: [PATCH] CC-5895: Upgrade Propel to 1.7 Remove propel library from repo --- airtime_mvc/library/propel/CHANGELOG | 107 - airtime_mvc/library/propel/INSTALL | 4 - airtime_mvc/library/propel/LICENSE | 19 - airtime_mvc/library/propel/WHATS_NEW | 807 ---- .../propel/contrib/dbd2propel/dbd2propel.xsl | 381 -- .../propel/contrib/dbd2propel/transform.php | 21 - .../library/propel/contrib/pat/patForms.php | 2784 ----------- .../pat/patForms/Creator/Definition.php | 42 - .../contrib/pat/patForms/Creator/Propel.php | 132 - .../patForms/Creator/_propel_creator_test.php | 201 - .../pat/patForms/Datasource/Propel.php | 70 - .../contrib/pat/patForms/Definition.php | 122 - .../pat/patForms/Definition/Propel.php | 165 - .../propel/contrib/pat/patForms/Element.php | 1954 -------- .../propel/contrib/pat/patForms/Rule.php | 340 -- .../contrib/pat/patForms/Rule/Match.php | 163 - .../contrib/pat/patForms/Rule/MaxLength.php | 161 - .../contrib/pat/patForms/Rule/MaxValue.php | 163 - .../contrib/pat/patForms/Rule/MinLength.php | 161 - .../contrib/pat/patForms/Rule/MinValue.php | 165 - .../contrib/pat/patForms/Rule/NotMatch.php | 163 - .../contrib/pat/patForms/Rule/ValidValues.php | 182 - .../contrib/pat/patForms/Storage/Propel.php | 146 - .../contrib/pat/patForms/res/form.dynamic.tpl | 94 - .../pat/patForms/res/mysql-dump.bookstore.sql | 10 - .../pat/patForms_Storage_Propel_test.php | 97 - .../propel/contrib/pat/patTemplate.php | 2378 --------- .../pear/HTML_QuickForm_Propel/Propel.php | 909 ---- .../Structures_DataGrid_Propel/Propel.php | 352 -- .../propel/docs/behavior/aggregate_column.txt | 130 - .../behavior/alternative_coding_standards.txt | 89 - .../propel/docs/behavior/auto_add_pk.txt | 73 - .../propel/docs/behavior/nested_set.txt | 370 -- .../propel/docs/behavior/query_cache.txt | 103 - .../propel/docs/behavior/sluggable.txt | 135 - .../propel/docs/behavior/soft_delete.txt | 116 - .../library/propel/docs/behavior/sortable.txt | 285 -- .../propel/docs/behavior/timestampable.txt | 92 - airtime_mvc/library/propel/docs/build.xml | 34 - .../propel/docs/cookbook/Add-Custom-SQL.txt | 34 - .../propel/docs/cookbook/Copying-Objects.txt | 47 - .../docs/cookbook/Customizing-Build.txt | 153 - .../docs/cookbook/Existing-Database.txt | 95 - .../propel/docs/cookbook/LOB-Columns.txt | 73 - .../propel/docs/cookbook/Master-Slave.txt | 94 - .../propel/docs/cookbook/Multi-Component.txt | 297 -- .../propel/docs/cookbook/Namespaces.txt | 133 - .../propel/docs/cookbook/Nested-Set.txt | 183 - .../docs/cookbook/Runtime-Introspection.txt | 164 - .../propel/docs/cookbook/Writing-Behavior.txt | 424 -- .../propel/docs/guide/01-Installation.txt | 164 - .../propel/docs/guide/02-BuildTime.txt | 350 -- .../propel/docs/guide/03-Basic-CRUD.txt | 319 -- .../propel/docs/guide/04-Relationships.txt | 386 -- .../propel/docs/guide/05-Validators.txt | 253 - .../propel/docs/guide/06-Transactions.txt | 291 -- .../propel/docs/guide/07-Behaviors.txt | 280 -- .../library/propel/docs/guide/08-Logging.txt | 448 -- .../propel/docs/guide/09-Inheritance.txt | 329 -- .../reference/Buildtime-Configuration.txt | 312 -- .../propel/docs/reference/ModelCriteria.txt | 1025 ---- .../docs/reference/Runtime-Configuration.txt | 318 -- .../library/propel/docs/reference/Schema.txt | 398 -- .../library/propel/generator/bin/propel-gen | 70 - .../library/propel/generator/build-propel.xml | 513 -- .../propel/generator/build.properties-sample | 192 - .../library/propel/generator/build.xml | 184 - .../library/propel/generator/build.xml-local | 124 - .../propel/generator/default.properties | 267 -- .../AlternativeCodingStandardsBehavior.php | 133 - .../lib/behavior/AutoAddPkBehavior.php | 54 - .../lib/behavior/SoftDeleteBehavior.php | 467 -- .../lib/behavior/TimestampableBehavior.php | 171 - .../AggregateColumnBehavior.php | 122 - .../AggregateColumnRelationBehavior.php | 164 - .../templates/objectCompute.php | 17 - .../templates/objectUpdate.php | 11 - .../templates/objectUpdateRelated.php | 16 - .../templates/queryFindRelated.php | 20 - .../templates/queryUpdateRelated.php | 8 - .../ConcreteInheritanceBehavior.php | 235 - .../ConcreteInheritanceParentBehavior.php | 89 - .../behavior/nestedset/NestedSetBehavior.php | 99 - ...NestedSetBehaviorObjectBuilderModifier.php | 1540 ------ .../NestedSetBehaviorPeerBuilderModifier.php | 555 --- .../NestedSetBehaviorQueryBuilderModifier.php | 357 -- .../query_cache/QueryCacheBehavior.php | 262 - .../behavior/sluggable/SluggableBehavior.php | 332 -- .../behavior/sortable/SortableBehavior.php | 83 - .../SortableBehaviorObjectBuilderModifier.php | 636 --- .../SortableBehaviorPeerBuilderModifier.php | 367 -- .../SortableBehaviorQueryBuilderModifier.php | 283 -- .../lib/builder/DataModelBuilder.php | 607 --- .../generator/lib/builder/om/ClassTools.php | 120 - .../lib/builder/om/ExtensionQueryBuilder.php | 139 - .../om/ExtensionQueryInheritanceBuilder.php | 138 - .../generator/lib/builder/om/OMBuilder.php | 526 -- .../lib/builder/om/ObjectBuilder.php | 186 - .../builder/om/PHP5ExtensionNodeBuilder.php | 111 - .../om/PHP5ExtensionNodePeerBuilder.php | 112 - .../builder/om/PHP5ExtensionObjectBuilder.php | 133 - .../builder/om/PHP5ExtensionPeerBuilder.php | 136 - .../lib/builder/om/PHP5InterfaceBuilder.php | 108 - .../om/PHP5MultiExtendObjectBuilder.php | 196 - .../lib/builder/om/PHP5NestedSetBuilder.php | 1136 ----- .../builder/om/PHP5NestedSetPeerBuilder.php | 1727 ------- .../lib/builder/om/PHP5NodeBuilder.php | 1104 ----- .../lib/builder/om/PHP5NodePeerBuilder.php | 754 --- .../lib/builder/om/PHP5ObjectBuilder.php | 4250 ----------------- .../om/PHP5ObjectNoCollectionBuilder.php | 962 ---- .../lib/builder/om/PHP5PeerBuilder.php | 2761 ----------- .../lib/builder/om/PHP5TableMapBuilder.php | 354 -- .../generator/lib/builder/om/PeerBuilder.php | 305 -- .../generator/lib/builder/om/QueryBuilder.php | 1065 ----- .../builder/om/QueryInheritanceBuilder.php | 276 -- .../generator/lib/builder/sql/DDLBuilder.php | 166 - .../lib/builder/sql/DataSQLBuilder.php | 253 - .../lib/builder/sql/mssql/MssqlDDLBuilder.php | 173 - .../builder/sql/mssql/MssqlDataSQLBuilder.php | 37 - .../lib/builder/sql/mysql/MysqlDDLBuilder.php | 413 -- .../builder/sql/mysql/MysqlDataSQLBuilder.php | 22 - .../builder/sql/oracle/OracleDDLBuilder.php | 185 - .../sql/oracle/OracleDataSQLBuilder.php | 22 - .../lib/builder/sql/pgsql/PgsqlDDLBuilder.php | 304 -- .../builder/sql/pgsql/PgsqlDataSQLBuilder.php | 102 - .../builder/sql/sqlite/SqliteDDLBuilder.php | 119 - .../sql/sqlite/SqliteDataSQLBuilder.php | 36 - .../builder/util/DefaultEnglishPluralizer.php | 33 - .../generator/lib/builder/util/Pluralizer.php | 28 - .../lib/builder/util/PropelStringReader.php | 91 - .../lib/builder/util/PropelTemplate.php | 92 - .../lib/builder/util/XmlToAppData.php | 417 -- .../lib/builder/util/XmlToDataSQL.php | 265 - .../generator/lib/config/GeneratorConfig.php | 217 - .../lib/exception/EngineException.php | 22 - .../propel/generator/lib/model/AppData.php | 222 - .../propel/generator/lib/model/Behavior.php | 247 - .../propel/generator/lib/model/Column.php | 1188 ----- .../lib/model/ColumnDefaultValue.php | 91 - .../lib/model/ConstraintNameGenerator.php | 72 - .../propel/generator/lib/model/Database.php | 676 --- .../propel/generator/lib/model/Domain.php | 386 -- .../propel/generator/lib/model/ForeignKey.php | 509 -- .../propel/generator/lib/model/IDMethod.php | 35 - .../generator/lib/model/IdMethodParameter.php | 108 - .../propel/generator/lib/model/Index.php | 285 -- .../generator/lib/model/Inheritance.php | 147 - .../generator/lib/model/NameFactory.php | 77 - .../generator/lib/model/NameGenerator.php | 73 - .../generator/lib/model/PhpNameGenerator.php | 167 - .../generator/lib/model/PropelTypes.php | 343 -- .../propel/generator/lib/model/Rule.php | 194 - .../propel/generator/lib/model/Table.php | 1579 ------ .../propel/generator/lib/model/Unique.php | 58 - .../propel/generator/lib/model/Validator.php | 184 - .../propel/generator/lib/model/VendorInfo.php | 172 - .../propel/generator/lib/model/XMLElement.php | 182 - .../lib/platform/DefaultPlatform.php | 299 -- .../generator/lib/platform/MssqlPlatform.php | 107 - .../generator/lib/platform/MysqlPlatform.php | 110 - .../generator/lib/platform/OraclePlatform.php | 113 - .../generator/lib/platform/PgsqlPlatform.php | 118 - .../generator/lib/platform/Platform.php | 182 - .../generator/lib/platform/SqlitePlatform.php | 87 - .../lib/reverse/BaseSchemaParser.php | 188 - .../generator/lib/reverse/SchemaParser.php | 63 - .../lib/reverse/mssql/MssqlSchemaParser.php | 240 - .../lib/reverse/mysql/MysqlSchemaParser.php | 340 -- .../lib/reverse/oracle/OracleSchemaParser.php | 249 - .../lib/reverse/pgsql/PgsqlSchemaParser.php | 548 --- .../lib/reverse/sqlite/SqliteSchemaParser.php | 195 - .../lib/task/AbstractPropelDataModelTask.php | 593 --- .../lib/task/PropelConvertConfTask.php | 344 -- .../generator/lib/task/PropelDataDTDTask.php | 68 - .../generator/lib/task/PropelDataDumpTask.php | 354 -- .../lib/task/PropelDataModelTemplateTask.php | 217 - .../generator/lib/task/PropelDataSQLTask.php | 193 - .../generator/lib/task/PropelGraphvizTask.php | 170 - .../generator/lib/task/PropelOMTask.php | 231 - .../generator/lib/task/PropelSQLExec.php | 701 --- .../generator/lib/task/PropelSQLTask.php | 250 - .../lib/task/PropelSchemaReverseTask.php | 548 --- .../pear/BuildPropelGenPEARPackageTask.php | 258 - .../generator/pear/build-pear-package.xml | 160 - .../propel/generator/pear/build.properties | 5 - .../propel/generator/pear/pear-build.xml | 121 - .../propel/generator/pear/pear-propel-gen | 24 - .../propel/generator/pear/pear-propel-gen.bat | 30 - .../generator/resources/dtd/database.dtd | 180 - .../resources/xsd/custom_datatypes.xsd | 8 - .../generator/resources/xsd/database.xsd | 862 ---- .../generator/resources/xsl/database.xsl | 292 -- .../library/propel/runtime/lib/Propel.php | 916 ---- .../propel/runtime/lib/adapter/DBAdapter.php | 297 -- .../propel/runtime/lib/adapter/DBMSSQL.php | 215 - .../propel/runtime/lib/adapter/DBMySQL.php | 145 - .../propel/runtime/lib/adapter/DBNone.php | 104 - .../propel/runtime/lib/adapter/DBOracle.php | 150 - .../propel/runtime/lib/adapter/DBPostgres.php | 141 - .../propel/runtime/lib/adapter/DBSQLite.php | 116 - .../lib/adapter/MSSQL/MssqlDateTime.class.php | 35 - .../lib/adapter/MSSQL/MssqlDebugPDO.php | 19 - .../lib/adapter/MSSQL/MssqlPropelPDO.php | 132 - .../lib/collection/PropelArrayCollection.php | 188 - .../lib/collection/PropelCollection.php | 409 -- .../lib/collection/PropelObjectCollection.php | 249 - .../collection/PropelOnDemandCollection.php | 151 - .../lib/collection/PropelOnDemandIterator.php | 118 - .../lib/config/PropelConfiguration.php | 159 - .../config/PropelConfigurationIterator.php | 103 - .../runtime/lib/connection/DebugPDO.php | 111 - .../lib/connection/DebugPDOStatement.php | 122 - .../runtime/lib/connection/PropelPDO.php | 716 --- .../runtime/lib/exception/PropelException.php | 50 - .../runtime/lib/formatter/ModelWith.php | 144 - .../lib/formatter/PropelArrayFormatter.php | 170 - .../runtime/lib/formatter/PropelFormatter.php | 202 - .../lib/formatter/PropelObjectFormatter.php | 112 - .../lib/formatter/PropelOnDemandFormatter.php | 96 - .../formatter/PropelStatementFormatter.php | 45 - .../propel/runtime/lib/logger/BasicLogger.php | 91 - .../runtime/lib/logger/MojaviLogAdapter.php | 160 - .../propel/runtime/lib/map/ColumnMap.php | 464 -- .../propel/runtime/lib/map/DatabaseMap.php | 191 - .../propel/runtime/lib/map/RelationMap.php | 299 -- .../propel/runtime/lib/map/TableMap.php | 712 --- .../propel/runtime/lib/map/ValidatorMap.php | 92 - .../propel/runtime/lib/om/BaseObject.php | 319 -- .../lib/om/NestedSetRecursiveIterator.php | 86 - .../propel/runtime/lib/om/NodeObject.php | 324 -- .../propel/runtime/lib/om/Persistent.php | 108 - .../runtime/lib/om/PreOrderNodeIterator.php | 78 - .../propel/runtime/lib/query/Criteria.php | 1561 ------ .../propel/runtime/lib/query/Criterion.php | 543 --- .../runtime/lib/query/CriterionIterator.php | 54 - .../library/propel/runtime/lib/query/Join.php | 250 - .../runtime/lib/query/ModelCriteria.php | 1841 ------- .../runtime/lib/query/ModelCriterion.php | 283 -- .../propel/runtime/lib/query/ModelJoin.php | 166 - .../propel/runtime/lib/query/PropelQuery.php | 33 - .../propel/runtime/lib/util/BasePeer.php | 1099 ----- .../propel/runtime/lib/util/NodePeer.php | 369 -- .../runtime/lib/util/PropelAutoloader.php | 113 - .../runtime/lib/util/PropelColumnTypes.php | 88 - .../lib/util/PropelConditionalProxy.php | 71 - .../runtime/lib/util/PropelDateTime.php | 76 - .../runtime/lib/util/PropelModelPager.php | 349 -- .../propel/runtime/lib/util/PropelPager.php | 597 --- .../runtime/lib/validator/BasicValidator.php | 35 - .../runtime/lib/validator/MatchValidator.php | 68 - .../lib/validator/MaxLengthValidator.php | 39 - .../lib/validator/MaxValueValidator.php | 43 - .../lib/validator/MinLengthValidator.php | 36 - .../lib/validator/MinValueValidator.php | 43 - .../lib/validator/NotMatchValidator.php | 66 - .../lib/validator/RequiredValidator.php | 38 - .../runtime/lib/validator/TypeValidator.php | 68 - .../runtime/lib/validator/UniqueValidator.php | 48 - .../lib/validator/ValidValuesValidator.php | 33 - .../lib/validator/ValidationFailed.php | 115 - .../pear/BuildPropelPEARPackageTask.php | 205 - .../runtime/pear/build-pear-package.xml | 121 - airtime_mvc/library/propel/test/README | 139 - .../propel/test/bookstore-packaged-test.php | 811 ---- .../library/propel/test/etc/lob/propel.gif | Bin 2671 -> 0 bytes .../library/propel/test/etc/lob/tin_drum.gif | Bin 8202 -> 0 bytes .../library/propel/test/etc/lob/tin_drum.txt | 76 - .../test/etc/schema/tabletest-schema.xml | 25 - .../propel/test/etc/xsl/coverage-frames.xsl | 636 --- .../library/propel/test/etc/xsl/log.xsl | 216 - .../propel/test/etc/xsl/phpunit2-noframes.xsl | 445 -- .../test/etc/xsl/str.replace.function.xsl | 105 - .../bookstore-packaged/book.schema.xml | 62 - .../book_club_list.schema.xml | 42 - .../bookstore-packaged/build.properties | 19 - .../external/author.schema.xml | 53 - .../bookstore-packaged/log.schema.xml | 31 - .../bookstore-packaged/media.schema.xml | 31 - .../bookstore-packaged/publisher.schema.xml | 17 - .../bookstore-packaged/review.schema.xml | 53 - .../bookstore-packaged/runtime-conf.xml | 66 - .../bookstore/behavior-aggregate-schema.xml | 39 - .../bookstore/behavior-auto-add-pk-schema.xml | 28 - .../behavior-concrete-inheritance-schema.xml | 69 - .../bookstore/behavior-nested-set-schema.xml | 27 - .../fixtures/bookstore/behavior-schema.xml | 15 - .../bookstore/behavior-sluggable-schema.xml | 23 - .../bookstore/behavior-soft-delete-schema.xml | 19 - .../bookstore/behavior-sortable-schema.xml | 21 - .../behavior-timestampable-schema.xml | 21 - .../test/fixtures/bookstore/build.properties | 35 - .../test/fixtures/bookstore/cms-schema.xml | 19 - .../test/fixtures/bookstore/runtime-conf.xml | 125 - .../propel/test/fixtures/bookstore/schema.xml | 320 -- .../test/fixtures/namespaced/build.properties | 31 - .../test/fixtures/namespaced/runtime-conf.xml | 81 - .../test/fixtures/namespaced/schema.xml | 87 - .../test/fixtures/nestedset/build.properties | 35 - .../fixtures/nestedset/nestedset-schema.xml | 39 - .../test/fixtures/nestedset/runtime-conf.xml | 53 - .../test/fixtures/treetest/build.properties | 26 - .../test/fixtures/treetest/runtime-conf.xml | 53 - .../fixtures/treetest/treetest-schema.xml | 28 - .../fixtures/unique-column/column-schema.xml | 9 - .../fixtures/unique-column/table-schema.xml | 13 - airtime_mvc/library/propel/test/speed.php | 401 -- airtime_mvc/library/propel/test/test.xml | 86 - .../behavior/AutoAddPkBehaviorTest.php | 70 - .../generator/behavior/ObjectBehaviorTest.php | 152 - .../generator/behavior/PeerBehaviorTest.php | 61 - .../behavior/SoftDeleteBehaviorTest.php | 360 -- .../generator/behavior/TableBehaviorTest.php | 34 - .../behavior/TimestampableBehaviorTest.php | 215 - .../AggregateColumnBehaviorTest.php | 254 - .../ConcreteInheritanceBehaviorTest.php | 202 - .../ConcreteInheritanceParentBehaviorTest.php | 53 - ...edSetBehaviorObjectBuilderModifierTest.php | 1351 ------ ...viorObjectBuilderModifierWithScopeTest.php | 551 --- ...stedSetBehaviorPeerBuilderModifierTest.php | 350 -- ...haviorPeerBuilderModifierWithScopeTest.php | 253 - ...tedSetBehaviorQueryBuilderModifierTest.php | 283 -- ...aviorQueryBuilderModifierWithScopeTest.php | 285 -- .../nestedset/NestedSetBehaviorTest.php | 48 - .../sluggable/SluggableBehaviorTest.php | 299 -- ...tableBehaviorObjectBuilderModifierTest.php | 279 -- ...viorObjectBuilderModifierWithScopeTest.php | 335 -- ...ortableBehaviorPeerBuilderModifierTest.php | 83 - ...haviorPeerBuilderModifierWithScopeTest.php | 114 - ...rtableBehaviorQueryBuilderModifierTest.php | 115 - ...aviorQueryBuilderModifierWithScopeTest.php | 142 - .../sortable/SortableBehaviorTest.php | 33 - .../generator/builder/NamespaceTest.php | 225 - .../om/GeneratedNestedSetObjectTest.php | 187 - .../builder/om/GeneratedNestedSetPeerTest.php | 188 - .../builder/om/GeneratedNestedSetTest.php | 120 - .../builder/om/GeneratedObjectLobTest.php | 289 -- .../builder/om/GeneratedObjectRelTest.php | 352 -- .../builder/om/GeneratedObjectTest.php | 1355 ------ .../builder/om/GeneratedPeerDoDeleteTest.php | 545 --- .../builder/om/GeneratedPeerDoSelectTest.php | 439 -- .../builder/om/GeneratedPeerTest.php | 90 - .../builder/om/OMBuilderNamespaceTest.php | 149 - .../generator/builder/om/OMBuilderTest.php | 89 - .../builder/om/PHP5TableMapBuilderTest.php | 149 - .../om/QueryBuilderInheritanceTest.php | 95 - .../generator/builder/om/QueryBuilderTest.php | 912 ---- .../builder/util/PropelTemplateTest.php | 54 - .../generator/builder/util/template.php | 1 - .../generator/model/BehaviorTest.php | 113 - .../testsuite/generator/model/ColumnTest.php | 81 - .../generator/model/NameFactoryTest.php | 151 - .../generator/model/PhpNameGeneratorTest.php | 55 - .../testsuite/generator/model/TableTest.php | 109 - .../platform/DefaultPlatformTest.php | 45 - .../generator/platform/PlatformTestBase.php | 55 - .../generator/platform/SqlitePlatformTest.php | 48 - .../test/testsuite/misc/BookstoreTest.php | 870 ---- .../testsuite/misc/CharacterEncodingTest.php | 112 - .../testsuite/misc/FieldnameRelatedTest.php | 396 -- .../test/testsuite/misc/Ticket520Test.php | 250 - .../runtime/adapter/DBOracleTest.php | 47 - .../collection/PropelArrayCollectionTest.php | 152 - .../collection/PropelCollectionTest.php | 353 -- .../collection/PropelObjectCollectionTest.php | 236 - .../PropelOnDemandCollectionTest.php | 76 - .../collection/PropelOnDemandIteratorTest.php | 59 - .../runtime/connection/PropelPDOTest.php | 425 -- .../formatter/PropelArrayFormatterTest.php | 129 - .../PropelArrayFormatterWithTest.php | 383 -- .../PropelObjectFormatterInheritanceTest.php | 55 - .../formatter/PropelObjectFormatterTest.php | 125 - .../PropelObjectFormatterWithTest.php | 406 -- .../formatter/PropelOnDemandFormatterTest.php | 151 - .../PropelOnDemandFormatterWithTest.php | 277 -- .../PropelStatementFormatterTest.php | 124 - .../testsuite/runtime/map/ColumnMapTest.php | 141 - .../testsuite/runtime/map/DatabaseMapTest.php | 171 - .../runtime/map/GeneratedRelationMapTest.php | 75 - .../runtime/map/RelatedMapSymmetricalTest.php | 70 - .../testsuite/runtime/map/RelationMapTest.php | 89 - .../testsuite/runtime/map/TableMapTest.php | 286 -- .../runtime/om/BaseObjectSerializeTest.php | 95 - .../testsuite/runtime/om/BaseObjectTest.php | 69 - .../runtime/query/CriteriaCombineTest.php | 385 -- .../query/CriteriaFluidConditionTest.php | 181 - .../runtime/query/CriteriaMergeTest.php | 399 -- .../testsuite/runtime/query/CriteriaTest.php | 974 ---- .../test/testsuite/runtime/query/JoinTest.php | 135 - .../runtime/query/ModelCriteriaHooksTest.php | 196 - .../runtime/query/ModelCriteriaTest.php | 2068 -------- .../testsuite/runtime/query/ModelJoinTest.php | 85 - .../testsuite/runtime/query/ModelWithTest.php | 183 - .../runtime/query/PropelQueryTest.php | 63 - .../runtime/util/BasePeerExceptionsTest.php | 94 - .../testsuite/runtime/util/BasePeerTest.php | 413 -- .../runtime/util/PropelConfigurationTest.php | 69 - .../runtime/util/PropelDateTimeTest.php | 139 - .../runtime/util/PropelModelPagerTest.php | 149 - .../runtime/util/PropelPagerTest.php | 162 - .../runtime/validator/ValidatorTest.php | 228 - .../test/tools/helpers/BaseTestCase.php | 30 - .../bookstore/BookstoreDataPopulator.php | 247 - .../bookstore/BookstoreEmptyTestBase.php | 38 - .../helpers/bookstore/BookstoreTestBase.php | 47 - .../behavior/BookstoreNestedSetTestBase.php | 146 - .../behavior/BookstoreSortableTestBase.php | 104 - .../bookstore/behavior/DonothingBehavior.php | 13 - .../helpers/bookstore/behavior/TestAuthor.php | 83 - .../behavior/Testallhooksbehavior.php | 183 - .../bookstore/validator/ISBNValidator.php | 29 - .../tools/helpers/cms/CmsDataPopulator.php | 143 - .../test/tools/helpers/cms/CmsTestBase.php | 45 - .../propel/test/tools/phing/DefineTask.php | 58 - airtime_mvc/library/propel/test/tree-test.php | 426 -- 414 files changed, 109582 deletions(-) delete mode 100644 airtime_mvc/library/propel/CHANGELOG delete mode 100644 airtime_mvc/library/propel/INSTALL delete mode 100644 airtime_mvc/library/propel/LICENSE delete mode 100644 airtime_mvc/library/propel/WHATS_NEW delete mode 100644 airtime_mvc/library/propel/contrib/dbd2propel/dbd2propel.xsl delete mode 100644 airtime_mvc/library/propel/contrib/dbd2propel/transform.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Creator/Definition.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Creator/Propel.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Creator/_propel_creator_test.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Datasource/Propel.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Definition.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Definition/Propel.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Element.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/Match.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxLength.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxValue.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinLength.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinValue.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/NotMatch.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Rule/ValidValues.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/Storage/Propel.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/res/form.dynamic.tpl delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms/res/mysql-dump.bookstore.sql delete mode 100644 airtime_mvc/library/propel/contrib/pat/patForms_Storage_Propel_test.php delete mode 100644 airtime_mvc/library/propel/contrib/pat/patTemplate.php delete mode 100644 airtime_mvc/library/propel/contrib/pear/HTML_QuickForm_Propel/Propel.php delete mode 100644 airtime_mvc/library/propel/contrib/pear/Structures_DataGrid_Propel/Propel.php delete mode 100644 airtime_mvc/library/propel/docs/behavior/aggregate_column.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/alternative_coding_standards.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/auto_add_pk.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/nested_set.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/query_cache.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/sluggable.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/soft_delete.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/sortable.txt delete mode 100644 airtime_mvc/library/propel/docs/behavior/timestampable.txt delete mode 100644 airtime_mvc/library/propel/docs/build.xml delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Add-Custom-SQL.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Copying-Objects.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Customizing-Build.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Existing-Database.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/LOB-Columns.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Master-Slave.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Multi-Component.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Namespaces.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Nested-Set.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Runtime-Introspection.txt delete mode 100644 airtime_mvc/library/propel/docs/cookbook/Writing-Behavior.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/01-Installation.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/02-BuildTime.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/03-Basic-CRUD.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/04-Relationships.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/05-Validators.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/06-Transactions.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/07-Behaviors.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/08-Logging.txt delete mode 100644 airtime_mvc/library/propel/docs/guide/09-Inheritance.txt delete mode 100644 airtime_mvc/library/propel/docs/reference/Buildtime-Configuration.txt delete mode 100644 airtime_mvc/library/propel/docs/reference/ModelCriteria.txt delete mode 100644 airtime_mvc/library/propel/docs/reference/Runtime-Configuration.txt delete mode 100644 airtime_mvc/library/propel/docs/reference/Schema.txt delete mode 100755 airtime_mvc/library/propel/generator/bin/propel-gen delete mode 100644 airtime_mvc/library/propel/generator/build-propel.xml delete mode 100644 airtime_mvc/library/propel/generator/build.properties-sample delete mode 100644 airtime_mvc/library/propel/generator/build.xml delete mode 100644 airtime_mvc/library/propel/generator/build.xml-local delete mode 100644 airtime_mvc/library/propel/generator/default.properties delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/AlternativeCodingStandardsBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/AutoAddPkBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/SoftDeleteBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/TimestampableBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnRelationBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectCompute.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdate.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdateRelated.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryFindRelated.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryUpdateRelated.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceParentBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorPeerBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorQueryBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/query_cache/QueryCacheBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/sluggable/SluggableBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorObjectBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorQueryBuilderModifier.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/DataModelBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/ClassTools.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/OMBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/ObjectBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5InterfaceBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodeBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodePeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5PeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PHP5TableMapBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/PeerBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/QueryBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/om/QueryInheritanceBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/DDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/DataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDDLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDataSQLBuilder.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/DefaultEnglishPluralizer.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/Pluralizer.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/PropelStringReader.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/PropelTemplate.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/XmlToAppData.php delete mode 100644 airtime_mvc/library/propel/generator/lib/builder/util/XmlToDataSQL.php delete mode 100644 airtime_mvc/library/propel/generator/lib/config/GeneratorConfig.php delete mode 100644 airtime_mvc/library/propel/generator/lib/exception/EngineException.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/AppData.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Behavior.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Column.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/ColumnDefaultValue.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/ConstraintNameGenerator.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Database.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Domain.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/ForeignKey.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/IDMethod.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/IdMethodParameter.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Index.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Inheritance.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/NameFactory.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/NameGenerator.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/PhpNameGenerator.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/PropelTypes.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Rule.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Table.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Unique.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/Validator.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/VendorInfo.php delete mode 100644 airtime_mvc/library/propel/generator/lib/model/XMLElement.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/DefaultPlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/MssqlPlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/MysqlPlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/OraclePlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/PgsqlPlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/Platform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/platform/SqlitePlatform.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/BaseSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/SchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/mssql/MssqlSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/mysql/MysqlSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/oracle/OracleSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/pgsql/PgsqlSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/reverse/sqlite/SqliteSchemaParser.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/AbstractPropelDataModelTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelConvertConfTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelDataDTDTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelDataDumpTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelDataModelTemplateTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelDataSQLTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelGraphvizTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelOMTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelSQLExec.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelSQLTask.php delete mode 100644 airtime_mvc/library/propel/generator/lib/task/PropelSchemaReverseTask.php delete mode 100644 airtime_mvc/library/propel/generator/pear/BuildPropelGenPEARPackageTask.php delete mode 100644 airtime_mvc/library/propel/generator/pear/build-pear-package.xml delete mode 100644 airtime_mvc/library/propel/generator/pear/build.properties delete mode 100644 airtime_mvc/library/propel/generator/pear/pear-build.xml delete mode 100755 airtime_mvc/library/propel/generator/pear/pear-propel-gen delete mode 100644 airtime_mvc/library/propel/generator/pear/pear-propel-gen.bat delete mode 100644 airtime_mvc/library/propel/generator/resources/dtd/database.dtd delete mode 100644 airtime_mvc/library/propel/generator/resources/xsd/custom_datatypes.xsd delete mode 100644 airtime_mvc/library/propel/generator/resources/xsd/database.xsd delete mode 100644 airtime_mvc/library/propel/generator/resources/xsl/database.xsl delete mode 100644 airtime_mvc/library/propel/runtime/lib/Propel.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBAdapter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBMSSQL.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBMySQL.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBNone.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBOracle.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBPostgres.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/DBSQLite.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlDateTime.class.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlDebugPDO.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlPropelPDO.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/collection/PropelArrayCollection.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/collection/PropelCollection.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/collection/PropelObjectCollection.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandCollection.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandIterator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/config/PropelConfiguration.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/config/PropelConfigurationIterator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/connection/DebugPDO.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/connection/DebugPDOStatement.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/connection/PropelPDO.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/exception/PropelException.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/ModelWith.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/PropelArrayFormatter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/PropelFormatter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/PropelObjectFormatter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/PropelOnDemandFormatter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/formatter/PropelStatementFormatter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/logger/BasicLogger.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/logger/MojaviLogAdapter.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/map/ColumnMap.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/map/DatabaseMap.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/map/RelationMap.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/map/TableMap.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/map/ValidatorMap.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/om/BaseObject.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/om/NestedSetRecursiveIterator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/om/NodeObject.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/om/Persistent.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/om/PreOrderNodeIterator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/Criteria.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/Criterion.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/CriterionIterator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/Join.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/ModelCriteria.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/ModelCriterion.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/ModelJoin.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/query/PropelQuery.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/BasePeer.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/NodePeer.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelAutoloader.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelColumnTypes.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelConditionalProxy.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelDateTime.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelModelPager.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/util/PropelPager.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/BasicValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/MatchValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/MaxLengthValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/MaxValueValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/MinLengthValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/MinValueValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/NotMatchValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/RequiredValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/TypeValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/UniqueValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/ValidValuesValidator.php delete mode 100644 airtime_mvc/library/propel/runtime/lib/validator/ValidationFailed.php delete mode 100644 airtime_mvc/library/propel/runtime/pear/BuildPropelPEARPackageTask.php delete mode 100644 airtime_mvc/library/propel/runtime/pear/build-pear-package.xml delete mode 100644 airtime_mvc/library/propel/test/README delete mode 100644 airtime_mvc/library/propel/test/bookstore-packaged-test.php delete mode 100644 airtime_mvc/library/propel/test/etc/lob/propel.gif delete mode 100644 airtime_mvc/library/propel/test/etc/lob/tin_drum.gif delete mode 100644 airtime_mvc/library/propel/test/etc/lob/tin_drum.txt delete mode 100644 airtime_mvc/library/propel/test/etc/schema/tabletest-schema.xml delete mode 100644 airtime_mvc/library/propel/test/etc/xsl/coverage-frames.xsl delete mode 100644 airtime_mvc/library/propel/test/etc/xsl/log.xsl delete mode 100644 airtime_mvc/library/propel/test/etc/xsl/phpunit2-noframes.xsl delete mode 100644 airtime_mvc/library/propel/test/etc/xsl/str.replace.function.xsl delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book_club_list.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/build.properties delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/external/author.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/log.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/media.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/publisher.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/review.schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore-packaged/runtime-conf.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-aggregate-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-auto-add-pk-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-concrete-inheritance-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-nested-set-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sluggable-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-soft-delete-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sortable-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/behavior-timestampable-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/build.properties delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/cms-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/runtime-conf.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/bookstore/schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/namespaced/build.properties delete mode 100644 airtime_mvc/library/propel/test/fixtures/namespaced/runtime-conf.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/namespaced/schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/nestedset/build.properties delete mode 100644 airtime_mvc/library/propel/test/fixtures/nestedset/nestedset-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/nestedset/runtime-conf.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/treetest/build.properties delete mode 100644 airtime_mvc/library/propel/test/fixtures/treetest/runtime-conf.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/treetest/treetest-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/unique-column/column-schema.xml delete mode 100644 airtime_mvc/library/propel/test/fixtures/unique-column/table-schema.xml delete mode 100644 airtime_mvc/library/propel/test/speed.php delete mode 100644 airtime_mvc/library/propel/test/test.xml delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/AutoAddPkBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/ObjectBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/PeerBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/SoftDeleteBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/TableBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/TimestampableBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/aggregate_column/AggregateColumnBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceParentBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sluggable/SluggableBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierWithScopeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/NamespaceTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetObjectTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetPeerTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectLobTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectRelTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoDeleteTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoSelectTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderNamespaceTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/PHP5TableMapBuilderTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderInheritanceTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/util/PropelTemplateTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/builder/util/template.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/model/BehaviorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/model/ColumnTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/model/NameFactoryTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/model/PhpNameGeneratorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/model/TableTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/platform/DefaultPlatformTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/platform/PlatformTestBase.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/generator/platform/SqlitePlatformTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/misc/BookstoreTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/misc/CharacterEncodingTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/misc/FieldnameRelatedTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/misc/Ticket520Test.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/adapter/DBOracleTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelArrayCollectionTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelCollectionTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelObjectCollectionTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandCollectionTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandIteratorTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/connection/PropelPDOTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterWithTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterInheritanceTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterWithTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterWithTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelStatementFormatterTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/ColumnMapTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/DatabaseMapTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/GeneratedRelationMapTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/RelatedMapSymmetricalTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/RelationMapTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/map/TableMapTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectSerializeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaCombineTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaFluidConditionTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaMergeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/JoinTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaHooksTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/ModelJoinTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/ModelWithTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/query/PropelQueryTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerExceptionsTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/PropelConfigurationTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/PropelDateTimeTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/PropelModelPagerTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/util/PropelPagerTest.php delete mode 100644 airtime_mvc/library/propel/test/testsuite/runtime/validator/ValidatorTest.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/BaseTestCase.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreDataPopulator.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreEmptyTestBase.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreTestBase.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/DonothingBehavior.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/TestAuthor.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/Testallhooksbehavior.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/bookstore/validator/ISBNValidator.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/cms/CmsDataPopulator.php delete mode 100644 airtime_mvc/library/propel/test/tools/helpers/cms/CmsTestBase.php delete mode 100644 airtime_mvc/library/propel/test/tools/phing/DefineTask.php delete mode 100644 airtime_mvc/library/propel/test/tree-test.php diff --git a/airtime_mvc/library/propel/CHANGELOG b/airtime_mvc/library/propel/CHANGELOG deleted file mode 100644 index fe4ff5fde..000000000 --- a/airtime_mvc/library/propel/CHANGELOG +++ /dev/null @@ -1,107 +0,0 @@ -= Changelog Of The Propel 1.5 Branch = - -== 2010-06-17: Version 1.5.2 == - - * [1810] Changed default table type keyword to ENGINE for MySQL (closes #969) - * [1809] Added a way to read virtual columns starting with a lowercase character (closes #993) - * [1808] Added connection object to the FK getter (closes #1018) - * [1807] Fixed namespace issue with `soft_delete` behavior (closes #1015) - * [1806] Fixed issue with instance pooling and soft_delete behavior (closes #1016) - * [1805] Added namespace declaration to model class interface (closes #1014) - * [1804] Improved generated class code when using namespaces (refs #683) - * [1803] Documented namespace.autoPackage build property (refs #1005) - * [1802] Added support for package autosetting based on namespace attribute (refs #1005) - * [1801] Fixed related instance pooling clear in case of an emulated on delete cascade / set null (refs #1012) - * [1800] Fixed onDelete cascade and setnull for self-referencing foreign keys (closes #1012) - * [1799] Fixed `ModelCriteria::find()` throws `Exception` instead of `PropelException` - * [1798] Fixed hard-to-debug unit test exception message - * [1797] Fixed cascade deletion emulation when `Criteria` is modified by `doSelect()` (closes #1008) - * [1796] Added `ModelCriteria::findOneOrCreate()` (closes #1009) - * [1795] Fixed `delete()` called in iterator breaks on demand formatter (closes #1006) - * [1794] Fixed double iteration on Propel collection (closes #1004) (patch from jeremyp) - * [1793] Documented namespaces (refs #683) - * [1792] Added support for namespaces in many-to-many relationships (refs #683) - * [1791] Added support for namespaces in single table inheritance (refs #683) - * [1790] Added mention of a common error code in runtime settings documentation - * [1789] Documented the simple templating system (refs #1002) - * [1788] Allowed namespace tests to run alongside normal tests (refs #683) - * [1787] Fixed `PropelObjectCollection::toArray()` when the collection is empty (closes #1001) - * [1786] Fixed runtime doc typo - * [1785] Refactored the `aggregate_column` behavior to take advantage of the buildtime simple templating engine (refs #1002, #995) - * [1784] Added simple templating engine for behaviors (refs #1002) - * [1783] Added a !HowTo on writing behaviors (should have been published in the blog, but Posterous is having troubles with code samples) - * [1782] Improved namespace support in generated `TableMap` classes (refs #683) - * [1781] Introducing Model Namespaces (PHP 5.3 only) (WIP) (refs #683) - * [1780] Fixed generated `filterByXXX()` for string columns when using custom comparison - * [1779] Added `aggregate_column` behavior (refs #995) - * [1778] Refactored `ForeignKey` class in generator - * [1777] [doc] Fixed typo in CRUD chapter - * [1776] Fixed generated relation names for tables with symmetrical foreign keys (closes #968) - * [1775] Fixed generated relation names for tables with more than one self-referencing foreign key (closes #972) - * [1774] Fixed copy of foreign keys with hardcoded refPhpName in concrete inheritance behavior (closes #988) - * [1773] Changing runtime autoload strategy (closes #974): - * Using absolute path in core autoloading - * introducing `PropelAutoloader` for models - * removing the need for include path change in installation docs - * [1772] Added failed SQL query to `BasePeer` exception messages (closes #979) - * [1771] Documented the schema autosuggest feature in supported IDEs - * [1770] Expanded the schema XSD annotations for easier schema autocompletion - * [1769] showcasing link to XSD file in schema to allow autocompletion on NetBeans - * [1768] Fixed typos in `ModelCriteria` doc (closes #978) (patch from Frosty) - * [1767] Fixed typo in install doc (closes #576) - * [1766] Fixed schema DTD does not validate schemas without behaviors (closes #973) - * [1765] Added the ability to comment the generated SQL query from a Criteria (closes #970) - * [1764] Fixed limitation in schema size when transformation or external schema is included (closes #971) - * [1763] Fixed limitation in schema size when no transformation nor external schema is included (closes #971) - -== 2010-05-10: Version 1.5.1 == - - * [1759] Moved ModelWith runtime class to formatter directory - * [1758] Fixed warning with new StringReader - * [1757] Reduced console logging when building an up-to-date schema - * [1756] Parsing schemas as strings instead of files (closes #967) - * [1755] Reverting r1548 to allow inclusion of external schemas (refs #967) - * [1754] Documented custom defaultJoin type (refs #870) (closes #936) - * [1749] fix Criteria::addCond() example and php-doc (closes #964) - * [1748] fix Join::addCondition() php-doc (closes #963) - * [1747] Add getJoin() method to ModelCriteria (closes #961) - * [1745] Fixed auto_add_pk behavior when using separate schemas (closes #956) - * [1743] Refactored ModelCriteria::count() to allow query cache on counts - * [1742] Fixed propel-gen executable on windows (closes #942) - * [1741] disabled query cloning by default, you can enable it on a per query basis using keepQuery() (refs #953) - * [1740] Fixed shallow Criteria cloning (refs #953) - * [1739] Fixed overriding primary key in a new object (closes #960) - * [1738] Fixed generated joinXXX() methods used in secondary Criteria (closes #958) - * [1737] Fixed array hydration (refs #954, #959) - * [1736] Added unit test to demonstrate Array Hydration regression (refs #959) - * [1735] Fixed typo in MySQL DDL builder (closes #957) - * [1734] fixed doc typos (patch from Frosty) (closes #955) - * [1733] Refactored hydration schema - * removed circular dependency between Criteria and Formatter (refs #891) - * formatters now copy the necessary hydration data from the ModelCriteria - * Should improve memory handling in large resultsets - * removed PropelFormatter::setCriteria() and checkCriteria (refs #892) - * [1732] refactored on demand hydration (refs #954), removed ModelJoin storage in ModelWith - * [1731] Refactored Joined Array hydration (refs #954) - * [1730] Changed Propel::enableInstancePooling() return value - * [1729] Added a exception to explicit the limits of one-to-many joined hydration - * [1728] Refactored joined object hydration - * Now deals correctly with any join chain (refs #954) - * Faster for large resultsets and long join chains - * [1727] refactored BasePeer::doDelete() to handle table aliases and perform better (closes #949) - * [1726] Small Criteria optimization - * [1725] Fixed ModelCriteria::delete() fails when using true table alias (closes #949) - * [1724] Allowed Merging of Criteria objects to combien conditions with an OR (closes #951) - * [1723] Added the ability to reindex a collection (closes #851) - * [1722] Gave a public way to remove an alias (useful when merging Criterias) - * [1721] Added ModelCriteria::postUpdate() and ModelCriteria::postDelete() hooks (closes #945) - * [1720] Fixed issue with instance pooling and composite fkeys in peer classes (closes #924) - * [1719] Fixed E_STRICT warning in concrete table inheritance (closes #910) - * [1718] Added unit tests for PropelObjectCollection::toKeyValue(), and made it just a little smarter (closes #943) - * [1717] Fixed typo in Relationships doc closes #941) - * [1716] Fixed reverse task and validators (closes #928) - * [1715] Fixed phpDoc for Criteria::getCriterion() (closes #929) - * [1714] Fixed regression in orderBy() used in conjunction with ignoreCase (closes #946) - * [1712] Fixed concrete table inheritance with more than one level (closes #922) - * [1711] Fixed filterByXXX() when passed an explicit Criteria::EQUAL (closes #944) - * [1710] Fixed references to 1.4 pages in documentaton (closes #937) \ No newline at end of file diff --git a/airtime_mvc/library/propel/INSTALL b/airtime_mvc/library/propel/INSTALL deleted file mode 100644 index cb7effd16..000000000 --- a/airtime_mvc/library/propel/INSTALL +++ /dev/null @@ -1,4 +0,0 @@ -I N S T A L L I N G P R O P E L -================================== - -See docs/guide/01-Installation.txt for detailed installation instructions. \ No newline at end of file diff --git a/airtime_mvc/library/propel/LICENSE b/airtime_mvc/library/propel/LICENSE deleted file mode 100644 index 1b4925a27..000000000 --- a/airtime_mvc/library/propel/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2005-2010 Hans Lellelid, David Zuelke, Francois Zaninotto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/airtime_mvc/library/propel/WHATS_NEW b/airtime_mvc/library/propel/WHATS_NEW deleted file mode 100644 index 9120f63ae..000000000 --- a/airtime_mvc/library/propel/WHATS_NEW +++ /dev/null @@ -1,807 +0,0 @@ -= What's new in Propel 1.5? = - -[[PageOutline]] - -First and foremost, don't be frightened by the long list of new features that follows. Propel 1.5 is completely backwards compatible with Propel 1.4 and 1.3, so there is no hidden cost to benefit from these features. If you didn't do it already, upgrade the propel libraries, rebuild your model, and you're done - your application can now use the Propel 1.5 features. - -== New Query API == - -This is the killer feature of Propel 1.5. It will transform the painful task of writing Criteria queries into a fun moment. - -=== Model Queries === - -Along Model and Peer classes, Propel 1.5 now generates one Query class for each table. These Query classes inherit from Criteria, but have additional abilities since the Propel generator has a deep knowledge of your schema. That means that Propel 1.5 advises that you use ModelQueries instead of raw Criteria. - -Model queries have smart filter methods for each column, and termination methods on their own. That means that instead of writing: - -{{{ -#!php -add(BookPeer::TITLE, 'War And Peace'); -$book = BookPeer::doSelectOne($c); -}}} - -You can write: - -{{{ -#!php -filterByTitle('War And Peace'); -$book = $q->findOne(); -}}} - -In addition, each Model Query class benefits from a factory method called `create()`, which returns a new instance of the query class. And the filter methods return the current query object. So it's even easier to write the previous query as follows: - -{{{ -#!php -filterByTitle('War And Peace'); - ->findOne(); -}}} - -The termination methods are `find()`, `findOne()`, `count()`, `paginate()`, `update()`, and `delete()`. They all accept a connection object as last parameter. - -Remember that a Model Query IS a Criteria. So your Propel 1.4 code snippets still work: - -{{{ -#!php -addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID); - ->add(AuthorPeer::LAST_NAME, 'Tolstoi') - ->addAscendingOrderByColumn(BookPeer::TITLE) - ->findOne(); -}}} - -But you will soon see that it's faster to use the generated methods of the Model Query classes: - -{{{ -#!php -useAuthorQuery(); - ->filterByLastName('Tolstoi') - ->endUse() - ->orderByTitle() - ->findOne(); -}}} - -That's right, you can embed a query into another; Propel guesses the join to apply from the foreign key declared in your schema. - -That makes it very easy to package your own custom model logic into reusable query methods. After a while, your code can easily look like the following: - -{{{ -#!php -filterByPublisher($publisher) - ->cheap() - ->recent() - ->useAuthorQuery(); - ->stillAlive() - ->famous() - ->endUse() - ->orderByTitle() - ->find(); -}}} - -The Model Queries can understand `findByXXX()` method calls, where `'XXX'` is the phpName of a column of the model. That answers one of the most common customization need: - -{{{ -#!php -findOneByTitle('War And Peace'); -}}} - -Eventually, these Query classes will replace the Peer classes; you should place all the code necessary to request or alter Model object in these classes. The Criteria/Peer way of doing queries still work exactly the same as in previous Propel versions, so your existing applications won't suffer from this update. - -'''Tip''': Incidentally, if you use an IDE with code completion, you will see that writing a query has never been so easy. - -=== Collections And On-Demand Hydration === - -The `find()` method of generated Model Query objects returns a `PropelCollection` object. You can use this object just like an array of model objects, iterate over it using `foreach`, access the objects by key, etc. - -{{{ -#!php -limit(5) - ->find(); // $books is a PropelCollection object -foreach ($books as $book) { - echo $book->getTitle(); -} -}}} - -Propel also returns a `PropelCollection` object instead of an array when you use a getter for a one-to-many relationship: - -{{{ -#!php -getBooks(); // $books is a PropelCollection object -}}} - -If your code relies on list of objects being arrays, you will need to update it a little. The `PropelCollection` object provides a method for most common array operations: - -{{{ -Array | Collection object ------------------------- | ----------------------------------------- -foreach($books as $book) | foreach($books as $book) -count($books) | count($books) or $books->count() -$books[]= $book | $books[]= $book or $books->append($book) -$books[0] | $books[0] or $books->getFirst() -$books[123] | $books[123] or $books->offsetGet(123) -unset($books[1]) | unset($books[1]) or $books->remove(1) -empty($books) | $books->isEmpty() -in_array($book, $books) | $books->contains($book) -array_pop($books) | $books->pop() -etc. -}}} - -'''Warning''': `empty($books)` always returns false when using a collection, even on a non-empty one. This is a PHP limitation. Prefer `$books->isEmpty()`, or `count($books)>0`. - -'''Tip''': If you can't afford updating your code to support collections instead of arrays, you can still ask Propel to generate 1.4-compatible model objects by overriding the `propel.builder.object.class` setting in your `build.properties`, as follows: - -{{{ -#!ini -propel.builder.object.class = builder.om.PHP5ObjectNoCollectionBuilder -}}} - -The `PropelCollection` class offers even more methods that you will soon use a lot: - -{{{ -#!php -getArrayCopy() // get the array inside the collection -$books->toArray() // turn all objects to associative arrays -$books->getPrimaryKeys() // get an array of the primary keys of all the objects in the collection -$books->getModel() // return the model of the collection, e.g. 'Book' -}}} - -Another advantage of using a collection instead of an array is that Propel can hydrate model objects on demand. Using this feature, you'll never fall short of memory again. Available through the `setFormatter()` method of Model Queries, on-demand hydration is very easy to trigger: - -{{{ -#!php -limit(50000) - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) // just add this line - ->find(); -foreach ($books as $book) { - echo $book->getTitle(); -} -}}} - -In this example, Propel will hydrate the `Book` objects row by row, after the `foreach` call, and reuse the memory between each iteration. The consequence is that the above code won't use more memory when the query returns 50,000 results than when it returns 5. - -`ModelCriteria::FORMAT_ON_DEMAND` is one of the many formatters provided by the new Query objects. You can also get a collection of associative arrays instead of objects, if you don't need any of the logic stored in your model object, by using `ModelCriteria::FORMAT_ARRAY`. - -The [wiki:Users/Documentation/1.5/ModelCriteria documentation] describes each formatter, and how to use it. - -=== Model Criteria === - -Generated Model Queries inherit from `ModelCriteria`, which extends your good old `Criteria`, and adds a few useful features. Basically, a `ModelCriteria` is a `Criteria` linked to a Model; by using the information stored in the generated TableMaps at runtime, `ModelCriteria` offers powerful methods to simplify the process of writing a query. - -For instance, `ModelCriteria::where()` provides similar functionality to `Criteria::add()`, except that its [http://www.php.net/manual/en/pdostatement.bindparam.php PDO-like syntax] removes the burden of Criteria constants for comparators. - -{{{ -#!php -where('Book.Title LIKE ?', 'War And P%') - ->findOne(); -}}} - -Propel analyzes the clause passed as first argument of `where()` to determine which escaping to use for the value passed as second argument. In the above example, the `Book::TITLE` column is declared as `VARCHAR` in the schema, so Propel will bind the title as a string. - -The `where()` method can also accept more complex clauses. You just need to explicit every column name as `'ModelClassName.ColumnPhpName'`, as follows: - -{{{ -#!php -where('UPPER(Book.Title) LIKE ?', 'WAR AND P%') - ->where('(Book.Price * 100) <= ?', 1500) - ->findOne(); -}}} - -Another great addition of `ModelCriteria` is the `join()` method, which just needs the name of a related model to build a JOIN clause: - -{{{ -#!php -join('Book.Author') - ->where('CONCAT(Author.FirstName, " ", Author.LastName) = ?', 'Leo Tolstoi') - ->find(); -}}} - -`ModelCriteria` has a built-in support for table aliases, which allows to setup a query using two joins on the same table, which was not possible with the `Criteria` object: - -{{{ -#!php -join('b.Author a') // use 'a' as an alias for 'Author' in the query - ->where('CONCAT(a.FirstName, " ", a.LastName) = ?', 'Leo Tolstoi') - ->find(); -}}} - -This syntax probably looks familiar, because it is very close to SQL. So you probably won't need long to figure out how to write a complex query with it. The documentation offers [wiki:Users/Documentation/1.5/ModelCriteria an entire chapter] dedicated to the new `ModelCriteria` class. Make sure you read it to see the power of this new query API. - -=== Criteria Enhancements === - -Generated queries and ModelQueries are not the only ones to have received a lot of attention in Propel 1.5. The Criteria object itself sees a few improvements, that will ease the writing of queries with complex logic. - -`Criteria::addOr()` operates the way you always expected it to. For instance, in Propel 1.4, `addOr()` resulted in a SQL `AND` if called on a column with no other condition: - -{{{ -#!php -add(BookPeer::TITLE, '%Leo%', Criteria::LIKE); -$c->addOr(BookPeer::TITLE, '%Tolstoi%', Criteria::LIKE); -// translates in SQL as -// WHERE (book.TITLE LIKE '%Leo%' OR book.TITLE LIKE '%Tolstoi%') - -// addOr() used to fail on a column with no existing condition -$c = new Criteria(); -$c->add(BookPeer::TITLE, '%Leo%', Criteria::LIKE); -$c->addOr(BookPeer::ISBN, '1234', Criteria::EQUAL); -// translates in SQL as -// WHERE book.TITLE LIKE '%Leo%' AND book.ISBN = '1234' -}}} - -This is fixed in Propel 1.5. This means that you don't need to call upon the `Criterion` object for a simple OR clause: - -{{{ -#!php -add(BookPeer::TITLE, '%Leo%', Criteria::LIKE); -$c->addOr(BookPeer::ISBN, '1234', Criteria::EQUAL); -// translates in SQL as -// WHERE (book.TITLE LIKE '%Leo%' OR book.ISBN = '1234') - -// and it's much faster to write than -$c = new Criteria(); -$c1 = $c->getNewCriterion(BookPeer::TITLE, '%Leo%', Criteria::LIKE); -$c2 = $c->getNewCriterion(BookPeer::ISBN, '1234', Criteria::EQUAL); -$c1->addOr($c2); -$c->add($c1); -}}} - -`add()` and `addOr()` only allow simple logical operations on a single condition. For more complex logic, Propel 1.4 forced you to use Criterions again. This is no longer the case in Propel 1.5, which provides a new `Criteria::combine()` method. It expects an array of named conditions to be combined, and an operator. Use `Criteria::addCond()` to create a condition, instead of the usual `add()`: - -{{{ -#!php -addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL); // creates a condition named 'cond1' -$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL); // creates a condition named 'cond2' -$c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); // combine 'cond1' and 'cond2' with a logical OR -// translates in SQL as -// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar'); -}}} - -`combine()` accepts more than two conditions at a time: -{{{ -#!php -addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL); -$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL); -$c->addCond('cond3', BookPeer::TITLE, 'FooBar', Criteria::EQUAL); -$c->combine(array('cond1', 'cond2', 'cond3'), Criteria::LOGICAL_OR); -// translates in SQL as -// WHERE ((book.TITLE = 'Foo' OR book.TITLE = 'Bar') OR book.TITLE = 'FooBar'); -}}} - -`combine()` itself can return a named condition to be combined later. So it allows for any level of logical complexity: - -{{{ -#!php -addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL); -$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL); -$c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR, 'cond12'); - -$c->addCond('cond3', BookPeer::ISBN, '1234', Criteria::EQUAL); -$c->addCond('cond4', BookPeer::ISBN, '4567', Criteria::EQUAL); -$c->combine(array('cond3', 'cond4'), Criteria::LOGICAL_OR, 'cond34'); - -$c->combine(array('cond12', 'cond34'), Criteria::LOGICAL_AND); - -// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar') -// AND (book.ISBN = '1234' OR book.ISBN = '4567'); -}}} - -The new `combine()` method makes it much easier to handle logically complex criterions. The good news is that if your application code already uses the old Criterion way, it will continue to work with Propel 1.5 as all these changes are backwards compatible. - -Of course, since Model Queries extend Criteria, this new feature is available for all your queries, with a slightly different syntax, in order to support column phpNames: - -{{{ -#!php -condition('cond1', 'Book.Title = ?', 'Foo') - ->condition('cond2', 'Book.Title = ?', 'Bar') - ->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR, 'cond12') - ->condition('cond3', 'Book.ISBN = ?', '1234') - ->condition('cond4', 'Book.ISBN = ?', '4567') - ->combine(array('cond3', 'cond4'), Criteria::LOGICAL_OR, 'cond34') - ->combine(array('cond12', 'cond34'), Criteria::LOGICAL_AND) - ->find(); -// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar') -// AND (book.ISBN = '1234' OR book.ISBN = '4567'); -}}} - -== Many-to-Many Relationships == - -At last, Propel generates the necessary methods to retrieve related objects in a many-to-many relationship. Since this feature is often needed, many developers already wrote these methods themselves. To avoid method collision, the generation of many-to-many getters is therefore optional. - -All you have to do is to add the `isCrossRef` attribute to the cross reference table, and rebuild your model. For instance, if a `User` has many `Groups`, and the `Group` has many `Users`, the many-to-many relationship is materialized by a `user_group` cross reference table: - -{{{ -#!xml - - - -
- - - - -
- - - - - - - - - - -
-}}} - -Then, both end of the relationship see the other end through a one-to-many relationship. That means that you can deal with related objects just like you normally do, without ever creating instances of the cross reference object: - -{{{ -#!php -setName('John Doe'); -$group = new Group(); -$group->setName('Anonymous'); -// relate $user and $group -$user->addGroup($group); -// save the $user object, the $group object, and a new instance of the UserGroup class -$user->save(); - -// retrieve objects as if they shared a one-to-many relationship -$groups = $user->getGroups(); - -// the model query also features a smart filter method for the relation -$groups = GroupPeer::create() - ->filterByUser($user) - ->find(); -}}} - -The syntax should be no surprise, since it's the same as the one for one-to-many relationships. Find more details about many-to-many relationships in the [wiki:Users/Documentation/1.5/Relationships relationships documentation]. - -== New Behaviors == - -The new behavior system, introduced in Propel 1.4, starts to unleash its true power with this release. Three new behaviors implement the most common customizations of object models: `nested_sets`, `sluggable`, and `sortable`. - -=== Nested Set Behavior === - -Using the `treeMode` attribute in a schema, you could turn a Propel model into a hierarchical data store starting with Propel 1.3. This method is now deprecated in favor of a new `nested_set` behavior, that does eactly the same thing, but in a more extensible and effective way. - -The main difference between the two implementations is performance. On the first levels of a large tree, the Propel 1.3 implementation of Nested sets used to consume a very large amount of memory and CPU to retrieve the siblings or the children of a given node. This is no longer true with the new behavior. - -This performance boost comes at a small price: you must add a new "level" column to your nested set models, and let the behavior update this column for the whole tree. - -For instance, if you used nested sets to keep a list of categories, the schema used to look like: - -{{{ -#!xml - - - - - -
-}}} - -The upgrade path is then pretty straightforward: - -1 - Update the schema, by removing the `treeMode` and `nestedSet` attributes and adding the `nested_set` behavior and the `tree_level` column: - -{{{ -#!xml - - - - - - - - - - - -
-}}} - -2 - Rebuild the model - -3 - Change the parent class of your model classes (object and peer) that used the nested set `treeMode`: - -{{{ -#!php - - - - - - - - -}}} - -Now, every time you save a new `Post` object, Propel will compose its slug according to the pattern defined in the behavior parameter and save it in an additional `slug` column: - -{{{ -#!php -setTitle('How Is Life On Earth?'); -$post1->setContent('Lorem Ipsum...'); -$post1->save(); -echo $post1->getSlug(); // '/posts/how-is-life-on-earth' -}}} - -Propel replaces every name enclosed between brackets in the slug pattern by the related column value. It also cleans up the string to make it URL-compatible, and ensures that it is unique. - -If you use this slug in URLs, you will need to retrieve a `Post` object based on it. This is just a one-liner: - -{{{ -#!php -findOneBySlug('/posts/how-is-life-on-earth'); -}}} - -There are many ways to customize the `sluggable` behavior to match the needs of your applications. Check the new [wiki:Users/Documentation/1.5/Behaviors/sluggable sluggable behavior documentation] for more details. - -=== Concrete Table Inheritance Behavior === - -Propel has offered [wiki:Users/Documentation/1.5/Inheritance#SingleTableInheritance Single Table Inheritance] for a long time. But for complex table inheritance needs, it is necessary to provide [http://martinfowler.com/eaaCatalog/concreteTableInheritance.html Concrete Table Inheritance]. Starting with Propel 1.5, this inheritance implementation is supported through the new `concrete_inheritance` behavior. - -In the following example, the `article` and `video` tables use this behavior to inherit the columns and foreign keys of their parent table, `content`: - -{{{ -#!xml - - - - - - - -
- - - -
- - - - - -
- - - - - -
-}}} - -The behavior copies the columns of the parent table to the child tables. That means that the generated `Article` and `Video` models have a `Title` property and a `Category` relationship: - -{{{ -#!php -setName('Movie'); -$cat->save(); -// create a new Article -$art = new Article(); -$art->setTitle('Avatar Makes Best Opening Weekend in the History'); -$art->setCategory($cat); -$art->setContent('With $232.2 million worldwide total, Avatar had one of the best-opening weekends in the history of cinema.'); -$art->save(); -// create a new Video -$vid = new Video(); -$vid->setTitle('Avatar Trailer'); -$vid->setCategory($cat); -$vid->setResourceLink('http://www.avatarmovie.com/index.html') -$vid->save(); -}}} - -If Propel stopped there, the `concrete_inheritance` behavior would only provide a shorcut to avoid repeating tags in the schema. But wait, there is more: the `Article` and `Video` classes actually extend the `Content` class: - -{{{ -#!php -getCategory()->getName(); - } -} -echo $art->getCategoryName(); // 'Movie' -echo $vid->getCategoryName(); // 'Movie' -}}} - -And the true power of Propel's Concrete Table Inheritance is that every time you save an `Article` or a `Video` object, Propel saves a copy of the `title` and `category_id` columns in a `Content` object. Consequently, retrieving objects regardless of their child type becomes very easy: - -{{{ -#!php -find(); -foreach ($conts as $content) { - echo $content->getTitle() . "(". $content->getCategoryName() ")/n"; -} -// Avatar Makes Best Opening Weekend in the History (Movie) -// Avatar Trailer (Movie) -}}} - -The resulting relational model is denormalized - in other terms, data is copied across tables - but the behavior takes care of everything for you. That allows for very effective read queries on complex inheritance structures. - -Check out the brand new [wiki:Users/Documentation/1.5/Inheritance#ConcreteTableInheritance Inheritance Documentation] for more details on using and customizing this behavior. - -=== Sortable Behavior === - -Have you ever enhanced a Propel Model to give it the ability to move up or down in an ordered list? The `sortable` behavior, new in Propel 1.5, offers exactly that... and even more. - -As usual for behaviors, activate `sortable` in your `schema.yml`: - -{{{ -#!xml - - - - - - - - - - - -
-}}} - -Then rebuild your model, and you're done. You have just created an ordered task list for users: - -{{{ -#!php -setTitle('Wash the dishes'); -$t1->setUser($paul); -$t1->save(); -echo $t1->getRank(); // 1 -$t2 = new Task(); -$t2->setTitle('Do the laundry'); -$t2->setUser($paul); -$t2->save(); -echo $t2->getRank(); // 2 -$t3 = new Task(); -$t3->setTitle('Rest a little'); -$t3->setUser($john); -$t3->save() -echo $t3->getRank(); // 1, because John has his own task list - -// retrieve the tasks -$allPaulsTasks = TaskPeer::retrieveList($scope = $paul->getId()); -$allJohnsTasks = TaskPeer::retrieveList($scope = $john->getId()); -$t1 = TaskPeer::retrieveByRank($rank = 1, $scope = $paul->getId()); -$t2 = $t1->getNext(); -$t2->moveUp(); -echo $t2->getRank(); // 1 -echo $t1->getRank(); // 2 -}}} - -This new behavior is fully unit tested and very customizable. Check out all you can do with `sortable` in the [wiki:Users/Documentation/1.5/Behaviors/sortable sortable behavior documentation]. - -=== Timestampable Behavior === - -This behavior is not new, since it was introduced in Propel 1.4. However, with the introduction of model queries, it gains specific query methods that will ease your work when retrieving objects based on their update date: - -{{{ -#!php -recentlyUpdated() // adds a minimum value for the update date - ->lastUpdatedFirst() // orders the results by descending update date - ->find(); -}}} - -== Better `toArray()` == - -When you call `toArray()` on a model object, you can now ask for the related objects: - -{{{ -#!php -toArray($keyType = BasePeer::TYPE_COLNAME, $includeLazyLoadColumns = true, $includeForeignObjects = true); -print_r($bookArray); - => array( - 'Id' => 123, - 'Title' => 'War And Peace', - 'ISBN' => '3245234535', - 'AuthorId' => 456, - 'PublisherId' => 567 - 'Author' => array( - 'Id' => 456, - 'FirstName' => 'Leo', - 'LastName' => 'Tolstoi' - ), - 'Publisher' => array( - 'Id' => 567, - 'Name' => 'Penguin' - ) - ) -}}} - -Only the related objects that were already hydrated appear in the result, so `toArray()` never issues additional queries. Together with the ability to return arrays instead of objects when using `PropelQuery`, this addition will help to debug and optimize model code. - -== Better Oracle Support == - -The Oracle adapter for the generator, the reverse engineering, and the runtime components have been greatly improved. This should provide an easier integration of Propel with an Oracle database. - -== Code Cleanup == - -=== Directory Structure Changes === - -The organization of the Propel runtime and generator code has been reworked, in order to make navigation across Propel classes easier for developers. End users should see no difference, apart if your `build.properties` references alternate builder classes in the Propel code. In that case, you will need to update your `build.properties` with the new paths. For instance, a reference to: - -{{{ -#!ini -propel.builder.peer.class = propel.engine.builder.om.php5.PHP5PeerBuilder -}}} - -Must be changed to: - -{{{ -#!ini -propel.builder.peer.class = builder.om.PHP5PeerBuilder -}}} - -Browse the Propel generator directory structure to find the classes you need. - -=== DebugPDO Refactoring === - -To allow custom connection handlers, the debug code that was written in the `DebugPDO` class has been moved to `PropelPDO`. The change is completely backwards compatible, but makes it easier to connect to a database without using PDO. - -During the change, the [wiki:Users/Documentation/1.5/07-Logging documentation about Propel logging and debugging features] was rewritten and should now be clearer. - -== propel-gen Script Modifications == - -The `propel-gen` script no longer requires a path to the project directory if you call it from a project directory. That means that calling `propel-gen` with a single argument defaults to expecting a task name: - -{{{ -> cd /path/to/my/project -> propel-gen reverse -}}} - -By default, the `propel-gen` command called without a task name defaults to the `main` task (and builds the model, the SQL, and the generation). - -Note: The behavior of the `propel-gen` script when called with one parameter differs from what it used to be in Propel 1.4, where the script expected a path in every situation. So the following syntax won't work anymore: - -{{{ -> propel-gen /path/to/my/project -}}} - -Instead, use either: - -{{{ -> cd /path/to/my/project -> propel-gen -}}} - -or: - -{{{ -> propel-gen /path/to/my/project main -}}} - -== License Change == - -Propel is more open-source than ever. To allow for an easier distribution, the open-source license of the Propel library changes from LGPL3 to MIT. This [http://en.wikipedia.org/wiki/MIT_License MIT License] is also known as the X11 License. - -This change removes a usage restriction enforced by the LGPL3: you no longer need to release any modifications to the core Propel source code under a LGPL compatible license. - -Of course, you still have the right to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Propel. In other terms, you can do whatever you want with the Propel code, without worrying about the license, as long as you leave the LICENSE file within. - -== Miscellaneous == - - * Generated model classes now offer a `fromArray()` and a `toArray()` method by default. This feature existed before, but was disabled by default in the `build.properties`. The `addGenericAccessors` and `addGenericMutators` settings are therefore enabled by default in Propel 1.5. - * You can now prefix all the table names of a database schema by setting the `tablePrefix` attribute of the `` tag. - * The `addIncludes` build property introduced in Propel 1.4 is now set to `false` by default. That means that the runtime autoloading takes care of loading all classes at runtime, including generated Base classes. - * A bugfix in the name generator for related object getter in tables with two foreign keys related to the same table may have introduced problems in applications relying on old (wrong) names. Check your generated base model classes for the `getXXXrelatedByYYY()` and modify the application code relying on it if it exists. A good rule of thumb to avoid problems in such case is to name your relations by using the `phpName` and `refPhpName` attributes in the `` element in the schema. - * XSL transformation of your schemas is no longer enabled by default. Turn the `propel.schema.transform` setting to `true` in your `build.properties` to enable it again. This change removes the requirement on the libxslt extention for Propel. - * `ModelObject::addSelectColumns()` now accepts an additional parameter to allow the use of table aliases - * Added `ModelObject::clear()` to reinitialize a model object - * Added `ModelObject::isPrimaryKeyNull()` method to check of an object was hydrated with no values (in case of a left join) - * Added `Criteria::addSelectModifier($modifier)` to add more than one select modifier (e.g. 'SQL_CALC_FOUND_ROWS', 'HIGH_PRIORITY', etc.) - * Added `PeerClass::addGetPrimaryKeyFromRow()` to retrieve the Primary key from a result row - * Added a new set of constants in the generated Peer class to list column names without the table name (this is `BasePeer::TYPE_RAW_COLNAME`) - * Removed references to Creole in the code (Propel uses PDO instead of Creole since version 1.3) \ No newline at end of file diff --git a/airtime_mvc/library/propel/contrib/dbd2propel/dbd2propel.xsl b/airtime_mvc/library/propel/contrib/dbd2propel/dbd2propel.xsl deleted file mode 100644 index 852af4ace..000000000 --- a/airtime_mvc/library/propel/contrib/dbd2propel/dbd2propel.xsl +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - - true - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TIMESTAMP - LONGVARCHAR - BOOLEAN - BLOB - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - restrict - cascade - setnull - restrict - - - -
diff --git a/airtime_mvc/library/propel/contrib/dbd2propel/transform.php b/airtime_mvc/library/propel/contrib/dbd2propel/transform.php deleted file mode 100644 index 129f19f85..000000000 --- a/airtime_mvc/library/propel/contrib/dbd2propel/transform.php +++ /dev/null @@ -1,21 +0,0 @@ -load('model.xml'); - -// load the transformation stylesheet -$xsl = new DOMDocument; -$xsl->load('dbd2propel.xsl'); - -$proc = new XSLTProcessor(); -// attach the xsl rules -$proc->importStyleSheet($xsl); - -$schema_xml = $proc->transformToXML($xml); - -file_put_contents('schema.xml', $schema_xml); diff --git a/airtime_mvc/library/propel/contrib/pat/patForms.php b/airtime_mvc/library/propel/contrib/pat/patForms.php deleted file mode 100644 index a1c66a135..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms.php +++ /dev/null @@ -1,2784 +0,0 @@ - - * @author gERD Schaufelberger - * @author Stephan Schmidt - * @copyright 2003-2004 PHP Application Tools - * @license LGPL - * @link http://www.php-tools.net - */ - -/** - * set the include path - */ -if ( !defined( 'PATFORMS_INCLUDE_PATH' ) ) { - define( 'PATFORMS_INCLUDE_PATH', dirname( __FILE__ ). '/patForms' ); -} - -/** - * needs helper methods of patForms_Element - */ -include_once PATFORMS_INCLUDE_PATH . "/Element.php"; - -/** - * error definition: renderer base class file (renderers/_base.php) could not - * be found. - * - * @see patForms::_createModule() - */ -define( "PATFORMS_ERROR_NO_MODULE_BASE_FILE", 1001 ); - -/** - * error definition: the specified renderer could not be found. - * - * @see patForms::_createModule() - */ -define( "PATFORMS_ERROR_MODULE_NOT_FOUND", 1002 ); - -/** - * error definition: the element added via the {@link patForms::addElement()} - * is not an object. Use the {@link patForms::createElement()} method to - * create an element object. - * - * @see patForms::addElement() - * @see patForms::createElement() - */ -define( "PATFORMS_ERROR_ELEMENT_IS_NO_OBJECT", 1003 ); - -/** - * error definition: generic unexpected error. - */ -define( "PATFORMS_ERROR_UNEXPECTED_ERROR", 1004 ); - -/** - * element does not exist - */ -define( "PATFORMS_ERROR_ELEMENT_NOT_FOUND", 1012 ); - -/** - * renderer object has not been set - if you want to render the form, you have to - * set a renderer object via the {@link patForms::setRenderer()} method. To create - * a renderer, use the {@link patForms::createRenderer()} method. - * - * @see patForms::setRenderer() - * @see patForms::createRenderer() - */ -define( "PATFORMS_ERROR_NO_RENDERER_SET", 1013 ); - -/** - * invalid renderer - * - * @see createRenderer() - */ -define( "PATFORMS_ERROR_INVALID_RENDERER", 1014 ); - -/** - * invalid method - * - * @see setMethod() - */ -define( "PATFORMS_ERROR_INVALID_METHOD", 1015 ); - -/** - * Given parameter is not a boolean value - */ -define( "PATFORMS_ERROR_PARAMETER_NO_BOOL", 1016 ); - -/** - * Given Static property does not exist - */ -define( "PATFORMS_ERROR_NO_STATIC_PROPERTY", 1017 ); - -/** - * Unknown event - */ -define( "PATFORMS_ERROR_UNKNOWN_EVENT", 1018 ); - -/** - * Invalid event handler - */ -define( "PATFORMS_ERROR_INVALID_HANDLER", 1019 ); - -/** - * Event exists - */ -define( 'PATFORMS_NOTICE_EVENT_ALREADY_REGISTERED', 1020 ); - -/** - * Invalid storage container - */ -define( 'PATFORMS_ERROR_INVALID_STORAGE', 1021 ); - -define( 'PATFORMS_NOTICE_ARRAY_EXPECTED', 1022 ); - -define( 'PATFORMS_NOTICE_ATTRIBUTE_NOT_SUPPORTED', 1023 ); - -define( 'PATFORMS_NOTICE_INVALID_OPTION', 1024 ); - -define( 'PATFORMS_ERROR_ATTRIBUTE_REQUIRED', 1025 ); - -define( 'PATFORMS_ERROR_CAN_NOT_VERIFY_FORMAT', 1026 ); - -define( 'PATFORMS_ERROR_METHOD_FOR_MODE_NOT_AVAILABLE', 1027 ); - - -/** - * errors apply on translating errors matching current locale settings - */ -define( 'PATFORMS_NOTICE_VALIDATOR_ERROR_LOCALE_UNDEFINED', 1028 ); -define( 'PATFORMS_WARNING_VALIDATOR_ERROR_UNDEFINED', 1029 ); - -/** - * apply the rule before the built-in validation - */ -define( 'PATFORMS_RULE_BEFORE_VALIDATION', 1 ); - -/** - * apply the rule after the built-in validation - */ -define( 'PATFORMS_RULE_AFTER_VALIDATION', 2 ); - -/** - * apply the rule before AND after the built-in validation - */ -define( 'PATFORMS_RULE_BOTH', 3 ); - -/** - * attach the observer to the elements - */ -define( 'PATFORMS_OBSERVER_ATTACH_TO_ELEMENTS', 1 ); - -/** - * attach the observer to the form - */ -define( 'PATFORMS_OBSERVER_ATTACH_TO_FORM', 2 ); - -/** - * attach the observer to the form and the elements - */ -define( 'PATFORMS_OBSERVER_ATTACH_TO_BOTH', 3 ); - -/** - * group values should stay nested - */ -define('PATFORMS_VALUES_NESTED', 0); - -/** - * group values should be flattened - */ -define('PATFORMS_VALUES_FLATTENED', 1); - -/** - * group values should be prefixed - */ -define('PATFORMS_VALUES_PREFIXED', 2); - -/** - * Static patForms properties - used to emulate pre-PHP5 static properties. - * - * @see setStaticProperty() - * @see getStaticProperty() - */ -$GLOBALS['_patForms'] = array( - 'format' => 'html', - 'locale' => 'C', - 'customLocales' => array(), - 'autoFinalize' => true, - 'defaultAttributes' => array(), -); - -/** - * patForms form manager class - serialize form elements into any given output format - * using element classes, and build the output via renderer classes. - * - * @package patForms - * @author Sebastian Mordziol - * @author gERD Schaufelberger - * @author Stephan Schmidt - * @copyright 2003-2004 PHP Application Tools - * @license LGPL - * @link http://www.php-tools.net - * @version 0.9.0alpha - * @todo check the clientside functionality, as that can lead to broken pages - */ -class patForms -{ - /** - * javascript that will displayed only once - * - * @access private - * @var array - */ - var $globalJavascript = array(); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceJavascript = array(); - - /** - * stores the mode for the form. It defaults to 'default', and is only overwritten if - * set specifically. It is passed on to any elements you create. - * - * @access private - * @see setMode() - */ - var $mode = 'default'; - - /** - * XML entities - * - * @access private - * @see toXML() - * @todo This is redundant to the Element's xmlEntities property - find a way to keep this in one place - */ - var $xmlEntities = array( - "<" => "<", - ">" => ">", - "&" => "&", - "'" => "'", - '"' => """ - ); - - /** - * stores the format for the element. It defaults to 'html', and is only overwritten if - * set specifically. It is passed on to any elements you create. - * - * @access private - * @see setFormat() - */ - var $format = 'html'; - - /** - * stores the flag telling the form whether it has been submitted - this is passed on to any - * elements you create. - * - * @access private - * @see setSubmitted() - */ - var $submitted = false; - - /** - * stores the element objects of this form. - * @access private - * @see addElement() - */ - var $elements = array(); - - /** - * stores the current element count for this form, used to generate the ids for each element - * @access private - * @see getElementId() - */ - var $elementCounter = 0; - - /** - * stores a renderer - * @access private - * @see setRenderer(), renderForm() - */ - var $renderer = null; - - /** - * stores the locale to use when adding validation errors for the whole form. - * - * @access private - * @var string $locale - * @see setLocale() - */ - var $locale = 'C'; - - /** - * stores custom locale - * - * @access private - * @var array - * @see setLocale() - */ - var $customLocales = array(); - - /** - * stores the element name - * @access private - * @see getElementName() - */ - var $elementName = 'Form'; - - /** - * flag to indicate, whether form should be validated automatically - * by renderForm() - * - * @access private - * @var string - * @see setAutoValidate(), renderForm() - */ - var $autoValidate = false; - - /** - * name of the variable that indicates, whether the form has - * been submitted. - * - * @access private - * @var string - * @see setAutoValidate() - */ - var $submitVar = null; - - /** - * event handlers - * - * @access private - * @var array - * @see registerEventHandler() - * @see registerEvent() - */ - var $_eventHandler = array(); - - /** - * events that can be triggered - * - * @access private - * @var array - * @see registerEventHandler() - * @see triggerEvent() - * @see registerEvent() - */ - var $_validEvents = array( 'onInit', 'onValidate', 'onSubmit', 'onError', 'onSuccess' ); - - /** - * Stores whether the current form has been validated - * - * @access private - */ - var $validated = false; - - /** - * Stores whether the current form is valid or not (after the - * validation process) - * - * @access private - */ - var $valid = null; - - /** - * Stores the names of all static properties that patForms will use as defaults - * for the properties with the same name on startup. - * - * @access private - */ - var $staticProperties = array( - 'format' => 'setFormat', - 'autoFinalize' => 'setAutoFinalize', - 'locale' => 'setLocale', - ); - - /** - * Stores the flag for the autoFinalize feature - * - * @access private - */ - var $autoFinalize = true; - - /** - * custom validation rules - * - * @access private - * @var array - */ - var $_rules = array(); - - /** - * define error codes an messages for the form - * - * Will be set by validation rules that have been - * added to the form. - * - * @access private - * @var array $validatorErrorCodes - */ - var $validatorErrorCodes = array(); - - /** - * stores any validation errors that can occurr during the - * form's validation process. - * - * @access private - * @var array $validationErrors - */ - var $validationErrors = array(); - - /** - * next error offset for rules - * @access private - * @var integer - */ - var $nextErrorOffset = 1000; - - /** - * Attributes of the form - needed to generate the form tag - * - * @access private - * @var array $attributes - * @see setAttribute() - */ - var $attributes = array(); - - /** - * Attribute definition for the form - defines which attribute the form - * itself supports. - * - * @access public - */ - var $attributeDefinition = array( - - 'id' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'name' => array( - 'required' => true, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'method' => array( - 'required' => true, - 'format' => 'string', - 'default' => 'post', - 'outputFormats' => array( 'html' ), - ), - - 'action' => array( - 'required' => true, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'accept' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'accept-charset' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'enctype' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'onreset' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'onsubmit' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - - 'target' => array( - 'required' => false, - 'format' => 'string', - 'outputFormats' => array( 'html' ), - ), - ); - - /** - * Stores all available patForms options - these are inherited by all elements - * and their dependencies, like rules. - * - * Short option overview: - * - * - scripts: enable client script integration - * - * @access public - */ - var $options = array( - - 'scripts' => array( - 'enabled' => true, - 'params' => array(), - ), - - ); - - /** - * observers of the form - * - * @access private - * @var array - */ - var $observers = array(); - - /** - * Sets the default attributes that will be inherited by any elements you add to the form. - * - * Note: You have to call this method statically before creating a new form if you use - * patForm's automatic element creation feature via the {@link createForm()} method, as the - * default attributes cannot be set after an element has been created. - * - * @static - * @access public - * @param array $attributes The list of attributes to set with key => value pairs. - */ - function setDefaultAttributes( $attributes ) - { - patForms::setStaticProperty( 'defaultAttributes', $attributes ); - } - - /** - * sets the locale (language) to use for the validation error messages of all elements - * in the form. - * - * @access public - * @param string language code - * @param string optional language file - * @return bool True on success - */ - function setLocale( $locale, $languageFile = null ) - { - if (!is_null($languageFile)) { - $languageData = patForms::parseLocaleFile($languageFile); - - $customLocales = patForms::getStaticProperty('customLocales'); - $customLocales[$locale] = $languageData; - patForms::setStaticProperty('customLocales', $customLocales); - } - - if ( isset( $this ) && is_a( $this, 'patForms' ) ) { - $this->locale = $locale; - - if ( !empty( $this->elements ) ) { - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) { - $this->elements[$i]->setLocale( $locale ); - } - } - } else { - patForms::setStaticProperty('locale', $locale); - } - - return true; - } - - /** - * checks, whether a locale is a custom locale - * - * @static - * @access public - * @param string locale name - * @return boolean - */ - function isCustomLocale($locale) - { - $customLocales = patForms::getStaticProperty('customLocales'); - if (isset($customLocales[$locale])) { - return true; - } - return false; - } - - /** - * get the custom locale for an element or a rule - * - * @static - * @access public - * @param string locale - * @param string key - * @return array - */ - function getCustomLocale($locale, $key) - { - $customLocales = patForms::getStaticProperty('customLocales'); - if (!isset($customLocales[$locale])) { - return false; - } - if (!isset($customLocales[$locale][$key])) { - return false; - } - return $customLocales[$locale][$key]; - } - - /** - * parses a locale file - * - * @access private - * @param string filename - * @return array locale information - * @todo add some file checks - */ - function parseLocaleFile($filename) - { - return parse_ini_file($filename, true); - } - - /** - * sets the format of the element - this will be passed on to any elements you create. If you - * have already added some elements when you call this method, it will be passed on to them too. - * - * @access public - * @param string $format The name of the format you have implemented in your element(s). - * @return bool $result True on success - * @see setMode() - * @see format - * @see serialize() - */ - function setFormat( $format ) - { - if ( isset( $this ) && is_a( $this, 'patForms' ) ) - { - $this->format = strtolower( $format ); - - if ( !empty( $this->elements ) ) - { - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) - { - $this->elements[$i]->setFormat( $format ); - } - } - } - else - { - patForms::setStaticProperty( 'format', $format ); - } - - return true; - } - - /** - * sets the mode of the form - If you have already added some elements when you call this - * method, it will be passed on to them too. - * - * @access public - * @param string $mode The mode to set the form to: default|readonly or any other mode you have implemented in your element class(es). Default is 'default'. - * @see setMode() - * @see mode - * @see serialize() - */ - function setMode( $mode ) - { - $this->mode = strtolower( $mode ); - - if ( !empty( $this->elements ) ) - { - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) - { - $this->elements[$i]->setMode( $mode ); - } - } - } - - /** - * sets the current submitted state of the form. Set this to true if you want the form - * to pick up its submitted data. It will pass on this information to all elements that - * have been added so far, and new ones inherit it too. - * - * @access public - * @param bool $state True if it has been submitted, false otherwise (default). - * @see isSubmitted() - * @see submitted - */ - function setSubmitted( $state ) - { - if ( $state == true ) - { - $eventState = $this->triggerEvent( 'Submit' ); - if ( $eventState === false ) - return false; - } - - $this->submitted = $state; - - if ( !empty( $this->elements ) ) - { - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) - { - $this->elements[$i]->setSubmitted( $state ); - } - } - - return $state; - } - - /** - * sets the method for the request - * - * @access public - * @param string $method GET or POST - * @see method - * @uses setAttribute() - */ - function setMethod( $method ) - { - $method = strtolower( $method ); - - if ( $method != 'get' && $method != 'post' ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_INVALID_METHOD, - 'Unknown method "'.$method.'". Currently only GET and POST are supported as patForms methods.' - ); - } - $this->setAttribute( 'method', $method ); - return true; - } - - /** - * sets the action for the form - * - * This is a only a wrapper for setAttribute() - * - * @access public - * @param string $action - * @see setAttribute() - */ - function setAction( $action ) - { - return $this->setAttribute( 'action', $action ); - } - - /** - * Sets the AutoFinalize mode for the form. The AutoFinalize mode will tell patForms to - * finalize all elements after the form has been validated successfully. - * - * @access public - * @param boolean $mode Whether to activate the AutoFinalize mode (true) or not (false). - * @return boolean $success True if okay, a patError object otherwise. - * @see finalizeForm() - */ - function setAutoFinalize( $mode ) - { - if ( !is_bool( $mode ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_PARAMETER_NO_BOOL, - 'The setAutoFinalize() method requires a boolean value ( true or false ) as parameter.' - ); - } - - if ( isset( $this ) && is_a( $this, 'patForms' ) ) - { - $this->autoFinalize = $mode; - } - else - { - patForms::setStaticProperty( 'autoFinalize', $mode ); - } - - return true; - } - - /** - * Wrapper method that adds a filter to all elements - * of the form at once instead of having to do it for - * each element. - * - * @access public - * @param object &$filter The filter object to apply - * @see patForms_Element::applyFilter() - * @todo add error management and docs once the element's applyFilter method has too - */ - function applyFilter( &$filter ) - { - if ( empty( $this->elements ) ) - return true; - - $cnt = count( $this->elements ); - - for ( $i = 0; $i < $cnt; $i++ ) - { - $this->elements[$i]->applyFilter( $filter ); - } - } - - /** - * creates a new patForms object and returns it; this method is made to be called statically - * to be able to create a new patForms object from anywhere. - * - * @access public - * @param array $formDefinition Optional form definition for elements that will be added to the form - * @param array $attributes The attributes to set for the form itself - * @return object patForms $form The new patForms object. - * @todo it should be possible to pass Rule definitions, so they can be loaded and added automatically. - */ - function &createForm( $formDefinition = null, $attributes = null ) - { - $form = &new patForms(); - - if ( $attributes != null ) - { - $form->setAttributes( $attributes ); - } - - if ( $formDefinition === null ) - return $form; - - foreach ( $formDefinition as $name => $element ) - { - if ( !isset( $element["filters"] ) ) - { - $element["filters"] = null; - } - if ( !isset( $element["children"] ) ) - { - $element["children"] = null; - } - - $el = &$form->createElement( $name, $element["type"], $element["attributes"], $element["filters"], $element["children"] ); - - if ( isset( $element["renderer"] ) ) { - $el->setRenderer( $element["renderer"] ); - } - - $result = $form->addElement( $el ); - if (patErrorManager::isError( $result )) { - return $result; - } - } - return $form; - } - - /** - * add a custom validation rule - * - * @access public - * @param object patForms_Rule validation rule - * @param integer time to apply rule (before or after built-in validation) - * @param boolean apply the rule, even if the form is invalid - * @param boolean should form get revalidated (not implemented yet) - * @return boolean currently always true - */ - function addRule( &$rule, $time = PATFORMS_RULE_AFTER_VALIDATION, $invalid = false, $revalidate = false ) - { - $rule->prepareRule( $this ); - - $this->_rules[] = array( - 'rule' => &$rule, - 'time' => $time, - 'invalid' => $invalid, - 'revalidate' => $revalidate - ); - } - - /** - * patForms PHP5 constructor - processes some intitialization tasks like merging the currently - * set static properties with the internal properties. - * - * @access public - */ - function __construct() - { - foreach ( $this->staticProperties as $staticProperty => $setMethod ) - { - $propValue = patForms::getStaticProperty( $staticProperty ); - if ( patErrorManager::isError( $propValue ) ) - continue; - - $this->$setMethod( $propValue ); - } - - // initialize patForms internal attribute collection - $this->loadAttributeDefaults(); - } - - /** - * patForms pre-PHP5 constructor - does nothing for the moment except being a wrapper - * for the PHP5 contructor for older PHP versions support. - * - * @access public - */ - function patForms() - { - patForms::__construct(); - } - - /** - * sets a renderer object that will be used to render - * the form. - * - * @access public - * @param object &$renderer The renderer object - * @return mixed $success True on success, patError object otherwise. - * @see createRenderer() - * @see renderForm() - */ - function setRenderer( &$renderer, $args = array() ) - { - if ( !is_object( $renderer ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_INVALID_RENDERER, - 'You can only set a patForms_Renderer object with the setRenderer() method, "'.gettype( $renderer ).'" given.' - ); - } - - $this->renderer = &$renderer; - - if ( isset( $args['includeElements'] ) && $args['includeElements'] === true ) - { - // check all elements - there may be some that need - // renderers too, so we give them the same renderer if - // they don't already have one. - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( $this->elements[$i]->usesRenderer && !is_object( $this->elements[$i]->renderer ) ) - { - $this->elements[$i]->setRenderer( $renderer ); - } - } - } - - return true; - } - - /** - * sets a storage container object that will be used to store data - * - * @access public - * @param object patForms_Storage - * @see createStorage() - */ - function setStorage( &$storage ) - { - if ( !is_object( $storage ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_INVALID_STORAGE, - 'You can only set a patForms_Storage object with the setStorage() method, "'.gettype( $storage ).'" given.' - ); - } - - $this->registerEventHandlerObject( $storage, - array( - 'onInit' => 'loadEntry', - 'onValidate' => 'validateEntry', - 'onSuccess' => 'storeEntry' - ) - ); - } - - /** - * renders the form with the renderer that was set via the {@link setRenderer()} - * method. - * - * WARNING: This is still in alpha state! - * - * Should this method return a reference?? - * The return value could contain large blocks of HTML or large arrays! - * Do we want to copy these? - * - * @access public - * @param mixed $args arguments that will be passed to the renderer - * @return mixed $form The rendered form, or false if failed. - */ - function renderForm( $args = null ) - { - if ( $this->renderer === null ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_NO_RENDERER_SET, - 'Form cannot be rendered, you have to set a renderer first via the setRenderer() method.' - ); - } - - // form is not submitted, or auto-validation is disabled => render it - if ( !$this->isSubmitted() || $this->autoValidate !== true ) - { - $this->triggerEvent( 'Init' ); - return $this->renderer->render( $this, $args ); - } - - $this->validateForm(); - - return $this->renderer->render( $this, $args ); - } - - /** - * Validates all elements of the form. - * - * @access public - * @param boolean Flag to indicate, whether form should be validated again, if it already has been validated. - * @return boolean True if all elements could be validated, false otherwise. - * @see finishForm() - */ - function validateForm( $revalidate = false ) - { - if ( $this->validated && !$revalidate ) - return $this->valid; - - $valid = true; - - /** - * validate custom rules - */ - if ( !$this->_applyRules( PATFORMS_RULE_BEFORE_VALIDATION ) ) - { - $valid = false; - } - - /** - * validate elements - */ - if ( $valid === true ) - { - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - if ( !$this->elements[$i]->validate() ) - { - $valid = false; - } - } - } - - if ($valid === true) { - $result = $this->triggerEvent('Validate'); - if ($result === false) { - $valid = false; - } - } - - /** - * validate custom rules - */ - if ( !$this->_applyRules( PATFORMS_RULE_AFTER_VALIDATION, $valid ) ) - { - $valid = false; - } - - if ( $valid === true && $this->autoFinalize === true ) - $this->finalizeForm(); - - $this->valid = $valid; - - $this->validated = true; - - if ( $valid === true ) - { - $this->_announce( 'status', 'validated' ); - $event = 'Success'; - } - else - { - $this->_announce( 'status', 'error' ); - $event = 'Error'; - } - - $this->triggerEvent( $event ); - - return $this->valid; - } - - /** - * apply rules - * - * @access private - * @param integer time of validation - * @param boolean form is valid - * @return boolean rules are valid or not - * @todo add documentation - */ - function _applyRules( $time, $isValid = true ) - { - $valid = true; - - $cnt = count( $this->_rules ); - for ($i = 0; $i < $cnt; $i++) { - - // wrong time - if (( $this->_rules[$i]['time'] & $time ) != $time) { - continue; - } - if (!$isValid && !$this->_rules[$i]['invalid']) { - continue; - } - - $result = $this->_rules[$i]['rule']->applyRule( $this, PATFORMS_RULE_AFTER_VALIDATION ); - if ( $result === false ) { - $valid = false; - } - } - return $valid; - } - - /** - * Finalizes the form by telling each fom element to finalize - finalizing means to - * process any tasks that need to be done after the form has been validated, like - * deleting any temporary files or whatever an element needs to do at that point. - * - * @access public - * @return bool $success Wether all elements could be finalized - * @see validateForm() - */ - function finalizeForm() - { - $success = true; - - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - if ( !$this->elements[$i]->finalize() ) - { - patErrorManager::raiseWarning( - PATFORMS_ERROR_ELEMENT_NOT_FINALIZED, - 'Element "'.$this->elements[$i]->elementName.'" could not be finalized. See the element error messages for more details.' - ); - - $success = false; - } - } - - return $success; - } - - /** - * creates a new renderer from the patForms renderer collection and returns it. - * - * @access public - * @param string The name of the renderer to create - have a look at the Renderer/ subfolder for a list of available renderers. - * @return object patForms_Renderer The renderer object, or error object - */ - function &createRenderer( $name ) - { - return patForms::_createModule( 'Renderer', $name ); - } - - /** - * creates a new storage container and returns it. - * - * @access public - * @param string The name of the storage to create - have a look at the Storage/ subfolder for a list of available storage containers. - * @return object patForms_Storage The storage container, or error object - */ - function &createStorage( $name ) - { - return patForms::_createModule( 'Storage', $name ); - } - - /** - * Creates a new filter and returns it. - * - * You may pass an array as second parameter that contains - * parameters for the filter. patForms will check for setter methods - * for all keys and set the corresponding values. - * - * This eases the creating of simple filter objects. - * - * @access public - * @param string The name of the filter to create - have a look at the Filter/ subfolder for a list of available filters. - * @param array Optional parameters for the filter, if you provide a parameter, make sure the filter implements a set[Paramname]() method. - * This will be automated with interceptors in the PHP5 version of patForms - * @return object patForms_Filter The filter, or error object - */ - function &createFilter( $name, $params = null ) - { - $filter = &patForms::_createModule( 'Filter', $name ); - - if ( !is_array( $params ) ) - { - return $filter; - } - - foreach ( $params as $param => $value ) - { - $setter = 'set' . ucfirst( $param ); - if ( method_exists( $filter, $setter ) ) - { - $filter->$setter( $value ); - } - } - return $filter; - } - - /** - * creates a new rule from the patForms rule collection and returns it. - * - * If your rules are not located in patForms/Rule you have to load and - * instantiate them on your own. - * - * @access public - * @param string The name of the rule to create - have a look at the Rule/ subfolder for a list of available rules. - * @param string The id of the rule, needed if the rule uses client side actions. - * @return object patForms_Rule The rule object, or error object - */ - function &createRule( $name, $id = null ) - { - $rule = &patForms::_createModule( 'Rule', $name ); - if ( $id != null ) - { - $rule->setId( $id ); - } - return $rule; - } - - /** - * creates a new observer from the patForms observer collection and returns it. - * - * If your observers are not located in patForms/Observer you have to load and - * instantiate them on your own. - * - * @access public - * @param string The name of the observer to create - have a look at the Observer/ subfolder for a list of available observers. - * @return object patForms_Observer The observer object, or error object - */ - function &createObserver( $name ) - { - $observer = &patForms::_createModule( 'Observer', $name ); - - return $observer; - } - - /** - * creates a new module for patForms - * - * @access private - * @param string $type type of the module. Possible values are 'Renderer', 'Rule' - * @param string $name The name of the renderer to create - have a look at the renderers/ subfolder for a list of available renderers. - * @return object $module The module object, or an error object - */ - function &_createModule( $type, $name ) - { - $baseFile = PATFORMS_INCLUDE_PATH . '/'.$type.'.php'; - $baseClass = 'patForms_'.$type; - - // if there is an underscore in the module name, we want - // to load the module from a subfolder, so we transform - // all underscores to slashes. - $pathName = $name; - if ( strstr( $pathName, '_' ) ) - { - $pathName = str_replace( '_', '/', $name ); - } - - $moduleFile = PATFORMS_INCLUDE_PATH . '/'.$type.'/'.$pathName.'.php'; - $moduleClass = 'patForms_'.$type.'_'.$name; - - if ( !class_exists( $baseClass ) ) - { - if ( !file_exists( $baseFile ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_NO_MODULE_BASE_FILE, - $type .' base file could not be found', - 'Tried to load base file in path "'.$baseFile.'"' - ); - } - - include_once $baseFile; - } - - if ( !class_exists( $moduleClass ) ) - { - if ( !file_exists( $moduleFile ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_MODULE_NOT_FOUND, - $type.' "'.$name.'" file "'.$moduleFile. '" could not be found.' - ); - } - - include_once $moduleFile; - } - - $module = &new $moduleClass(); - - return $module; - } - - /** - * adds an element to the form - has to be a patForms_Element object. Use the {@link createElement()} - * method to create a new element object. Also takes care of passing on the form's configuration - * including the mode, format and submitted flags to the element. - * - * @access public - * @param object &$element The patForms_Element object to add to this form. - * @return bool $success True if everything went well, false otherwise. - * @see patForms_Element - * @see createElement() - */ - function addElement( &$element ) - { - if ( !is_object( $element ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_ELEMENT_IS_NO_OBJECT, - 'The addElement() method expects an element object, "'.gettype( $element ).'" given.' - ); - } - - if ( patErrorManager::isError( $element ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_UNEXPECTED_ERROR, - 'The element you are trying to add is a patError object, and not a patForms element object.' - ); - } - - if ( !$element->getId() ) { - $element->setId( $this->getElementId() ); - } - $element->setMode( $this->getMode() ); - $element->setFormat( $this->getFormat() ); - $element->setSubmitted( $this->isSubmitted() ); - $element->setLocale( $this->getLocale() ); - - $this->elements[] =& $element; - - return true; - } - - /** - * replaces an element in the form - * - * @access public - * @param object $element The patForms_Element object to be replaced - * @param object &$replace The element that will replace the old element - * @return bool $success True if everything went well, false otherwise. - * @see patForms_Element - * @see addElement() - */ - function replaceElement( $element, &$replace ) - { - if ( !is_object( $replace ) ) { - return patErrorManager::raiseError( - PATFORMS_ERROR_ELEMENT_IS_NO_OBJECT, - 'The addElement() method expects an element object, "'.gettype( $replace ).'" given.' - ); - } - - if ( patErrorManager::isError( $replace ) ) { - return patErrorManager::raiseError( - PATFORMS_ERROR_UNEXPECTED_ERROR, - 'The element you are trying to add is a patError object, and not a patForms element object.' - ); - } - - if (is_object($element)) { - $element = $element->getId(); - } - - $cnt = count($this->elements); - for ($i = 0; $i < $cnt; $i++) { - if ($this->elements[$i]->getId() === $element) { - - if ( !$replace->getId() ) { - $replace->setId( $this->getElementId() ); - } - $replace->setMode( $this->getMode() ); - $replace->setFormat( $this->getFormat() ); - $replace->setSubmitted( $this->isSubmitted() ); - $replace->setLocale( $this->getLocale() ); - - $this->elements[$i] = &$replace; - return true; - } - - // the current element is a container - if (method_exists($this->elements[$i], 'replaceElement')) { - $result = $this->elements[$i]->replaceElement($element, $replace); - if ($result === true) { - return $result; - } - } - } - - return false; - } - - /** - * Get an element by its name. - * - * @access public - * @param string $name name of the element - * @return object patForms element - * @deprecated please use patForms::getElementByName() instead - */ - function &getElement( $name ) - { - return $this->getElementByName( $name ); - } - - /** - * Get an element by its name. - * - * @access public - * @param string $name name of the element - * @return mixed either a patForms element or an array containing patForms elements - * @see getElementById() - */ - function &getElementByName( $name ) - { - if ( $name == '__form' ) { - return $this; - } - - $elements = array(); - $cnt = count( $this->elements ); - for ($i = 0; $i < $cnt; $i++) { - if ($this->elements[$i]->getName() == $name) { - $elements[] = &$this->elements[$i]; - continue; - } - if (method_exists($this->elements[$i], 'getElementById')) { - patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND); - $result = &$this->elements[$i]->getElementByName($name); - patErrorManager::popExpect(); - if (!patErrorManager::isError($result)) { - if (is_array($result)) { - $cnt2 = count( $result ); - for ($j = 0; $j < $cnt2; $j++) { - $elements[] = &$result[$j]; - } - } else { - $elements[] = &$result; - } - } - } - } - - switch( count( $elements ) ) - { - case 0: - return patErrorManager::raiseError( - PATFORMS_ERROR_ELEMENT_NOT_FOUND, - 'Element '.$name.' could not be found.' - ); - break; - case 1: - return $elements[0]; - break; - default: - return $elements; - break; - } - } - - /** - * Get an element by its id. - * - * @access public - * @param string $id id of the element - * @return object patForms element - */ - function &getElementById( $id ) - { - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( $this->elements[$i]->getId() == $id ) { - return $this->elements[$i]; - } - if (method_exists($this->elements[$i], 'getElementById')) { - patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND); - $result = &$this->elements[$i]->getElementById($id); - patErrorManager::popExpect(); - if (!patErrorManager::isError($result)) { - return $result; - } - } - } - return patErrorManager::raiseError( - PATFORMS_ERROR_ELEMENT_NOT_FOUND, - 'Element '.$name.' could not be found.' - ); - } - - /** - * Get all elements of the form - * - * @access public - * @return array all elements of the form - */ - function &getElements() - { - return $this->elements; - } - - /** - * Creates a new form element and returns a reference to it. - * - * The optional $filters array has to be in the following format: - * - *
-	* array(
-	*       array(
-	*              'filter' => 'Multiplier',
-	*              'params' => array( 'multiplier' => 6 )
-	*            )
-	*	   )
-	* 
- * - * @access public - * @param string $name The name of the element - * @param string $type The type of the element; for a list of possible elements, have a look at the elements/ subfolder of the patForms package. - * @param array $attributes Attributes for the element - * @param array $filters Optional filters that will be applied - * @return object patForms_Element $element The element object, or patError if failed. - */ - function &createElement( $name, $type, $attributes, $filters = null, $children = null ) - { - $element =& patForms::_createModule( 'Element', $type ); - if ( patErrorManager::isError( $element ) ) - { - return $element; - } - - $attributes['name'] = $name; - if ( !isset( $attributes['id'] ) ) { - $attributes['id'] = $this->getElementId(); - } - - // add default attributes - do this the 'silent' way be checking whether - // the element supports the given attribute, as the element throws a notice - // if it does not support it - this is not expected from default attributes. - foreach ( patForms::getStaticProperty( 'defaultAttributes' ) as $attributeName => $attributeValue ) - { - if ( !$element->hasAttribute( $attributeName ) ) - { - continue; - } - - $element->setAttribute( $attributeName, $attributeValue ); - } - - // set the given attributes normally - $success = $element->setAttributes( $attributes ); - if ( patErrorManager::isError( $success ) ) - { - return $success; - } - - if (is_array($children)) { - foreach ($children as $child) { - $childName = $child['attributes']['name']; - - $childEl = &patForms::createElement($childName, $child['type'], $child['attributes']); - if ( isset( $child["renderer"] ) ) { - $childEl->setRenderer( $child["renderer"] ); - } - - $element->addElement($childEl); - } - } - - $success = $element->_init(); - if ( patErrorManager::isError( $success ) ) { - return $success; - } - - // if we don't have any filters to add, we're done - if ( !is_array( $filters ) ) - { - return $element; - } - - $cnt = count( $filters ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $params = isset( $filters[$i]['params'] ) ? $filters[$i]['params'] : null; - $filter = &patForms::createFilter( $filters[$i]['filter'], $params ); - if ( patErrorManager::isError( $filter ) ) - { - continue; - } - $element->applyFilter( $filter ); - } - - return $element; - } - - /** - * retrieves the validation errors from all elements in the form. Use this if the validateForm() - * method returned false. - * - * @access public - * q - * @return array $errors Array containing an array with validation errors for each element in the form. - * @todo replace __form with the name of the form, once attributes are implemented - */ - function getValidationErrors($withElements = true) - { - $found = false; - $errors = array(); - - if ( !empty( $this->validationErrors ) ) - { - $errors['__form'] = $this->validationErrors; - $found = true; - } - - if ($withElements === false) { - return $errors; - } - - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - $name = $this->elements[$i]->getAttribute( 'name' ); - if ( $name === false ) - { - continue; - } - - $elementErrors = $this->elements[$i]->getValidationErrors(); - - if ( empty( $elementErrors ) ) - continue; - - $errors[$name] = $elementErrors; - $found = true; - } - - if ( $found ) - return $errors; - - return false; - } - - /** - * retrieves the values for all elements in the form. - * - * @access public - * @param array desired fields - * @param integer Mode that should be used to return values in groups - * @return array The values for all elements, as elementname => elementvalue. - * - * @todo remove the ugly Group check and replace with something better - * @todo implement something similar for getValidation errors - */ - function getValues( $fields = null, $type = PATFORMS_VALUES_NESTED ) - { - $values = array(); - - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - $name = $this->elements[$i]->getAttribute( 'name' ); - if ( $name === false ) { - continue; - } - - if ( is_array( $fields ) && !in_array( $name, $fields ) ) { - continue; - } - - $tmpVal = $this->elements[$i]->getValue(); - if (!is_array($tmpVal) || $this->elements[$i]->elementName != 'Group') { - $values[$name] = $tmpVal; - continue; - } - - switch ($type) { - case PATFORMS_VALUES_FLATTENED: - $values = array_merge($values, $tmpVal); - break; - case PATFORMS_VALUES_PREFIXED: - foreach ($tmpVal as $key => $val) { - $values[$name.'_'.$key] = $val; - } - break; - case PATFORMS_VALUES_NESTED: - default: - $values[$name] = $tmpVal; - break; - - } - } - return $values; - } - - /** - * sets the values for all elements in the form. Use this to fill your form with external - * data, like a db query. Caution: if you do this and set the form to submitted, the values - * will be overwritten by any values present in the $_GET or $_POST variables. - * - * @access public - * @param array $values The values for all elements, as elementname => elementvalue. - */ - function setValues( $values, $overrideUserInput = false ) - { - patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND); - foreach ($values as $elName => $value) { - $el = &$this->getElementByName($elName); - if (patErrorManager::isError($el)) { - continue; - } - if ($overrideUserInput === true) { - $el->setValue($value); - } else { - $el->setDefaultValue($value); - } - } - patErrorManager::popExpect(); - return true; - } - - /** - * retrieves the current mode of the form - * - * @access public - * @return string $mode The current form mode - * @see setMode() - * @see $mode - */ - function getMode() - { - return $this->mode; - } - - /** - * returns the locale that is currently set for the form. - * - * @access public - * @return string $locale The locale. - * @see setLocale() - * @see $locale - */ - function getLocale() - { - return $this->locale; - } - - /** - * retrieves the current format of the form - * - * @access public - * @return string $format The current form format - * @see setFormat() - * @see format - */ - function getFormat() - { - return $this->format; - } - - /** - * retrieves the current method of the form - * - * @access public - * @return string $method The request method - * @see setMethod() - */ - function getMethod() - { - return $this->getAttribute( 'method' ); - } - - /** - * retrieves the current action of the form - * - * @access public - * @return string $action Action of the form - * @see setAction() - */ - function getAction() - { - $action = $this->getAttribute( 'action' ); - if ( !empty( $action ) ) - return $action; - return $_SERVER['PHP_SELF']; - } - - /** - * adds an atribute to the form's attribute collection. If the attribute - * already exists, it is overwritten. - * - * @access public - * @param string $attributeName The name of the attribute to add - * @param string $atributeValue The value of the attribute - */ - function setAttribute( $attributeName, $attributeValue ) - { - if ( !isset( $this->attributeDefinition[$attributeName] ) ) - { - patErrorManager::raiseNotice( - PATFORMS_NOTICE_ATTRIBUTE_NOT_SUPPORTED, - "The attribute '".$attributeName."' is not supported by the form, skipped it. [".get_class( $this )."]" - ); - return true; - } - - $this->attributes[$attributeName] = $attributeValue; - - return true; - } - - /** - * adds several attributes at once to the form's attribute collection. - * Any existing attributes will be overwritten. - * - * @access public - * @param array $attributes The attributes to add - * @see setAttribute() - */ - function setAttributes( $attributes ) - { - if ( !is_array( $attributes ) ) - { - return patErrorManager::raiseError( - PATFORMS_NOTICE_ARRAY_EXPECTED, - "setAttributes: array expected" - ); - } - - foreach ( $attributes as $attributeName => $attributeValue ) - { - $this->setAttribute( $attributeName, $attributeValue ); - } - - return true; - } - - /** - * retrieves the value of a form attribute. - * - * @access public - * @param string $attribute The name of the attribute to retrieve - * @return mixed $attributeValue The value of the attribute, or false if it does not exist in the attributes collection. - * @see setAttribute() - */ - function getAttribute( $attribute ) - { - if ( !isset( $this->attributes[$attribute] ) ) - { - return false; - } - - return $this->attributes[$attribute]; - } - - /** - * retrieves all attributes of the form, or only the specified attributes. - * - * @access public - * @param array $attributes Optional: The names of the attributes to retrieve. Only the attributes that exist will be returned. - * @return array $result The attributes - * @see getAttribute() - */ - function getAttributes( $attributes = array() ) - { - if ( empty( $attributes ) ) - { - return $this->attributes; - } - - $result = array(); - foreach ( $attributes as $attribute ) - { - if ( $attributeValue = $this->getAttribute( $attribute ) ) - { - $result[$attribute] = $attributeValue; - } - } - - return $result; - } - - /** - * Loads the default attribute values into the attributes collection. Done directly - * on startup (in the consructor). - * - * The action defaults to the path of the current script, with session - * ID appended automatically, if SID has been defined. - * - * @access public - * @return bool $success Always returns true. - * @see $attributeDefaults - */ - function loadAttributeDefaults() - { - foreach ( $this->attributeDefinition as $attributeName => $attributeDef ) - { - if ( isset( $attributeDef['default'] ) ) - { - $this->attributes[$attributeName] = $attributeDef['default']; - } - - if ( $attributeName == 'action' ) - { - $this->attributes[$attributeName] = $_SERVER['PHP_SELF']; - /** - * session has been started, append session ID - */ - if ( defined( 'SID' ) ) - $this->attributes[$attributeName] .= '?' . SID; - } - } - - return true; - } - - /** - * retrieves the form's current submitted state. - * - * If autoValidate is used, it will check for the submitVar and - * set the submitted flag accordingly - * - * @access public - * @return bool $state True if it has been submitted, false otherwise. - * @see setSubmitted(), setAutoValidate() - * @see submitted - */ - function isSubmitted() - { - if ( $this->submitted === true ) - { - return true; - } - - if ( !isset( $this->submitVar ) ) - { - return false; - } - - if ( !$this->autoValidate ) - { - return false; - } - - if ( isset( $_GET[$this->submitVar] ) || isset( $_POST[$this->submitVar] ) ) - { - $this->setSubmitted( true ); - } - - return $this->submitted; - } - - /** - * Creates a new patForms_Creator object - * - * @static - * @access public - * @return object $creator The creator object, or a patError object on failure - */ - function createCreator( $type ) - { - return patForms::_createModule( 'Creator', $type ); - } - - /** - * get the element name of the form - * - * @access public - * @return string name of the form - */ - function getElementName() - { - return $this->elementName; - } - - /** - * get next error offset - * - * @access public - * @return integer - */ - function getErrorOffset( $requiredCodes = 100 ) - { - $offset = $this->nextErrorOffset; - $this->nextErrorOffset = $this->nextErrorOffset + $requiredCodes; - return $offset; - } - - /** - * add error codes and messages for validator method - * - * @access public - * @param array defintions - * @param integer offset for the error codes - */ - function addValidatorErrorCodes( $defs, $offset = 1000 ) - { - foreach ( $defs as $lang => $codes ) - { - if ( !isset( $this->validatorErrorCodes[$lang] ) ) - { - $this->validatorErrorCodes[$lang] = array(); - } - - foreach ( $codes as $code => $message ) - { - $this->validatorErrorCodes[$lang][($offset+$code)] = $message; - } - } - } - - /** - * add a validation error to the whole form - * - * This can be achieved by adding a validation rule to the form. - * - * @access public - * @param integer $code - * @param array $vars fill named placeholder with values - * @return boolean $result true on success - * @see addRule() - */ - function addValidationError( $code, $vars = array() ) - { - $error = false; - $lang = $this->locale; - $element = $this->getElementName(); - - // find error message for selected language - while ( true ) - { - // error message matches language code - if ( isset( $this->validatorErrorCodes[$lang][$code] ) ) - { - $error = array( "element" => $element, "code" => $code, "message" => $this->validatorErrorCodes[$lang][$code] ); - break; - } - // no message found and no fallback-langauage available - else if ( $lang == "C" ) - { - break; - } - - $lang_old = $lang; - - // look for other languages - if ( strlen( $lang ) > 5 ) - { - list( $lang, $trash ) = explode( ".", $lang ); - } - else if ( strlen( $lang ) > 2 ) - { - list( $lang, $trash ) = explode( "_", $lang ); - } - else - { - $lang = "C"; - } - - // inform developer about missing language - patErrorManager::raiseNotice( - PATFORMS_NOTICE_VALIDATOR_ERROR_LOCALE_UNDEFINED, - "Required Validation Error-Code for language: $lang_old not available. Now trying language: $lang", - "Add language definition in used element or choose other language" - ); - - } - - // get default Error! - if ( !$error ) - { - patErrorManager::raiseWarning( - PATFORMS_WARNING_VALIDATOR_ERROR_UNDEFINED, - "No Error Message for this validation Error was defined", - "Review the error-definition for validation-errors in your element '$element'." - ); - $error = array( "element" => $element, "code" => 0, "message" => "Unknown validation Error" ); - } - - // insert values to placeholders - if ( !empty( $vars ) ) - { - foreach ( $vars as $key => $value ) - { - $error["message"] = str_replace( "[". strtoupper( $key ) ."]", $value, $error["message"] ); - } - } - - array_push( $this->validationErrors, $error ); - $this->valid = false; - return true; - } - - /** - * retreives a new element id, used to give each added element a unique id for this - * form (id can be overwritten by setting the id attribute specifically). - * - * @access private - * @return int $elementId The new element id. - */ - function getElementId() - { - $this->elementCounter++; - return 'pfo'.$this->elementCounter; - } - - /** - * attach an observer - * - * @access public - * @param object patForms_Observer - * @see createObserver() - * @uses patForms_Element::createObserver() - */ - function attachObserver( &$observer, $where = PATFORMS_OBSERVER_ATTACH_TO_ELEMENTS ) - { - /** - * attach the observer to all elements - */ - if ( ( $where & PATFORMS_OBSERVER_ATTACH_TO_ELEMENTS ) == PATFORMS_OBSERVER_ATTACH_TO_ELEMENTS ) - { - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - $this->elements[$i]->attachObserver( $observer ); - } - } - - /** - * attach the observer to the form - */ - if ( ( $where & PATFORMS_OBSERVER_ATTACH_TO_FORM ) == PATFORMS_OBSERVER_ATTACH_TO_FORM ) - { - $this->observers[] = &$observer; - } - return true; - } - - /** - * Retrieve the content for the start of the form, including any - * additional content, e.g. global scripts if the scripts option - * is enabled. - * - * @access public - * @return string $formStart The form start content - * @todo use format to build a dynamic method - */ - function serializeStart() - { - $methodName = "serializeStart".ucfirst( $this->getFormat() ).ucfirst( $this->getMode() ); - - if ( !method_exists( $this, $methodName ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_METHOD_FOR_MODE_NOT_AVAILABLE, - "Method for patForms mode '".$this->getMode()."' (".$methodName.") is not available." - ); - } - - return $this->$methodName(); - } - - /** - * Serializes the form's start element for html format, in default mode. - * - * @access private - * @return mixed $formStart The serialized start content, or a patError object. - */ - function serializeStartHtmlDefault() - { - $attributes = $this->getAttributesFor( $this->format ); - if ( patErrorManager::isError( $attributes ) ) - { - return $attributes; - } - - $content = patForms_Element::createTag( 'form', 'opening', $attributes ); - - if ( $this->optionEnabled( 'scripts' ) ) - { - $content .= $this->getScripts(); - } - - return $content; - } - - /** - * Serializes the form's start element for html format, in readonly mode. - * - * @access private - * @return mixed $formStart The serialized start content, or a patError object. - */ - function serializeStartHtmlReadonly() - { - $attributes = $this->getAttributesFor( $this->format ); - if ( patErrorManager::isError( $attributes ) ) - { - return $attributes; - } - - return patForms_Element::createTag( 'form', 'opening', $attributes ); - } - - /** - * Retrieve the content for the end of the form. - * - * @access public - * @return string $formEnd The form end content - */ - function serializeEnd() - { - $methodName = "serializeEnd".ucfirst( $this->getFormat() ).ucfirst( $this->getMode() ); - - if ( !method_exists( $this, $methodName ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_METHOD_FOR_MODE_NOT_AVAILABLE, - "Method for patForms mode '".$this->getMode()."' (".$methodName.") is not available." - ); - } - - return $this->$methodName(); - } - - /** - * Retrieves the content for the end of the form for html format, - * in default mode. - * - * @access private - * @return string $formEnd The form end content - */ - function serializeEndHtmlDefault() - { - return patForms_Element::createTag( 'form', 'closing' ); - } - - /** - * Retrieves the content for the end of the form for html format, - * in readonly mode. - * - * @access private - * @return string $formEnd The form end content - */ - function serializeEndHtmlReadonly() - { - return $this->serializeEndHtmlDefault(); - } - - /** - * validates the current attribute collection according to the attributes definition - * and the given output format, and returns the list of valid attributes. - * - * @access private - * @param string $format The output format to retrieve the attributes for. - * @return mixed $attributes The list of attributes, or false if failed. - */ - function getAttributesFor( $format ) - { - $attributes = array(); - - foreach ( $this->attributeDefinition as $attributeName => $attributeDef ) - { - if ( !isset( $this->attributes[$attributeName] ) ) - { - if ( $attributeDef["required"] ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_ATTRIBUTE_REQUIRED, - 'patForms needs the attribute "'.$attributeName.'" to be set.', - 'See the patForms attribute definition of patForms for a complete attribute reference.' - ); - } - - continue; - } - - $attributeValue = $this->attributes[$attributeName]; - - if ( !in_array( $format, $attributeDef["outputFormats"] ) ) - { - continue; - } - - if ( isset( $attributeDef["format"] ) ) - { - if ( !$this->_checkAttributeFormat( $attributeValue, $attributeDef["format"] ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_CAN_NOT_VERIFY_FORMAT, - "Format '".$attributeDef["format"]."' could not be verified for patForms attribute '".$attributeName."' => '".$attributeValue."'" - ); - } - } - - $attributes[$attributeName] = $attributeValue; - } - - return $attributes; - } - - /** - * checks the format of an attribute value according to the given format. - * - * @access private - * @param mixed $attributeValue The attribute value to check - * @param string $format The format to check the attribute value against - * @return bool $result True if format check succeeded, false otherwise. - * @see createAttributes() - * @todo Implement this method sometime - */ - function _checkAttributeFormat( $attributeValue, $format ) - { - return true; - } - - /** - * Enables a patForms option. - * - * See the {@link $options} property for an exhaustive list of available options. - * - * @access public - * @param string $option The option to enable - * @param array $params Optional parameters for the option - * @return mixed $result True on success, patError object otherwise. - * @see disableOption() - * @see optionEnabled() - * @see $options - */ - function enableOption( $option, $params = array() ) - { - if ( !in_array( $option, array_keys( $this->options ) ) ) - { - return patErrorManager::raiseNotice( - PATFORMS_NOTICE_INVALID_OPTION, - 'The option "'.$option.'" is not a valid patForms option.' - ); - } - - $this->options[$option]['enabled'] = true; - $this->options[$option]['params'] = $params; - - // now update all available elements too - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) - { - $this->elements[$i]->enableOption( $option, $params ); - } - - return true; - } - - /** - * Disables a patForms option - * - * See the {@link $options} property for an exhaustive list of available options. - * - * @access public - * @param string $option The option to disable - * @return mixed $result True on success, patError object otherwise. - * @see enableOption() - * @see optionEnabled() - * @see $options - */ - function disableOption( $option ) - { - if ( !in_array( $option, array_keys( $this->options ) ) ) - { - return patErrorManager::raiseNotice( - PATFORMS_NOTICE_INVALID_OPTION, - 'The option "'.$option.'" is not a valid patForms option.' - ); - } - - $this->options[$option]['enabled'] = false; - - // now update all available elements too - $cnt = count( $this->elements ); - for ( $i=0; $i < $cnt; $i++ ) - { - $this->elements[$i]->disableOption( $option ); - } - - return true; - } - - /** - * Checks whether the given option is enabled. - * - * @access public - * @param string $option The option to check - * @return bool $enabled True if enabled, false otherwise. - * @see enableOption() - * @see disableOption() - * @see $options - */ - function optionEnabled( $option ) - { - if ( !isset( $this->options[$option] ) ) - return false; - - return $this->options[$option]['enabled']; - } - - /** - * Set the form to auto validate - * - * If you use this method, patForms will check the _GET and _POST variables - * for the variable you specified. If it is set, patForms assumes, that - * the form has been submitted. - * - * When creating a start tag for the form, the value will be inserted automatically. - * - * @access public - * @param string $submitVar - */ - function setAutoValidate( $submitVar ) - { - $this->autoValidate = true; - $this->submitVar = $submitVar; - } - - /** - * register a new event - * - * After registering an event, you may register one or more - * event handlers for this event an then trigger the event. - * - * This lets you extend the functionality of patForms. - * - * @access public - * @param string event name - * @return boolean true, if event could be registered - * @see registerEventHandler() - * @see triggerEvent() - */ - function registerEvent( $name ) - { - $event = 'on' . $name; - if ( in_array( $event, $this->_validEvents ) ) - { - return patErrorManager::raiseNotice( - PATFORMS_NOTICE_EVENT_ALREADY_REGISTERED, - 'Event "'.$event.'" already has been registered or is built-in event' - ); - } - array_push( $this->_validEvents, $event ); - return true; - } - - /** - * Register an event handler - * - * An event handler can be any valid PHP callback. You may pass - * one of the following values: - * - string functionname to call a globally declared function - * - array( string classname, string methodname) to call a static method - * - array( object obj, string methodname) to call a method of an object - * - * When the handler is called, two parameters will be passed: - * - object form : a patForms object - * - string event : the name of the event has should be handled. - * - * An event handler should always return true. If false is returned, - * the event will be cancelled. - * - * Currently handlers for the following events can be registered: - * - onSubmit - * - onSuccess - * - onError - * - * @access public - * @param string event name - * @param mixed event handler - * @return boolean true, if the handler could be registered - * @see triggerEvent() - * @see $_validEvents - */ - function registerEventHandler( $event, $handler ) - { - if ( !in_array( $event, $this->_validEvents ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_UNKNOWN_EVENT, - 'Cannot register event handler for unknown event "' . $event .'".' - ); - } - - if ( !is_callable( $handler ) ) - { - return patErrorManager::raiseError( - PATFORMS_ERROR_INVALID_HANDLER, - 'Event handler is not callable.' - ); - } - - if ( !isset( $this->_eventHandler[$event] ) ) - { - $this->_eventHandler[$event] = array(); - } - - $this->_eventHandler[$event][] = &$handler; - return true; - } - - /** - * set event handler object. - * - * An event handler object is used to handle all - * registered events. The object has to provide methods - * for all events it should handle, the names of the methods - * have to be the same as the names of the events. - * - * @access public - * @param object event handler object - * @param array method names, used to change the names of the methods - * @return boolean - */ - function registerEventHandlerObject( &$obj, $methods = array() ) - { - if ( empty( $methods ) ) - { - foreach ( $this->_validEvents as $event ) - { - if ( !method_exists( $obj, $event ) ) - continue; - - $methods[$event] = $event; - } - } - - foreach ( $methods as $event => $method ) - { - if ( !isset( $this->_eventHandler[$event] ) ) - { - $this->_eventHandler[$event] = array(); - } - - $this->_eventHandler[$event][] = array( &$obj, $method ); - } - - return true; - } - - /** - * Trigger an event - * - * In most cases there's no need to call this event - * from outside the class. The method is declared public - * to allow you to trigger custom events. - * - * @access public - * @param string Event name. The event name must not contain 'on', as this will be - * prefixed automatically. - */ - function triggerEvent( $event ) - { - $handlerName = 'on' . $event; - - if ( !isset( $this->_eventHandler[$handlerName] ) || empty( $this->_eventHandler[$handlerName] ) ) - { - return true; - } - - $cnt = count( $this->_eventHandler[$handlerName] ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $result = call_user_func( $this->_eventHandler[$handlerName][$i], $this, $event ); - if ( $result == false ) - { - return $result; - } - } - return true; - } - - /** - * Serializes the entire form to XML, all elements included - * - * @access public - * @param string $namespace Optional namespace to use for the tags - * @return string $xml The XML representation of the form - * @see patForms_Element::toXML() - * @todo needs patForms_Element, maybe switch to PEAR::XML_Util - */ - function toXML( $namespace = null ) - { - $tagName = 'Form'; - - // prepend Namespace - if ( $namespace != null ) - { - $tagName = $namespace.':'.$tagName; - } - - // get all attributes - $attributes = $this->getAttributes(); - - // create valid XML attributes - foreach ( $attributes as $key => $value ) - { - $attributes[$key] = strtr( $value, $this->xmlEntities ); - } - - $elements = ''; - for ( $i = 0; $i < $this->elementCounter; $i++ ) - { - $elements .= $this->elements[$i]->toXML( $namespace ); - } - - return patForms_Element::createTag( $tagName, "full", $attributes, $elements ); - } - - /** - * Set a static property. - * - * Static properties are stored in an array in a global variable, - * until PHP5 is ready to use. - * - * @static - * @param string property name - * @param mixed property value - * @see getStaticProperty() - */ - function setStaticProperty( $property, &$value ) - { - $GLOBALS["_patForms"][$property] = &$value; - } - - /** - * Get a static property. - * - * Static properties are stored in an array in a global variable, - * until PHP5 is ready to use. - * - * @static - * @param string property name - * @return mixed property value - * @see setStaticProperty() - */ - function &getStaticProperty( $property ) - { - if ( isset( $GLOBALS["_patForms"][$property] ) ) - { - return $GLOBALS["_patForms"][$property]; - } - return patErrorManager::raiseWarning( - PATFORMS_ERROR_NO_STATIC_PROPERTY, - 'Static property "'.$property.'" could not be retreived, it does not exist.' - ); - } - - /** - * Retrieves the form's name - * - * If no name is set, it will use 'patForms' as name. - * - * @access public - * @return string $name The name of the form. - */ - function getName() - { - if ( isset( $this->attributes['name'] ) ) - return $this->attributes['name']; - return 'patForms'; - } - - /** - * get the javascript for the form - * - * This is still in alpha state. It will later - * allow client side validation if the element - * provides this feature. - * - * @access public - * @return string javascript needed by the form - * @todo make this dependent on the format - * @todo add changeable linebreaks - */ - function getScripts() - { - foreach ($this->elements as $element) { - $element->registerJavascripts($this); - } - - $globalJavascript = implode ("", $this->javascripts['global']); - $instances = implode ("", $this->javascripts['instance']); - - $script = ''; - - return $script; - - /* - $globalJavascript = ''; - $instances = ''; - - $displayedTypes = array(); - - $cnt = count( $this->elements ); - for ( $i = 0; $i < $cnt; ++$i ) - { - $instances .= $this->elements[$i]->getInstanceJavascript(); - - $type = $this->elements[$i]->getElementName(); - if ( in_array( $type, $displayedTypes ) ) - continue; - - array_push( $displayedTypes, $type ); - $globalJavascript .= $this->elements[$i]->getGlobalJavascript(); - } - - $cnt = count( $this->_rules ); - for ( $i = 0; $i < $cnt; ++$i ) - { - $instances .= $this->_rules[$i]['rule']->getInstanceJavascript(); - - - $type = $this->_rules[$i]['rule']->getRuleName(); - if ( in_array( $type, $displayedTypes ) ) - continue; - - array_push( $displayedTypes, $type ); - - $globalJavascript .= $this->_rules[$i]['rule']->getGlobalJavascript(); - } - - $script = ''; - - return $script; - */ - } - - private $javascripts = array( - 'global' => array(), - 'instance' => array() - ); - - function registerGlobalJavascript($type, $script) { - - $this->javascripts['global'][$type] = $script; - } - - function registerInstanceJavascript($script) { - - $this->javascripts['instance'][] = $script; - } - - /** - * anounce a change in the element to all observers - * - * @access private - * @param string property that changed - * @param mixed new value of the property - */ - function _announce( $property, $value ) - { - $cnt = count( $this->observers ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $this->observers[$i]->notify( $this, $property, $value ); - } - return true; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Definition.php b/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Definition.php deleted file mode 100644 index c2ecb4a96..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Definition.php +++ /dev/null @@ -1,42 +0,0 @@ - $definition->name - )); - - foreach ($definition->elements as $el) { - $element = &$form->createElement($el['name'], $el['type'], null); - if (!empty($el['attributes']['datasource'])) { - $ds = $el['attributes']['datasource']; - unset($el['attributes']['datasource']); - $element->setDatasource(new $ds['name']($ds)); - } - // patForms will choke when we try to set attributes that - // don't exist for an element type. So we'll have to ask. - foreach ($el['attributes'] as $name => $value) { - if ($element->hasAttribute($name)) { - $element->setAttribute($name, $value); - } - } - if (isset($el['rules'])) { - foreach ($el['rules'] as $rule) { - $element->addRule(new $rule['type']($rule)); - } - } - $form->addElement($element); - } - if (!is_null($object)) { - $form->setValues($object->toArray()); - } - if ($definition->autoValidate) { - $form->setAutoValidate($definition->autoValidate); - } - - return $form; - } - -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Propel.php b/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Propel.php deleted file mode 100644 index 61876da98..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/Propel.php +++ /dev/null @@ -1,132 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Creator_Propel extends patForms_Creator -{ - private static $creoleTypeMapping = array( - CreoleTypes::BOOLEAN =>'Radio', // BOOLEAN = 1; - CreoleTypes::BIGINT =>'String', // BIGINT = 2; - CreoleTypes::SMALLINT =>'String', // SMALLINT = 3; - CreoleTypes::TINYINT =>'String', // TINYINT = 4; - CreoleTypes::INTEGER =>'String', // INTEGER = 5; - CreoleTypes::CHAR =>'String', // CHAR = 6; - CreoleTypes::VARCHAR =>'String', // VARCHAR = 7; - CreoleTypes::FLOAT =>'String', // FLOAT = 8; - CreoleTypes::DOUBLE =>'String', // DOUBLE = 9; - CreoleTypes::DATE =>'Date', // DATE = 10; - CreoleTypes::TIME =>'String', // TIME = 11; - CreoleTypes::TIMESTAMP =>'Date', // TIMESTAMP = 12; - CreoleTypes::VARBINARY =>'String', // VARBINARY = 13; - CreoleTypes::NUMERIC =>'String', // NUMERIC = 14; - CreoleTypes::BLOB =>'String', // BLOB = 15; - CreoleTypes::CLOB =>'String', // CLOB = 16; - CreoleTypes::TEXT =>'Text', // TEXT = 17; - CreoleTypes::LONGVARCHAR =>'Text', // LONGVARCHAR = 17; - CreoleTypes::DECIMAL =>'String', // DECIMAL = 18; - CreoleTypes::REAL =>'String', // REAL = 19; - CreoleTypes::BINARY =>'String', // BINARY = 20; - CreoleTypes::LONGVARBINARY =>'String', // LONGVARBINARY = 21; - CreoleTypes::YEAR =>'String', // YEAR = 22; - CreoleTypes::ARR =>'String', - CreoleTypes::OTHER =>'String' - ); - - /** - * Create a form from a propel instance - * - * @access public - * @param mixed $object An instance of a Propel object - * @param array $options Any options the creator may need - * @return object $form The patForms object, or a patError object on failure. - */ - function &create( $object, $options = array() ) - { - // Propel stuff - $propel_peer = $object->getPeer(); - $propel_mapBuilder = $propel_peer->getMapBuilder(); // Not sure if we're gonna need this one - $propel_tablename = constant(get_class($propel_peer) . '::TABLE_NAME'); - $propel_tableMap = $propel_mapBuilder->getDatabaseMap()->getTable($propel_tablename); - - // The form - $form =& patForms::createForm( null, array( 'name' => 'patForms_Creator_Form' ) ); - - $propel_cols = $propel_tableMap->getColumns(); - foreach ($propel_cols as $propel_colname => $propel_col) { - - // phpName can be altered by editing the schema.xml, - // thus I think, we should lowercase()/ucfirst() this - $propel_colname = strtolower($propel_colname); - $el_displayname = ucFirst($propel_colname); - // this could be omitted of course, but I think, it's a - // convenient way to get more safe request properties - $el_name = $propel_tablename . '[' . $propel_colname . ']'; - - $el_attr = array( - 'edit' => 'yes', - 'title' => $el_displayname, - 'label' => $el_displayname, - 'name' => $el_name, - 'description' => $el_displayname - ); - - //// Obsolete ? - // Parse column info to element type info - //$type_info = $this->parseTypeInfoFromColumn($propel_col); - // Merge extra element attributes - //$el_attr = array_merge( $el_attr, $type_info['attributes'] ); - - // Is the element required ? Can we retrieve this info from the Column object ? - $el_attr['required'] = 'yes'; - // Value: for now we use default to set the value. Is there a better (more correct) way to do this ? - $el_attr['default'] = $object->{'get'.$propel_col->getPhpName()}(); - - if ($propel_col->isPrimaryKey()) { - $el_type = 'hidden'; - } else { - $el_type = self::$creoleTypeMapping[$propel_col->getCreoleType()]; - } - - $el = &$form->createElement($el_name, $el_type, null); - // patForms will choke when we try to set attributes - // that don't match the element type. So we'll ask. - foreach ($el_attr as $name => $value) { - if ($el->hasAttribute($name)) { - $el->setAttribute($name, $value); - } - } - $form->addElement($el); - } - - return $form; - } - - // Seems this function will become obsolete if we use the static $creoleTypeMapping - function parseTypeInfoFromColumn ( $column ) { - - return array( - 'type' => 'String', - 'attributes' => array() - ); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/_propel_creator_test.php b/airtime_mvc/library/propel/contrib/pat/patForms/Creator/_propel_creator_test.php deleted file mode 100644 index 33f108ed7..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Creator/_propel_creator_test.php +++ /dev/null @@ -1,201 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ - - /** - * Main examples prepend file, needed *only* for the examples framework! - */ - //include_once 'patExampleGen/prepend.php'; - //$exampleGen->displayHead( 'Example' ); - - include('include/common.php'); - - // EXAMPLE START ------------------------------------------------------ - - /** - * main patForms class - */ - require_once ('patForms.php'); - - /** - * patErrorManager class - */ - require_once ('patErrorManager.php'); - - - // create the creator :) - $creator = &patForms::createCreator( 'Propel' ); - - // create the form object from the given propel Object class instance - - require_once('model/general/UserProfile.php'); - $userProfile = UserProfilePeer::retrieveByPK(1); - $form =& $creator->create( $userProfile ); - - //$wikipage = WikipagePeer::retrieveByPK('wiki'); - //$form =& $creator->create($wikipage); - - // create the needed renderer - $renderer =& patForms::createRenderer( "Array" ); - - // set the renderer - $form->setRenderer( $renderer ); - - // use auto-validation - $form->setAutoValidate( 'save' ); - - // serialize the elements - $elements = $form->renderForm(); - - - // ERROR DISPLAY ------------------------------------------------------ - if ( $form->isSubmitted() ) - { - displayErrors( $form ); // see patExampleGen/customFunctions.php - } - - // DISPLAY FORM ------------------------------------------------------ - displayForm( $form, $elements ); // see patExampleGen/customFunctions.php - - /** - * Takes a patForms object, asks it if there are any validation - * errors and displays them if need be. - * - * NOTE: this is just a helper method for our examples collection, - * so that you may concentrate on the relevant parts of the examples. - * It does in no way represent the way it should be done :) - * - * @access public - * @param object &$form The patForms object to use - */ - function displayErrors( &$form ) - { - // get the errors from the form object - if there are none, - // this returns false so it is easy to check if there are any. - $errors = $form->getValidationErrors(); - - // if there are any errors, display them. - if ( $errors ) - { - echo '
'; - echo '
Validation failed
'; - echo '
'; - - // the errors collection is an associative array with the - // field names as keys, so we go through that. - foreach ( $errors as $elementName => $elementErrors ) - { - $element =& $form->getElementByName( $elementName ); - - // each element can have more than one error - this - // is rare, but can happen so this is an indexed array - // with one error in each row. - foreach ( $elementErrors as $row => $error ) - { - echo '
'; - echo ' '.$element->getAttribute( 'label' ).': '.$error['message'].'('.$error['element'].' element error #'.$error['code'].')
'; - echo '
'; - } - } - - echo '
'; - echo '
'; - } - // no errors, tell the world everything is fine - else - { - - echo '
Validation successful.
'; - } - } - - - /** - * Displays a standard form from the examples collection when the - * form is rendered via the array renderer. Does not work for any - * other examples. - * - * NOTE: this is just a helper method for our examples collection, - * so that you may concentrate on the relevant parts of the examples. - * It does in no way represent the way it should be done :) - * - * @access public - * @param object &$form The current form object - * @param array $elements The rendered elements from the - * @return - * @see - */ - function displayForm( &$form, $elements ) - { - // output the opening form tag - echo $form->serializeStart(); - - echo "\n"; - foreach ( $elements as $element ) { - } - echo "
\n"; - - // display all elements - foreach ( $elements as $element ) - { - if (!isset($element['description'])) { - // would choke a warning on hidden fields - // strange enough, we've no $element['type'] for hidden inputs - echo $element['element'] . "\n"; - continue; - } - - echo '
'; - echo $element['label']."
"; - echo "
".$element["element"]."
"; - echo "".$element["description"]."
"; - - echo '
'; - - //} else { - //echo "".$element['description']."".$element['element']."\n"; - //} - } - - // submit button, closing form tag - echo '

'; - echo $form->serializeEnd(); - - - // form submitted? display all form values - if ( $form->isSubmitted() ) { - $els =& $form->getElements(); - $cnt = count( $els ); - - echo '
'; - echo '
Submitted form values
'; - echo '
'; - echo ' '; - - for ( $i = 0; $i < $cnt; $i++ ) { - echo ''; - echo ' '; - echo ''; - } - - echo '
'.$els[$i]->getAttribute('label').' : '.$els[$i]->getValue().'
'; - echo '
'; - echo '
'; - } - } diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Datasource/Propel.php b/airtime_mvc/library/propel/contrib/pat/patForms/Datasource/Propel.php deleted file mode 100644 index 08c059535..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Datasource/Propel.php +++ /dev/null @@ -1,70 +0,0 @@ -peername = $conf['peername']; - $this->label = $conf['label']; - $this->value = $conf['value']; - } - - public function getValues() { - - $map = call_user_func(array($this->peername, 'getPhpNameMap')); - - $c = new Criteria(); - $c->clearSelectColumns(); - - foreach (array($this->label, $this->value) as $arr) { - foreach ($arr['members'] as $member) { - if (is_array($member)) { - foreach ($member as $member) { - $c->addSelectColumn(constant($this->peername . '::' . $map[$member])); - } - } else { - $c->addSelectColumn(constant($this->peername . '::' . $map[$member])); - } - } - } - - if (isset($this->label['initial']) OR isset($this->value['initial'])) { - $label = isset($this->label['initial']) ? $this->label['initial'] : ''; - $value = isset($this->value['initial']) ? $this->value['initial'] : ''; - $result[] = array( - 'value' => $value, - 'label' => $label - ); - } - - $rs = AuthorPeer::doSelectStmt($c); - $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($rs->next()) { - $row = $rs->getRow(); - foreach (array('label', 'value') as $key) { - $arr = $this->$key; - $params = array($arr['mask']); - foreach ($arr['members'] as $member) { - if (is_array($member)) { - foreach ($member as $member) { - $field_name = strtolower($map[$member]); // TODO is this always true? - $params[] = $row[$field_name]; - } - } else { - $field_name = strtolower($map[$member]); // TODO is this always true? - $params[] = $row[$field_name]; - } - } - $$key = call_user_func_array('sprintf', $params); - $tmp[$key] = $$key; - } - $result[] = $tmp; - } - - return $result; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Definition.php b/airtime_mvc/library/propel/contrib/pat/patForms/Definition.php deleted file mode 100644 index d02ab5b78..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Definition.php +++ /dev/null @@ -1,122 +0,0 @@ -data['name'] = $name; - $this->data['mtime'] = time(); - if ($autoValidate) { - $this->data['autoValidate'] = $autoValidate; - } - } - - static public function create($conf) { - // TODO - } - - public function __get($name) { - - if (isset($this->data[$name])) { - return $this->data[$name]; - } - } - - // TODO change protocol to addElement(array $element) - public function addElement($name, $type, $attributes = array(), $rules = array()) { - - if (is_array($type)) { - extract($type); - } - - $this->data['elements'][$name]['name'] = $name; - $this->data['elements'][$name]['type'] = $type; - - foreach ($attributes as $key => $value) { - $value = $this->cast($value); - $this->data['elements'][$name]['attributes'][$key] = $value; - } - foreach ($rules as $key => $rule) { - $this->data['elements'][$name]['rules'][$key] = $rule; - } - } - - public function load($filename) { - - $data = $this->read($filename); - - foreach ($data as $key => $value) { - if ($key == 'elements') { - foreach ($value as $name => $element) { - $this->addElement($name, $element); - } - } else { - $this->data[$key] = $this->cast($value); - } - } - } - - public function save($filename) { - - $this->write($filename, $this->data); - } - - protected function read($filename) { - - $xml = file_get_contents($filename); - $unserializer = new XML_Unserializer(); - $unserializer->unserialize($xml); - return $unserializer->getUnserializedData(); - } - - protected function write($filename, $data) { - - $serializer = new XML_Serializer(array ( - 'addDecl' => true, - 'encoding' => 'ISO-8859-1', - 'indent' => ' ', - 'rootName' => 'form', - 'defaultTagName' => 'tag' - )); - $serializer->serialize($data); - $xml = $serializer->getSerializedData(); - - $fp = fopen($filename, 'w+'); - fputs($fp, $xml); - fclose($fp); - } - - protected function cast($value) { - - return $value; - - // seems as if patForms_Element(s) are broken here - // e.g. in patForms_Element_Text::serializeHtmlDefault() - // at line 245 if ( $this->attributes['display'] == 'no' ) - // will result to true if the display attribute is set - // to (php boolean) true - // so casting the 'true'/'false' and 'yes'/'no' values - // would break intended behaviour here - - if (is_array($value) OR is_bool($value)) { - return $value; - } - if ($value === 'true') { - return true; - } - if ($value === 'false') { - return false; - } - if (preg_match('/^[+-]?[0-9]+$/', $value)) { - settype($value, 'int'); - return $value; - } - if (preg_match('/^[+-]?[0-9]*\.[0-9]+$/', $value)) { - settype($value, 'double'); - return $value; - } - return $value; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Definition/Propel.php b/airtime_mvc/library/propel/contrib/pat/patForms/Definition/Propel.php deleted file mode 100644 index d2ecbe0a0..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Definition/Propel.php +++ /dev/null @@ -1,165 +0,0 @@ - 'Switch', // BOOLEAN = 1; - CreoleTypes::BIGINT => 'String', // BIGINT = 2; - CreoleTypes::SMALLINT => 'String', // SMALLINT = 3; - CreoleTypes::TINYINT => 'String', // TINYINT = 4; - CreoleTypes::INTEGER => 'String', // INTEGER = 5; - CreoleTypes::CHAR => 'String', // CHAR = 6; - CreoleTypes::VARCHAR => 'String', // VARCHAR = 7; - CreoleTypes::FLOAT => 'String', // FLOAT = 8; - CreoleTypes::DOUBLE => 'String', // DOUBLE = 9; - CreoleTypes::DATE => 'String', // DATE = 10; - CreoleTypes::TIME => 'String', // TIME = 11; - CreoleTypes::TIMESTAMP => 'Date', // TIMESTAMP = 12; - CreoleTypes::VARBINARY => 'String', // VARBINARY = 13; - CreoleTypes::NUMERIC => 'String', // NUMERIC = 14; - CreoleTypes::BLOB => 'Text', // BLOB = 15; - CreoleTypes::CLOB => 'Text', // CLOB = 16; - CreoleTypes::TEXT => 'Text', // TEXT = 17; - CreoleTypes::LONGVARCHAR => 'Text', // LONGVARCHAR = 17; - CreoleTypes::DECIMAL => 'String', // DECIMAL = 18; - CreoleTypes::REAL => 'String', // REAL = 19; - CreoleTypes::BINARY => 'String', // BINARY = 20; - CreoleTypes::LONGVARBINARY => 'Text', // LONGVARBINARY = 21; - CreoleTypes::YEAR => 'String', // YEAR = 22; - CreoleTypes::ARR => 'String', - CreoleTypes::OTHER => 'String' - ); - - private static $validatorTypeMap = array( - 'unique' => null, - 'minLength' => 'patForms_Rule_MinLength', - 'maxLength' => 'patForms_Rule_MaxLength', - 'minValue' => 'patForms_Rule_MinValue', - 'maxValue' => 'patForms_Rule_MaxValue', - 'match' => 'patForms_Rule_Match', - 'notMatch' => 'patForms_Rule_NotMatch', - 'required' => null, // will be done by the elements "required" attribute - 'validValues' => 'patForms_Rule_ValidValues', - ); - - /** - * @param array $conf an assoc array of parameters. these are: - * - string name => $name of the propel object class - * - string filename => $filename of the form definition xml file - */ - - static public function create($conf) { - - extract($conf); - - $autoValidate = isset($autoValidate) ? $autoValidate : 'save'; - - $definition = new patForms_Definition_Propel($name, $autoValidate); - - if (0 AND file_exists($filename)) { - // load definition from xml file - $definition->load($filename); - } else { - // populate definition from table map and save it to xml file - $definition = self::populateFromTableMap($definition, $conf); - $definition->save($filename); - } - - return $definition; - } - - private function populateFromTableMap($definition, $conf) { - - extract($conf); - - $mapBuilder = call_user_func(array($name . 'Peer', 'getMapBuilder')); - $tablename = constant($name . 'Peer::TABLE_NAME'); - $tableMap = $mapBuilder->getDatabaseMap()->getTable($tablename); - $cols = $tableMap->getColumns(); - - foreach ($cols as $col) { - - $phpname = $col->getPhpName(); - // this would need a patched version of patForms in order - // to retrieve request vars after having submitted the form - // TODO - ask patForms developers to enable this - // $elementName = $tablename . '[' . $phpname . ']'; - $elementName = $phpname; - - $elementType = self::$creoleTypeMap[$col->getCreoleType()]; - - // TODO somehow retrieve element type specific default values? - $elementAttributes = array( - 'name' => $elementName, - 'title' => $phpname, - 'label' => $phpname, - 'description' => $phpname, - 'edit' => 'yes', - 'display' => $col->isPrimaryKey() ? 'no' : 'yes', - // Is the element required? - // TODO Can we retrieve this info from the Column object? - 'required' => true, - ); - - switch ($col->getCreoleType()) { - case CreoleTypes::BOOLEAN: { - $elementAttributes['value'] = 1; - break; - } - case CreoleTypes::DATE: { - // TODO doesn't seem to work for some reason - // $elementAttributes['format'] = 'date'; - // $elementAttributes['dateformat'] = 'Ymd'; - break; - } - } - - if ($col->isForeignKey()) { - - $relColname = $col->getRelatedColumnName(); - $relTablename = $col->getRelatedTableName(); - $relColPhpname = - Propel::getDatabaseMap(constant($relTablename . 'Peer::DATABASE_NAME'))-> - getTable($relTablename)->getColumn($relColname)->getPhpname(); - - $elementAttributes['datasource'] = array ( - 'name' => 'patForms_Datasource_Propel', - 'peername' => $relTablename . 'Peer', - 'label' => array( - 'initial' => 'Please select one ...', - 'members' => array($relColPhpname), - 'mask' => '%s', - ), - 'value' => array( - 'members' => array($relColPhpname), - 'mask' => '%s', - ), - ); - $elementType = 'Enum'; - } - - $rules = array(); - if ($col->hasValidators()) { - foreach ($col->getValidators() as $validator) { - $name = $validator->getName(); - $type = self::$validatorTypeMap[$name]; - if (!is_null($type)) { - $rules[$name] = array ( - 'table' => $col->getTablename(), - 'col' => $col->getColumnName(), - 'name' => $name, - 'type' => self::$validatorTypeMap[$name], - 'value' => $validator->getValue(), - 'class' => $validator->getClass(), - 'message' => $validator->getMessage(), - ); - } - } - } - - $definition->addElement($phpname, $elementType, $elementAttributes, $rules); - } - - return $definition; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Element.php b/airtime_mvc/library/propel/contrib/pat/patForms/Element.php deleted file mode 100644 index de1a6c9ef..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Element.php +++ /dev/null @@ -1,1954 +0,0 @@ - - * @author gERD Schaufelberger - * @author Stephan Schmidt - */ - -/** - * error definition: the attribute that was set is not supported by this element (it is - * not listed in the attributeDefinition property set in the element class). - * @see patForms_Element::attributeDefinition - */ -define( "PATFORMS_ELEMENT_NOTICE_ATTRIBUTE_NOT_SUPPORTED", 1101 ); - -/** - * error definition: the setAttributes() method expects an array, - * but given value was not. - * @see patForms_Element::setAttributes() - */ -define( "PATFORMS_ELEMENT_ERROR_ARRAY_EXPECTED", 1102 ); - -/** - * error definition: the given attribute could not be set - */ -define( "PATFORMS_ELEMENT_ERROR_ADDING_ATTRIBUTE_FAILED", 1103 ); - -/** - * error definition: the element method to serialize the element in the given mode is - * not implemented. - * @see patForms_Element::serialize() - */ -define( "PATFORMS_ELEMENT_ERROR_METHOD_FOR_MODE_NOT_AVAILABLE", 1104 ); - -/** - * error definition: the element returned an error - */ -define( "PATFORMS_ELEMENT_ERROR_ERROR_RETURNED", 1105 ); - -/** - * error definition: the utility class {@link patForms_FormatChecker} could not be found, this is - * needed for the format validation of certain variable types. - * @see patForms_FormatChecker - * @see patForms_Element::validateFormat() - */ -define( "PATFORMS_ELEMENT_ERROR_FORMAT_CHECKER_NOT_FOUND", 1106 ); - -/** - * error definition: the modifier that was set for the element is not an array. - * @see patForms_Element::_applyModifiers() - */ -define( "PATFORMS_ELEMENT_ERROR_MODIFIER_NOT_AN_ARRAY", 1107 ); - -/** - * error definition: the method for the given modifier does not exist - * @see patForms_Element::_applyModifiers() - */ -define( "PATFORMS_ELEMENT_ERROR_METHOD_FOR_MODIFIER_NOT_FOUND", 1108 ); - -/** - * error definition: the modifier returned an error, modifications could not be made. - * @see patForms_Element::_applyModifiers() - */ -define( "PATFORMS_ELEMENT_ERROR_MODIFIER_RETURNED_ERROR", 1109 ); - -/** - * error definition: the given attribute is required for the specified output format. - * @see patForms_Element::getAttributesFor() - */ -define( "PATFORMS_ELEMENT_ERROR_ATTRIBUTE_REQUIRED", 1110 ); - -/** - * error definition: given modifier could not be applied to specified attribute - * @see patForms_Element::getAttributesFor() - */ -define( "PATFORMS_ELEMENT_ERROR_UNABLE_TO_APPLY_MODIFIER_TO_ATTRIBUTE", 1111 ); - -/** - * error definition: the given attribute is not available for output in the specified - * output format. - * @see patForms_Element::getAttributesFor() - */ -define( "PATFORMS_ELEMENT_ERROR_ATTRIBUTE_NOT_AVAILABLE_FOR_OUTPUT", 1112 ); - -/** - * error definition: format of the attribute could not be verified - * @see patForms_Element::getAttributesFor() - */ -define( "PATFORMS_ELEMENT_ERROR_CAN_NOT_VERIFY_FORMAT", 1113 ); - -/** - * error definition: the attribute collection of the element could not be validated. - * @see patForms_Element::toHtml() - */ -define( "PATFORMS_ELEMENT_ERROR_CAN_NOT_VALIDATE_ATTRIBUTE_COLLECTION", 1114 ); - -/** - * error definition: validator undefined - */ -define( "PATFORMS_ELEMENT_ERROR_VALIDATOR_ERROR_UNDEFINED", 1115 ); - -/** - * error definition: undefined locale for errors output - */ -define( "PATFORMS_ELEMENT_ERROR_VALIDATOR_ERROR_LOCALE_UNDEFINED", 1116 ); - -/** - * error definition: the html source for the element could not be generated. - */ -define( "PATFORMS_ELEMENT_ERROR_NO_HTML_CONTENT", 1221 ); - -/** - * error definition: not a valid renderer - */ -define( 'PATFORMS_ELEMENT_ERROR_INVALID_RENDERER', 1222 ); - -/** - * error definition: this element does not support the use of a renderer - */ -define( 'PATFORMS_ELEMENT_RENDERER_NOT_SUPPORTED', 1223 ); - -/** - * filter is located between patForms and browser - */ -define( 'PATFORMS_FILTER_TYPE_HTTP', 1 ); - -/** - * filter is located between patForms and the PHP script - */ -define( 'PATFORMS_FILTER_TYPE_PHP', 2 ); - -/** - * base patForms element class with all needed base functionality that each element - * should have. Extend this class to create your own elements. - * - * $Id: Element.php 1347 2009-12-03 21:06:36Z francois $ - * - * @abstract - * @package patForms - * @subpackage patForms_Element - * @access protected - * @version 0.1 - * @author Sebastian Mordziol - * @author gERD Schaufelberger - * @author Stephan Schmidt - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Element -{ - /** - * the type of the element, set this in your element class! - * @access protected - */ - var $elementType = false; - - /** - * javascript that will be displayed only once - * - * @access private - * @var array - */ - var $globalJavascript = array(); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceJavascript = array(); - - /** - * the value of the element - * @access protected - */ - var $value = false; - - /** - * filters that have been applied - * @access private - */ - var $filters = array(); - - /** - * observers that have been attached - * - * @access private - * @var array - */ - var $observers = array(); - - /** - * The elementName for the serialized version of the element - * - * This is needed for the toXML() method and also by the patForms - * error management. If it is not set, the element name will be - * created by extracting everything after the last underscore in - * the classname. - * - * @access protected - * @see toXML() - */ - var $elementName = null; - - /** - * the attribute collection of the element - * @access private - * @see setAttribute() - * @see setAttributes() - * @see getAttribute() - * @see getAttributes() - */ - var $attributes = array(); - - /** - * the configuration for the attributes supported by the element. Overwrite this - * in your element class. - * - * @abstract - */ - var $attributeDefinition = array(); - - /** - * Stores the attribute defaults for the element, that will be used - * if the given attributes have not been set by the user. - * - * @abstract - * @access private - * @see getAttributeDefaults() - */ - var $attributeDefaults = array(); - - /** - * stores the mode for the element. It defaults to 'default', and is only overwritten if - * set specifically. - * - * @access protected - * @see setMode() - */ - var $mode = "default"; - - /** - * stores the format for the element. It defaults to 'html', and is only overwritten if - * set specifically. - * - * @access protected - * @see setFormat() - */ - var $format = "html"; - - /** - * stores the locale to use when adding validation errors. The specified locale has - * to be set in the validationErrorCodes element class property, otherwise the default - * 'C' (as in the programming language C => english) will be used. - * - * @access private - * @var string $locale - * @see setLocale() - */ - var $locale = "C"; - - /** - * stores the flag telling the element whether it has been submitted - this is used by the - * getValue() method to determine where to get the element's value from. - * @access protected - * @see getValue() - */ - var $submitted = false; - - /** - * stores the flag whether the element is valid - * @access protected - */ - var $valid = true; - - /** - * stores any validation errors that can occurr during the element's validation process. - * - * @access private - * @var array $validationErrors - */ - var $validationErrors = array(); - - /** - * define error codes an messages for each form element - * - * @access protected - * @var array $validatorErrorCodes - */ - var $validatorErrorCodes = array(); - - /** - * defines the starting character for the modifier placeholders that can be inserted - * in the attributes listed as having modifier support. - * - * @access private - * @var string $modifierStart - */ - var $modifierStart = "["; - - /** - * defines the starting character for the modifier placeholders that can be inserted - * in the attributes listed as having modifier support. - * - * @access private - * @var string $modifierStart - */ - var $modifierEnd = "]"; - - /** - * XML entities - * - * @access protected - * @see toXML() - */ - var $xmlEntities = array( - "<" => "<", - ">" => ">", - "&" => "&", - "'" => "'", - '"' => """ - ); - /** - * shortcur to the session variables - * If "false", no session will be used, otherwise it stores the session variables for this element - * - * @access private - * @var mixed $sessionVar - */ - var $sessionVar = false; - - /** - * custom validation rules - * - * @access private - * @var array - */ - var $_rules = array(); - - /** - * next error offset for rules - * @access private - * @var integer - */ - var $nextErrorOffset = 1000; - - /** - * stores whether the element uses a renderer to serialize its content - * @access private - * @var bool - */ - var $usesRenderer = false; - - /** - * Stores the renderer object that can be set via the setRenderer method - * @access private - * @var object - */ - var $renderer = false; - - /** - * Stores all element options - * @access private - */ - var $options = array(); - - /** - * constructor - extend this in your class if you need to do specific operations - * on startup. In that case, however, don't forget to call this constructor anyway - * so that the thing happening here don't get lost. - * - * That's easy to do... just add the following line in your constructor: - * parent::patForms_Element(); - * - * @access public - * @param mixed $mode Optional: the output format, e.g. 'html' - */ - function __construct( $format = false ) - { - if ( $format !== false ) - { - $this->format = $format; - } - - $this->loadAttributeDefaults(); - } - - /** - * patForms_Element constructor for php4 - * - * @access private - * @param integer $id - * @return boolean $result true on success - * @see __construct - */ - function patForms_Element( $format = false ) - { - $this->__construct( $format ); - } - - /** - * Add any initialization routines for your element in your element class, - * for everythig your element needs to do after it has been instantiated and - * the attribute collection has been created. - * - * @abstract - * @access private - * @return mixed $success True on success, a patError object otherwise - */ - function _init() - { - // your code here - return true; - } - - /** - * sets the format of the element - this defines which method will be called in your - * element class, along with the {@link mode} property. - * - * @access public - * @param string $format The name of the format you have implemented in your element(s). Default is 'html' - * @see setFormat() - * @see format - * @see serialize() - */ - function setFormat( $format ) - { - $this->format = strtolower( $format ); - } - - /** - * sets the mode of the element that defines which methods will be called in your - * element class, along with the {@link format} property. - * - * @access public - * @param string $mode The mode to set the element to: default|readonly or any other mode you have implemented in your element class(es). Default is 'default'. - * @see setFormat() - * @see mode - * @see serialize() - */ - function setMode( $mode ) - { - $this->mode = strtolower( $mode ); - } - - /** - * sets the locale (language) to use for the validation error messages of the form. - * - * @access public - * @param string $lang - * @return bool $result True on success - * @see $locale - */ - function setLocale( $lang ) - { - $this->locale = $lang; - - // check, whether this is a custom locale - if (patForms::isCustomLocale($lang)) { - $errorMessages = patForms::getCustomLocale($lang, 'Element::' . $this->elementName); - if (is_array($errorMessages)) { - $this->validatorErrorCodes[$lang] = $errorMessages; - } - } - - return true; - } - - /** - * sets the value of the element, which will be used to fill the element with. If none is - * set and the element needs a value, it will load it using the {@link resolveValue()} method. - * - * This will override user input. - * - * @access public - * @param mixed $value The value to set - * @see $value - * @see resolveValue() - * @see getValue() - */ - function setValue( $value ) - { - $value = $this->_applyFilters( $value, 'in', PATFORMS_FILTER_TYPE_PHP ); - $this->value = $value; - } - - /** - * sets the default value of the element, which will be used to fill the element with. - * - * @access public - * @param mixed $value The value to set - * @see $value - * @see resolveValue() - * @see setValue() - * @see getValue() - */ - function setDefaultValue( $value ) - { - $this->setAttribute('default', $value); - } - - /** - * sets the current submitted state of the element. Set this to true if you want the element - * to pick up its submitted data. - * - * @access public - * @param bool $state True if it has been submitted, false otherwise (default). - * @see getSubmitted() - * @see $submitted - */ - function setSubmitted( $state ) - { - $this->submitted = $state; - } - - /** - * sets the internal ID of the element - this is only used by the {@link patForms} class to - * give each element a unique ID that will be added as ID attribute to each element if the - * id attribute has not been defined. - * - * @access public - * @param string $id The id to set for the element - * @see getId() - */ - function setId( $id ) - { - $this->attributes['id'] = $id; - } - - /** - * gets the internal ID of the element - * - * @access public - * @return string $id The id to set for the element - * @see setId() - */ - function getId() - { - return $this->getAttribute( 'id' ); - } - - /** - * checks whether a given attribute is supported by this element. - * - * @access public - * @param string $attributeName The name of the attribute to check - * @return bool $hasAttribute True if it supports the attribute, false otherwise. - */ - function hasAttribute( $attributeName ) - { - if ( isset( $this->attributeDefinition[$attributeName] ) ) - { - return true; - } - - return false; - } - - /** - * adds an attribute to the element's attribut3 collection. If the attribute - * already exists, it is overwritten. - * - * @access public - * @param string $attributeName The name of the attribute to add - * @param string $attributeValue The value of the attribute - * @return mixed $success True on success, a patError object otherwise - */ - function setAttribute( $attributeName, $attributeValue ) - { - if ( !isset( $this->attributeDefinition[$attributeName] ) ) - { - return patErrorManager::raiseNotice( - PATFORMS_ELEMENT_NOTICE_ATTRIBUTE_NOT_SUPPORTED, - 'Unknown attribute ['.$attributeName.']', - 'Ignored the attribute as the ['.$this->elementName.'] element does not support it.' - ); - } - - $this->attributes[$attributeName] = $attributeValue; - - return true; - } - - /** - * adds several attribute at once to the element's attributes collection. - * Any existing attributes will be overwritten. - * - * @access public - * @param array $attributes The attributes to add - * @return mixed $success True on success, false otherwise - */ - function setAttributes( $attributes ) - { - if ( !is_array( $attributes ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_ARRAY_EXPECTED, - "Not an array given (setAttributes)" - ); - } - - foreach ( $attributes as $attributeName => $attributeValue ) - { - $this->setAttribute( $attributeName, $attributeValue ); - } - - return true; - } - - /** - * sets a renderer object that will be used to render - * the element. Use the serialize() method to retrieve - * the rendered content of the element. - * - * Only enabled in elements that support renderers, like - * the radio element. - * - * @access public - * @param object &$renderer The renderer object - */ - function setRenderer( &$renderer ) - { - if ( !$this->usesRenderer ) - { - return patErrorManager::raiseWarning( - PATFORMS_ELEMENT_RENDERER_NOT_SUPPORTED, - 'The element \''.$this->elementName.'\' does not support the use of renderers - you do not have to set a renderer for this element.' - ); - } - - if ( !is_object( $renderer ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_INVALID_RENDERER, - 'You can only set a patForms_Renderer object with the setRenderer() method, "'.gettype( $renderer ).'" given.' - ); - } - - $this->renderer = &$renderer; - } - - /** - * retrieves the value of an attribute. - * - * @access public - * @param string $attribute The name of the attribute to retrieve - * @return mixed $attributeValue The value of the attribute, or false if it does not exist in the attributes collection. - * @see setAttribute() - */ - function getAttribute( $attribute ) - { - if ( !isset( $this->attributes[$attribute] ) ) - { - return false; - } - - return $this->attributes[$attribute]; - } - - /** - * retrieves all attributes, or only the specified attributes. - * - * @access public - * @param array $attributes Optional: The names of the attributes to retrieve. Only the attributes that exist will be returned. - * @return array $result The attributes - * @see getAttribute() - */ - function getAttributes( $attributes = array() ) - { - if ( empty( $attributes ) ) - { - return $this->attributes; - } - - $result = array(); - foreach ( $attributes as $attribute ) - { - if ( $attributeValue = $this->getAttribute( $attribute ) ) - { - $result[$attribute] = $attributeValue; - } - } - - return $result; - } - - /** - * Loads the default attribute values into the attributes collection. Done directly - * on startup (in the consructor), so make sure you call this if your element needs - * this feature and you have implemented a custom constructor in your element. - * - * @access public - * @return bool $success Always returns true. - * @see $attributeDefaults - */ - function loadAttributeDefaults() - { - foreach ( $this->attributeDefinition as $attributeName => $attributeDef ) - { - if ( isset( $attributeDef['default'] ) ) - { - $this->attributes[$attributeName] = $attributeDef['default']; - } - } - - return true; - } - - /** - * retrieves the current value of the element. If none is set, will try to retrieve the - * value from submitted form data. - * - * @access public - * @param boolean Determines whether the method is used from an external script - * @return mixed The value, or an empty string if none found. - * @see setValue() - * @see value - * @see resolveValue() - */ - function getValue( $external = true ) - { - if ( $this->value === false ) - { - $this->resolveValue(); - - // could not be resolved - if ( $this->value === false ) - { - $value = ''; - } - else - { - $value = $this->value; - } - } - else - { - $value = $this->value; - } - - if ( $external === false ) - { - return $value; - } - - $value = $this->_applyFilters( $value, 'out', PATFORMS_FILTER_TYPE_PHP ); - - return $value; - } - - /** - * resolves the scope the value of the element may be stored in, and returns it. - * - * @access protected - * @see getValue() - * @see value - * @todo parse element name, if it uses the array syntax - */ - function resolveValue() - { - $varName = $this->attributes['name']; - - if ( $this->submitted && isset( $_POST[$varName] ) ) - { - $this->value = $_POST[$varName]; - if ( ini_get( 'magic_quotes_gpc' ) ) - $this->value = $this->rStripSlashes( $this->value ); - $this->value = $this->_applyFilters( $this->value, 'in', PATFORMS_FILTER_TYPE_HTTP ); - return true; - } - - if ( $this->submitted && isset( $_GET[$varName] ) ) - { - $this->value = $_GET[$varName]; - if ( ini_get( 'magic_quotes_gpc' ) ) - $this->value = $this->rStripSlashes( $this->value ); - $this->value = $this->_applyFilters( $this->value, 'in', PATFORMS_FILTER_TYPE_HTTP ); - return true; - } - - if ( isset( $this->attributes['default'] ) ) - { - $this->value = $this->attributes['default']; - $this->value = $this->_applyFilters( $this->value, 'in', PATFORMS_FILTER_TYPE_PHP ); - - return true; - } - - return true; - } - - /** - * recursively strip slashes - * - * This method is used to 'fix' magic_quotes_gpc. - * - * @access public - * @param mixed user input (get or post) - * @return mixed data with slashes stripped - */ - function rStripSlashes( $value ) - { - if ( is_scalar( $value ) ) - return stripslashes( $value ); - if ( is_array( $value ) ) - { - foreach ( $value as $key => $val ) - { - $value[$key] = $this->rStripSlashes( $val ); - } - } - return $value; - } - - /** - * apply filters to a value - * - * @access private - * @param mixed value - * @param string direction of the filter ('in' or 'out') - * @param integer type of filters to apply - * @return mixed filtered value - */ - function _applyFilters( $value, $dir = 'in', $type = PATFORMS_FILTER_TYPE_PHP ) - { - if ( empty( $this->filters ) ) - return $value; - - /** - * apply filters! - */ - $cnt = count( $this->filters ); - for ( $i = 0; $i < $cnt; $i++ ) - { - /** - * check, whether filter is located between php script and form - */ - if ( $this->filters[$i]->getType() != $type ) - { - continue; - } - - $value = $this->filters[$i]->$dir( $value ); - } - return $value; - } - - /** - * retrieves the current mode of the element - * - * @access public - * @return string $mode The current element mode - * @see setMode() - * @see mode - */ - function getMode() - { - return $this->mode; - } - - /** - * retrieves the current format of the element - * - * @access public - * @return string $format The current element format - * @see setFormat() - * @see format - */ - function getFormat() - { - return $this->format; - } - - /** - * retrieves the element's current submitted state. - * - * @access public - * @return bool $state True if it has been submitted, false otherwise. - * @see setSubmitted() - * @see submitted - */ - function getSubmitted() - { - return $this->submitted; - } - - /** - * retrieves the name of the element - * - * @access public - * @return string $name name of the element - * @uses getAttribute() - */ - function getName() - { - return $this->getAttribute( 'name' ); - } - - /** - * add a custom validation rule - * - * @access public - * @param object patForms_Rule validation rule - * @param integer time, when rule has to be applied, can be before or after validation. - * If set to null, it will use the default value as specified in the rule - * @return boolean currently always true - */ - function addRule( &$rule, $time = null ) - { - if ( is_null( $time ) ) - { - $time = $rule->getTime(); - } - - $rule->prepareRule( $this ); - - $this->_rules[] = array( - 'rule' => &$rule, - 'time' => $time, - ); - return true; - } - - /** - * adds an observer to the element - * - * @access public - * @param object patForms_Observer observer - * @return boolean currently always true - */ - function attachObserver( &$observer ) - { - $this->observers[] = &$observer; - return true; - } - - /** - * dispatches the serialization of the element in the format that was set to the - * corresponding method in the element class. These methods must be named in the - * folowing scheme: - * - * serialize[format][mode](), e.g. serializeHtmlDefault() - * - * @access public - * @return string $element The created element according to the specified mode. - * @see setFormat() - * @see setMode() - * @todo serialize*() methods should return a patError object instead of false!!!! - * Has to be changed asap! - */ - function serialize() - { - $methodName = "serialize".ucfirst( $this->getFormat() ).ucfirst( $this->getMode() ); - - if ( !method_exists( $this, $methodName ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_METHOD_FOR_MODE_NOT_AVAILABLE, - "Element method for form mode '".$this->getMode()."' (".$methodName.") is not available." - ); - } - - /** - * get the value for internal use - * The PHP-filters will not be applied - */ - $value = $this->getValue( false ); - - $element = $this->$methodName( $value ); - if ( patErrorManager::isError( $element ) ) - { - return $element; - } - - return $element; - } - - /** - * Template method that applies rules and calls the elements - * validation method - * - * @final - * @access public - * @return bool $success True on success, false otherwise - */ - function validate() - { - // apply locale, if the current locale is a custom locale - if (patForms::isCustomLocale($this->locale)) { - $cnt = count( $this->_rules ); - for ( $i = 0; $i < $cnt; $i++ ) { - $this->_rules[$i]['rule']->setLocale($this->locale); - } - } - - /** - * validate custom rules - */ - if ( !$this->_applyRules( PATFORMS_RULE_BEFORE_VALIDATION ) ) - { - $this->_announce( 'status', 'error' ); - return false; - } - - /** - * the the unfiltered value - */ - $value = $this->getValue( false ); - - $valid = $this->validateElement( $value ); - if ( $valid === false ) - { - $this->_announce( 'status', 'error' ); - return false; - } - - /** - * validate custom rules - */ - if ( !$this->_applyRules( PATFORMS_RULE_AFTER_VALIDATION ) ) - { - $this->_announce( 'status', 'error' ); - return false; - } - - $this->_announce( 'status', 'validated' ); - return true; - } - - /** - * validates the given data with the element's validation routines - * and returns the data with any needed modifications. - * - * @abstract - * @access private - * @return bool $success True on success, false otherwise - */ - function validateElement() - { - // your code here - return true; - } - - /** - * apply rules - * - * @access private - * @param integer time of validation - * @return boolean rules are valid or not - * @todo add documentation - */ - function _applyRules( $time ) - { - $valid = true; - - $cnt = count( $this->_rules ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( ( $this->_rules[$i]['time'] & $time ) != $time ) - continue; - - $result = $this->_rules[$i]['rule']->applyRule( $this, $time ); - if ( $result === false ) - { - $valid = false; - } - } - return $valid; - } - - /** - * finalize the element. - * - * Used as a template method. - * - * @final - * @access protected - * @return bool $success True on success, false otherwise - * @uses finalizeElement() to call the user code - */ - function finalize() - { - $value = $this->getValue( false ); - return $this->finalizeElement( $value ); - } - - /** - * finalize the element - * - * Offers the possibility to process any needed operations after the element - * has been validated. Implement any tasks that you need to do then here - a - * good example is the File element, where this method enables the moving of - * the uploaded file to the correct location. - * - * @abstract - * @access private - * @param mixed value of the element - * @return bool $success True on success, false otherwise - */ - function finalizeElement( $value ) - { - return true; - } - - /** - * Enables an element option. - * - * See the {@link patForms::$options} property for an exhaustive list of available options. - * - * @access public - * @param string $option The option to enable - * @param array $params Optional parameters for the option - * @see disableOption() - * @see $options - */ - function enableOption( $option, $params = array() ) - { - if ( !isset( $this->options[$option] ) ) - $this->options[$option] = array(); - - $this->options[$option]['enabled'] = true; - $this->options[$option]['params'] = $params; - } - - /** - * Disables an element option - * - * See the {@link patForms::$options} property for an exhaustive list of available options. - * - * @access public - * @param string $option The option to disable - * @see enableOption() - * @see $options - */ - function disableOption( $option ) - { - if ( !isset( $this->options[$option] ) ) - $this->options[$option] = array(); - - $this->options[$option]['enabled'] = false; - } - - /** - * [helper method] validates the given value according to the specified method. It first - * checks if there is a method to check the format in the {@link patForms_FormatChecker} - * class, then checks in the element class itself. - * - * @access public - * @param mixed $value The value to validate the format of - * @param string $format The format to validate the value with - * @return bool $isValid True if valid, false if invalid or no method exists to validate the format. - * @see patForms_FormatChecker - */ - function validateFormat( $value, $format ) - { - if ( !class_exists( "patForms_FormatChecker" ) ) - { - $checkerFile = dirname( __FILE__ )."/FormatChecker.php"; - if ( !file_exists( $checkerFile ) ) - { - $this->valid = false; - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_FORMAT_CHECKER_NOT_FOUND, - "Type checker could not be found, aborting validation." - ); - } - - include_once( $checkerFile ); - } - - $format = strtolower( $format ); - - $methodName = "is_".$format; - $option = false; - - if ( method_exists( $this, $methodName ) ) - { - return $this->$methodName( $value ); - } - - if ( in_array( $methodName, get_class_methods( "patForms_FormatChecker" ) ) ) - { - return call_user_func( array( 'patForms_FormatChecker', $methodName ), $value ); - } - - return false; - } - - /** - * get next error offset - * - * @access public - * @return integer - */ - function getErrorOffset( $requiredCodes = 100 ) - { - $offset = $this->nextErrorOffset; - $this->nextErrorOffset = $this->nextErrorOffset + $requiredCodes; - return $offset; - } - - /** - * add error codes and messages for validator method - * - * @access public - * @param array defintions - * @param integer offset for the error codes - */ - function addValidatorErrorCodes( $defs, $offset = 1000 ) - { - foreach ( $defs as $lang => $codes ) - { - if ( !isset( $this->validatorErrorCodes[$lang] ) ) { - $this->validatorErrorCodes[$lang] = array(); - } - - foreach ( $codes as $code => $message ) { - $this->validatorErrorCodes[$lang][($offset+$code)] = $message; - } - } - } - - /** - * getValidationErrors - * - * @access public - * @return array errors that occured during the validation - */ - function getValidationErrors() - { - return $this->validationErrors; - } - - /** - * addValidationError - * - * - * @access public - * @param integer $code - * @param array $vars fill named placeholder with values - * @return boolean $result true on success - */ - function addValidationError( $code, $vars = array() ) - { - $error = false; - $lang = $this->locale; - $element = $this->getElementName(); - - // find error message for selected language - while ( true ) - { - // error message matches language code - if ( isset( $this->validatorErrorCodes[$lang][$code] ) ) - { - $error = array( "element" => $element, "code" => $code, "message" => $this->validatorErrorCodes[$lang][$code] ); - break; - } - // no message found and no fallback-langauage available - else if ( $lang == "C" ) - { - break; - } - - $lang_old = $lang; - - // look for other languages - if ( strlen( $lang ) > 5 ) - { - list( $lang, $trash ) = explode( ".", $lang ); - } - else if ( strlen( $lang ) > 2 ) - { - list( $lang, $trash ) = explode( "_", $lang ); - } - else - { - $lang = "C"; - } - - // inform developer about missing language - patErrorManager::raiseNotice( - PATFORMS_ELEMENT_ERROR_VALIDATOR_ERROR_LOCALE_UNDEFINED, - "Required Validation Error-Code for language: $lang_old not available. Now trying language: $lang", - "Add language definition in used element or choose other language" - ); - - } - - // get default Error! - if ( !$error ) - { - patErrorManager::raiseWarning( - PATFORMS_ELEMENT_ERROR_VALIDATOR_ERROR_UNDEFINED, - "No Error Message for this validation Error was defined", - "Review the error-definition for validation-errors in your element '$element'." - ); - $error = array( "element" => $element, "code" => 0, "message" => "Unknown validation Error" ); - } - - // insert values to placeholders - if ( !empty( $vars ) ) - { - foreach ( $vars as $key => $value ) - { - $error["message"] = str_replace( "[". strtoupper( $key ) ."]", $value, $error["message"] ); - } - } - - array_push( $this->validationErrors, $error ); - $this->valid = false; - return true; - } - - /** - * applies the specified modifiers to an attribute value, as set in the attribute definition. - * - * @access private - * @param mixed $attributeValue The value of the attribute to modify - * @param array $modifiers Array containing the list of modifiers and their options to apply. - * @return mixed $attributeValue The modified attribute value. - * @see createAttributes() - */ - function _applyModifiers( $attributeValue, $modifiers ) - { - if ( !is_array( $modifiers ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_MODIFIER_NOT_AN_ARRAY, - "Modifiers are not an array" - ); - } - - foreach ( $modifiers as $modifier => $modifierOptions ) - { - // compute method name for this definition and check if it exists - $modifierMethod = "_modifier".ucfirst( $modifier ); - - if ( !method_exists( $this, $modifierMethod ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_METHOD_FOR_MODIFIER_NOT_FOUND, - "Method not found for modifier '" . $modifier . "' (".$modifierMethod.") in class '" . get_class( $this ) . "'" - ); - } - - $modifiedValue = $this->$modifierMethod( $attributeValue ); - - if ( $modifiedValue === false ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_MODIFIER_RETURNED_ERROR, - "Modifier '".$modifier."' returned an error." - ); - } - - $attributeValue = $modifiedValue; - } - - return $attributeValue; - } - - /** - * insertSpecials attribute value modifier - * - * you can use special placeholders to insert dynamic values into the attribute values. - * This method inserts the correct information for each placeholder in the given string. - * - * @access private - * @param string $string The string to insert the specials in - * @return string $string The string with all needed replacements - * @see _applyModifiers() - * @todo Maybe make this configurable - * @todo Add any other relevant information - */ - function _modifierInsertSpecials( $modifyValue, $options = array() ) - { - if ( is_array( $modifyValue ) || is_object( $modifyValue ) || is_array( $this->value ) ) - return $modifyValue; - - // go through each attribute in the attribute definition and replace the strings - // with the corresponding attribute values. - foreach ( $this->attributeDefinition as $attributeName => $attributeDef ) - { - // if attribute was not set, strip the variable by setting it to empty. - $attributeValue = ""; - - // retrieve real attribute value if it was set - if ( isset( $this->attributes[$attributeName] ) && is_string( $this->attributes[$attributeName] ) ) - { - $attributeValue = $this->attributes[$attributeName]; - } - - $search = $this->modifierStart."ELEMENT_".strtoupper( $attributeName ).$this->modifierEnd; - - // make the replacement - $modifyValue = str_replace( $search, $attributeValue, $modifyValue ); - } - - // the element's value is special... - $modifyValue = str_replace( $this->modifierStart."ELEMENT_VALUE".$this->modifierEnd, $this->value, $modifyValue ); - - return $modifyValue; - } - - /** - * checks the format of an attribute value according to the given format. - * - * @access private - * @param mixed $attributeValue The attribute value to check - * @param string $format The format to check the attribute value against - * @return bool $result True if format check succeeded, false otherwise. - * @see createAttributes() - * @todo Implement this method sometime - */ - function _checkAttributeFormat( $attributeValue, $format ) - { - return true; - } - - /** - * validates the current attribute collection according to the attributes definition - * and the given output format, and returns the list of valid attributes. - * - * @access private - * @param string $format The output format to retrieve the attributes for. - * @return mixed $attributes The list of attributes, or false if failed. - */ - function getAttributesFor( $format ) - { - $attributes = array(); - - foreach ( $this->attributeDefinition as $attributeName => $attributeDef ) - { - if ( !isset( $this->attributes[$attributeName] ) ) - { - if ( $attributeDef["required"] ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_ATTRIBUTE_REQUIRED, - 'The element "'.$this->getElementName().'" needs the attribute "'.$attributeName.'" to be set.', - 'See the attribute definition of the element class "'.get_class( $this ).'"' - ); - } - - continue; - } - - $attributeValue = $this->attributes[$attributeName]; - - // special case disabled attribute: skip this if it is not set to yes - // to avoid generating a disabled field anyway (empty HTML attribute) - if ( $attributeName == 'disabled' && $attributeValue != 'yes' ) - { - continue; - } - - if ( isset( $attributeDef["modifiers"] ) && !empty( $attributeDef["modifiers"] ) ) - { - $modifiedValue = $this->_applyModifiers( $attributeValue, $attributeDef["modifiers"] ); - if ( $modifiedValue === false ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_UNABLE_TO_APPLY_MODIFIER_TO_ATTRIBUTE, - "Could not apply modifier to attribute '".$attributeName."' (value:'".$attributeValue."')" - ); - } - - $attributeValue = $modifiedValue; - - // store this for later use too - $this->attributes[$attributeName] = $attributeValue; - } - - if ( !in_array( $format, $attributeDef["outputFormats"] ) ) - { - continue; - } - - if ( isset( $attributeDef["format"] ) ) - { - if ( !$this->_checkAttributeFormat( $attributeValue, $attributeDef["format"] ) ) - { - return patErrorManager::raiseError( - PATFORMS_ELEMENT_ERROR_CAN_NOT_VERIFY_FORMAT, - "Format '".$attributeDef["format"]."' could not be verified for attribute '".$attributeName."' => '".$attributeValue."'" - ); - } - } - - $attributes[$attributeName] = $attributeValue; - } - - return $attributes; - } - - /** - * [helper method] wrapper for the {@link createTag()} method which automates the tag - * creation by creating the tag from the current attribute collection and element type. - * - * @access protected - * @return mixed $result The created tag, or false if failed. - * @see elementType - * @see attributes - * @see createTag() - */ - function toHtml() - { - $attributes = $this->getAttributesFor( $this->getFormat() ); - if ( patErrorManager::isError( $attributes ) ) - { - return $attributes; - } - - return $this->createTag( $this->elementType[$this->getFormat()], "full", $attributes ); - } - - /** - * [helper method] create a hidden field with the given value. Retrieves all other needed - * attributes from the attributes collection. - * @access public - */ - function createHiddenTag( $value ) - { - $attribs = array( 'type' => 'hidden', - 'name' => $this->attributes['name'], - 'value' => $value, - 'id' => $this->attributes['id'], - ); - - return $this->createTag( "input", "full", $attribs ); - } - - /** - * [helper method] creates a hidden field with the given value. Used for the - * display=no attribute, and is the same as the createHiddenTag() method, only - * that the attributes collection is initialized to ensure that any variables - * in the element's attributes get replaced. - * - * @access private - * @param mixed $value The value of the element - * @return string $element The serialized hidden tag - * @see createHiddenTag() - */ - function createDisplaylessTag( $value ) - { - // call this to initialize all attributes. This is needed - // here to make sure that if there are - $this->getAttributesFor( $this->getFormat() ); - - return $this->createHiddenTag( $value ); - } - - /** - * [helper method] create an element HTML source from its attribute collection and - * returns it. - * - * @static - * @access protected - * @param string $tagname The name of the element / tag - * @param string $type Optional: the type of element to generate. Valid parameters are full|opening|closing|empty. Defaults to "full". - * @param mixed $value The value of the element - * @return string $element The HTML source of the element - */ - function createTag( $tagname, $type = "full", $attributes = array(), $value = false ) - { - switch( $type ) - { - case "closing": - return ""; - break; - - case "empty": - case "opening": - $tag = "<".$tagname; - - // create attribute collection - foreach ( $attributes as $attributeName => $attributeValue ) - { - $tag = $tag . " ".$attributeName."=\"".htmlentities( (string)$attributeValue )."\""; - } - - // empty tag? - if ( $type == "empty" ) - { - $tag = $tag . " />"; - return $tag; - } - - $tag = $tag . ">"; - return $tag; - - break; - - case "full": - if ( $value === false ) - { - return patForms_Element::createTag( $tagname, "empty", $attributes ); - } - - return patForms_Element::createTag( $tagname, "opening", $attributes ).htmlentities( $value ).patForms_Element::createTag( $tagname, "closing" ); - break; - } - } - - /** - * create XML representation of the element - * - * This can be used when you need to store the structure - * of your form in flat files or create form templates that can - * be read by patForms_Parser at a later point. - * - * @access public - * @param string namespace - * @uses getElementName() - * @see patForms_Parser - */ - function toXML( $namespace = null ) - { - $tagName = $this->getElementName(); - - // prepend Namespace - if ( $namespace != null ) - { - $tagName = $namespace.':'.$tagName; - } - - // get all attributes - $attributes = $this->getAttributes(); - - // create valid XML attributes - foreach ( $attributes as $key => $value ) - { - $attributes[$key] = strtr( $value, $this->xmlEntities ); - } - - $value = strtr( $this->getValue(), $this->xmlEntities ); - - if ( $value != false ) - { - return $this->createTag( $tagName, "full", $attributes, $value ); - } - return $this->createTag( $tagName, "empty", $attributes ); - } - - /** - * apply a filter - * - * This is still in alpha state! - * - * @access public - * @param object patForms_Filter - * @todo add error management and docs - * @todo allow filter to be an array containg two callbacks - * array( 'in' => 'myInFunc', 'out' => 'myOutFunc' ) ) - */ - function applyFilter( &$filter ) - { - $this->filters[] = &$filter; - return true; - } - - /** - * Get the name of the element, as stored in the elementName property. - * - * This is used when serializing an element to XML to - * create a now form template. - * - * This method checks for the $elementName property and if it - * is set to null, it will extract the element name from the class name - * - * @access public - * @return string tag name - */ - function getElementName() - { - if ( $this->elementName != null ) - { - return $this->elementName; - } - - $class = get_class( $this ); - $name = substr( strrchr( $class, "_" ), 1 ); - return ucfirst( $name ); - } - - /** - * checks wheter sessions are used or switch session usage on or of - * - * If switch argument is missing, this function just reports if sessions - * will be used or not - * - * @access protected - * @param string $switch switch sessions on ("yes") or off ("yes") - * @return boolean $result true if sessions will be used, false otherwise - * @see setSessionValue() - * @see getSessionValue() - * @see unsetSessionValue() - * @todo destroy session variables if sessions won't be usead any further - */ - function useSession( $switch = null ) - { - // switch sessions on or off - if ( $switch == "yes" ) - { - $this->attributes["usesession"] = "yes"; - } - else if ( $switch == "no" ) - { - $this->attributes["usesession"] = "no"; - return false; - } - - if ( isset( $this->attributes["usesession"] ) && $this->attributes["usesession"] == "yes" ) - { - if ( !$this->sessionVar ) - { - if ( !defined( "SID" ) ) - { - session_start(); - } - - $name = $this->attributes["name"]; - if ( !isset( $_SESSION["_patforms_element"][$name] ) ) - { - $_SESSION["_patforms_element"][$name] = array(); - } - - $this->sessionVar =& $_SESSION["_patforms_element"][$name]; - } - - return true; - } - return false; - } - - /** - * save a variable to the session - * - * @access protected - * @param string $name name to identify the variable - * @param mixed $value - * @return boolean $result true on success - * @see getSessionValue() - * @see unsetSessionValue() - */ - function setSessionValue( $name, $value ) - { - if ( !$this->useSession() ) - { - return false; - } - - $this->sessionVar[$name] = $value; - return true; - } - - /** - * get a variable from session - * - * @access protected - * @param string $name name to identify the variable - * @return mixed $result false if no sessions are used, null if variable is not set or the value of the variable - * @see getSessionValue() - * @see unsetSessionValue() - */ - function getSessionValue( $name ) - { - if ( !$this->useSession() ) - { - return false; - } - - if ( isset( $this->sessionVar[$name] ) ) - { - return $this->sessionVar[$name]; - } - return null; - } - - /** - * remove a variable from session - * - * @access protected - * @param string $name name to identify the variable - * @return mixed $result false if no sessions are used, null if variable is not set or the value of the variable - * @see getSessionValue() - * @see setSessionValue) - */ - function unsetSessionValue( $name ) - { - if ( !$this->useSession() ) - { - return false; - } - - $value = null; - if ( isset( $this->sessionVar[$name] ) ) - { - $value = $this->sessionVar[$name]; - unset( $this->sessionVar[$name] ); - } - return $value; - } - - /** - * get the global javascript of the element - * - * @access public - * @return string - */ - /* - function getGlobalJavascript() - { - if ( !isset( $this->globalJavascript[$this->format] ) ) - { - $script = ''; - } - else - { - $script = $this->globalJavascript[$this->format]; - } - - $cnt = count( $this->_rules ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $tmp = $this->_rules[$i]['rule']->getGlobalJavascript(); - if ( $tmp === false ) - continue; - $script .= $tmp; - } - - return $script; - } - */ - - /** - * get the instance javascript of the element - * - * @access public - * @return string javascript for this instance - */ - /* - function getInstanceJavascript() - { - if ( !isset( $this->instanceJavascript[$this->format] ) ) - { - $script = ''; - } - else - { - $script = $this->instanceJavascript[$this->format]; - - $script = str_replace( '[ELEMENT::NAME]', $this->getName(), $script ); - $script = str_replace( '[ELEMENT::ID]', $this->getId(), $script ); - } - - $cnt = count( $this->_rules ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $tmp = $this->_rules[$i]['rule']->getInstanceJavascript(); - if ( $tmp === false ) - continue; - $script .= $tmp; - } - - return $script; - } - */ - - function registerJavascripts(&$form) { - - if ($script = $this->getGlobalJavascript()) { - $form->registerGlobalJavascript($this->elementName, $script); - } - - if ($script = $this->getInstanceJavascript()) { - $form->registerInstanceJavascript($script); - } - - foreach ($this->_rules as $rule) { - $rule['rule']->registerJavascripts($form); - } - } - - function getGlobalJavascript() { - - if (isset($this->globalJavascript[$this->format])) { - return $this->globalJavascript[$this->format]; - } - } - - function getInstanceJavascript() { - - if (isset($this->instanceJavascript[$this->format])) { - $script = $this->instanceJavascript[$this->format]; - $script = str_replace('[ELEMENT::NAME]', $this->getName(), $script); - $script = str_replace('[ELEMENT::ID]', $this->getId(), $script); - return $script; - } - } - - /** - * retrieves the element's current submitted state. - * - * @access public - * @return bool $state True if it has been submitted, false otherwise. - * @see submitted - */ - function isSubmitted() - { - if ( $this->submitted === true ) { - return true; - } - return false; - } - - /** - * returns the locale that is currently set for the form. - * - * @access public - * @return string $locale The locale. - * @see setLocale() - * @see $locale - */ - function getLocale() - { - return $this->locale; - } - - /** - * anounce a change in the element to all observers - * - * @access private - * @param string property that changed - * @param mixed new value of the property - */ - function _announce( $property, $value ) - { - $cnt = count( $this->observers ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $this->observers[$i]->notify( $this, $property, $value ); - } - return true; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule.php deleted file mode 100644 index 911c0965e..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule.php +++ /dev/null @@ -1,340 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - * @todo implement javascript helper methods (set a javascript property plus an - * array of keys that will be replaced by the properties of the rule) - */ -class patForms_Rule -{ - /** - * time when the rule should be applied - * - * Possible values are: - * -PATFORMS_RULE_BEFORE_VALIDATION - * -PATFORMS_RULE_AFTER_VALIDATION - * -PATFORMS_RULE_BOTH - * - * @access private - * @var integer - */ - var $_time = PATFORMS_RULE_AFTER_VALIDATION; - - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - var $globalScript = array(); - - /** - * script that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array(); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array(); - - /** - * store the container of the rule - * - * @access private - * @var object - */ - var $container; - - /** - * define error codes an messages for each form element - * - * @abstract - * @access private - * @var array - */ - var $validatorErrorCodes = array(); - - /** - * error code offset for the rule - * - * @abstract - * @access private - */ - var $errorOffset; - - /** - * format of the rule - * - * @abstract - * @access private - */ - var $format = 'html'; - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = ''; - - /** - * Get the time when the rule should be applied. - * - * This has to be defined in the _time property of the rule. - * - * @access public - * @return integer - */ - function getTime() - { - return $this->_time; - } - - /** - * create a new rule object - * - * @access public - * @param string id - */ - function patForms_Rule( $id = null ) - { - if ( $id === null ) - { - $id = uniqid( '' ); - } - - $this->_id = $id; - } - - /** - * set the id for the rule - * - * @access public - * @param string id - */ - function setId( $id ) - { - $this->_id = $id; - } - - /** - * set the locale, this is needed to update the rule - * translations, that have been passed to the container - * element - * - * @access public - * @param string new locale - * @return boolean - */ - function setLocale( $locale ) - { - // rules do not store locale information - if (!patForms::isCustomLocale($locale)) { - return true; - } - - $errorMessages = patForms::getCustomLocale($locale, 'Rule::' . $this->getRuleName()); - - if (is_array($errorMessages)) { - $this->validatorErrorCodes[$locale] = $errorMessages; - } - - $this->container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset ); - - return true; - } - - /** - * prepare the rule - * - * This method is used to initialize the rule. - * By default it adds it validatorErrorCodes - * to the container and stores a reference to the - * container. - * - * You may extend it in your custom rules, but should always be calling - * this method using: - * - * - * patForms_Rule::prepareRule( $container ); - * - * - * @access public - * @param object Either a patForms or patForms_Element object - */ - function prepareRule( &$container ) - { - $this->format = $container->getFormat(); - - $this->container = &$container; - $this->errorOffset = $container->getErrorOffset(); - - $container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset ); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @abstract - * @access public - * @param object Either a patForms or patForms_Element object - * @return boolean true, if rule has been applied succesfully, false otherwise - */ - function applyRule( &$container, $type = PATFORMS_RULE_BEFORE_VALIDATION ) - { - // your code - } - - /** - * addValidationError - * - * @access private - * @param integer $code - * @param array $vars fill named placeholder with values - * @return boolean $result true on success - */ - function addValidationError( $code, $vars = array() ) - { - $code= $this->errorOffset + $code; - return $this->container->addValidationError( $code, $vars ); - } - - /** - * get the name of the rule - * - * By default just return the classname, this is sufficient. - * - * @access public - * @return string - */ - function getRuleName() - { - if (!empty($this->ruleName)) { - return $this->ruleName; - } - return get_class( $this ); - } - - /** - * get the global javascript of the rule - * - * @access public - * @return string - * @todo Rules need to know the output format - */ - /* - function getGlobalJavascript() - { - if ( isset( $this->globalScript['html'] ) ) - { - return $this->globalScript['html']; - } - return ''; - } - */ - - /** - * get the instance javascript of the rule - * - * @access public - * @return string - */ - /* - function getInstanceJavascript() - { - if ( !isset( $this->instanceScript[$this->format] ) ) - { - return false; - } - // get the script for the current format - $script = $this->instanceScript[$this->format]; - - // always replace the id - $script = str_replace( '[RULE::ID]', $this->_id, $script ); - if ( method_exists( $this->container, 'getId' ) ) - { - $script = str_replace( '[CONTAINER::ID]', $this->container->getId(), $script ); - } - if ( method_exists( $this->container, 'getName' ) ) - { - $script = str_replace( '[CONTAINER::NAME]', $this->container->getName(), $script ); - } - - foreach ( $this->scriptPlaceholders as $placeholder => $property ) - { - if ( isset( $this->$property ) ) - $script = str_replace( '['.$placeholder.']', $this->$property, $script ); - else - $script = str_replace( '['.$placeholder.']', '', $script ); - } - return $script; - } - */ - - function registerJavascripts(&$form) { - - if ($script = $this->getGlobalJavascript()) { - $form->registerGlobalJavascript($this->getRuleName(), $script); - } - - if ($script = $this->getInstanceJavascript()) { - $form->registerInstanceJavascript($script); - } - } - - function getGlobalJavascript() { - - if (isset($this->globalScript[$this->format])) { - return $this->globalScript[$this->format]; - } - } - - function getInstanceJavascript(){ - - if (isset($this->instanceScript[$this->format])) { - $script = $this->instanceScript[$this->format]; - $script = str_replace('[RULE::ID]', $this->_id, $script); - if (method_exists($this->container, 'getId')) { - $script = str_replace('[CONTAINER::ID]', $this->container->getId(), $script); - } - if (method_exists($this->container, 'getName')) { - $script = str_replace('[CONTAINER::NAME]', $this->container->getName(), $script); - } - foreach ($this->scriptPlaceholders as $placeholder => $property) { - if (isset($this->$property)) { - $script = str_replace('['.$placeholder.']', $this->$property, $script); - } else { - $script = str_replace('['.$placeholder.']', '', $script); - } - } - return $script; - } - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/Match.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/Match.php deleted file mode 100644 index 3d47185f2..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/Match.php +++ /dev/null @@ -1,163 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_Match extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - - var $globalScript = array( - 'html' => "/* patForms::Rule::Match */ - -function pFRC_Match(field) { - this.field = eval('pfe_' + field); -} - -pFRC_Match.prototype.validate = function() { - value = this.field.getValue(); - if (!value.match(this.pattern)) { - alert('This is an invalid value.'); - } -} - -pFRC_Match.prototype.setValue = function(pattern) { - this.pattern = pattern; -} - -/* END: patForms::Rule::Match */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_Match('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'Match'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "This is an invalid value.", - ), - "de" => array( - 1 => "Dies ist ein ungültiger Wert.", - ), - "fr" => array( - 1 => "This is an invalid value.", - ) - ); - - /** - * the regEx pattern - * @access private - * @var string - */ - var $_pattern; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - private $value = 10; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->_pattern = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (preg_match($this->_pattern, $element->getValue()) != 0){ - return true; - } - - $this->addValidationError(1); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxLength.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxLength.php deleted file mode 100644 index d28c2f758..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxLength.php +++ /dev/null @@ -1,161 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_MaxLength extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - var $globalScript = array( - 'html' => "/* patForms::Rule::MaxLength */ - -function pFRC_MaxLength(field) { - this.field = eval('pfe_' + field); -} - -pFRC_MaxLength.prototype.validate = function() { - value = this.field.getValue(); - if (value.length > this.value) { - alert('Please enter a value that is max. ' + this.value + ' characters long.'); - } -} - -pFRC_MaxLength.prototype.setValue = function(value) { - this.value = value; -} - -/* END: patForms::Rule::MaxLength */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_MaxLength('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'MaxLength'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "Please enter a value that is max. [VALUE] characters long.", - ), - "de" => array( - 1 => "Bitte geben Sie einen max. [VALUE] Zeichen langen Wert ein.", - ), - "fr" => array( - 1 => "Please enter a value that is max. [VALUE] characters long.", - ) - ); - - /** - * possible values - * @access private - * @var array - */ - var $_values; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - private $value = 10; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->value = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (strlen($element->getValue()) <= $this->value) { - return true; - } - - $this->addValidationError(1, array('value' => $this->value)); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxValue.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxValue.php deleted file mode 100644 index 6b25b8c84..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MaxValue.php +++ /dev/null @@ -1,163 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_MaxValue extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - - var $globalScript = array( - 'html' => "/* patForms::Rule::MaxValue */ - -function pFRC_MaxValue(field) { - this.field = eval('pfe_' + field); -} - -pFRC_MaxValue.prototype.validate = function() { - value = this.field.getValue(); - if (parseInt(value) != value) { - alert('Please enter a number that is less or equal to ' + this.value); - } - if (parseInt(value) > this.value) { - alert('Please enter a number that is less or equal to ' + this.value); - } -} - -pFRC_MaxValue.prototype.setMaxValue = function(value) { - this.value = value; -} - -/* END: patForms::Rule::MaxValue */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_MaxValue('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'MaxValue'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "Please enter a number that is less or equal to [VALUE].", - ), - "de" => array( - 1 => "Bitte geben Sie eine Zahl kleiner oder gleich [VALUE] ein.", - ), - "fr" => array( - 1 => "Please enter a number that is less or equal to [VALUE].", - ) - ); - - /** - * the regEx pattern - * @access private - * @var string - */ - var $_value; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->_value = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (intval($element->getValue()) <= intval($this->_value)){ - return true; - } - - $this->addValidationError(1, array('value' => $this->_value)); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setMaxValue(%s);\n", $this->_id, $this->_value); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinLength.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinLength.php deleted file mode 100644 index 427600e49..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinLength.php +++ /dev/null @@ -1,161 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_MinLength extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - var $globalScript = array( - 'html' => "/* patForms::Rule::MinLength */ - -function pFRC_MinLength(field) { - this.field = eval('pfe_' + field); -} - -pFRC_MinLength.prototype.validate = function() { - value = this.field.getValue(); - if (value.length < this.value) { - alert('Please enter a value that is at least ' + this.value + ' characters long.'); - } -} - -pFRC_MinLength.prototype.setValue = function(value) { - this.value = value; -} - -/* END: patForms::Rule::MinLength */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_MinLength('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'MinLength'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "Please enter a value that is at least [VALUE] characters long.", - ), - "de" => array( - 1 => "Bitte geben Sie einen mindestens [VALUE] Zeichen langen Wert ein.", - ), - "fr" => array( - 1 => "Please enter a value that is at least [VALUE] characters long.", - ) - ); - - /** - * possible values - * @access private - * @var array - */ - var $_values; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - private $value = 10; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->value = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (strlen($element->getValue()) >= $this->value) { - return true; - } - - $this->addValidationError(1, array('value' => $this->value)); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinValue.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinValue.php deleted file mode 100644 index f31b107a4..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/MinValue.php +++ /dev/null @@ -1,165 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_MinValue extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - - var $globalScript = array( - 'html' => "/* patForms::Rule::MinValue */ - -function pFRC_MinValue(field) { - this.field = eval('pfe_' + field); -} - -pFRC_MinValue.prototype.validate = function() { - value = this.field.getValue(); - if (parseInt(value) != value) { - alert('Please enter a number that is greater or equal to ' + this.value); - } - if (parseInt(value) < this.value) { - alert('Please enter a number that is greater or equal to ' + this.value); - } -} - -pFRC_MinValue.prototype.setMinValue = function(value) { - this.value = value; -} - -/* END: patForms::Rule::MinValue */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_MinValue('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'MinValue'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "Please enter a number that is greater or equal to [VALUE].", - ), - "de" => array( - 1 => "Bitte geben Sie eine Zahl größer oder gleich [VALUE] ein.", - ), - "fr" => array( - 1 => "Please enter a number that is greater or equal to [VALUE].", - ) - ); - - /** - * the regEx pattern - * @access private - * @var string - */ - var $_value; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - private $value = 10; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->_value = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (intval($element->getValue()) >= intval($this->_value)){ - return true; - } - - $this->addValidationError(1, array('value' => $this->_value)); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setMinValue(%s);\n", $this->_id, $this->_value); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/NotMatch.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/NotMatch.php deleted file mode 100644 index c0ff7f365..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/NotMatch.php +++ /dev/null @@ -1,163 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_NotMatch extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - - var $globalScript = array( - 'html' => "/* patForms::Rule::NotMatch */ - -function pFRC_NotMatch(field) { - this.field = eval('pfe_' + field); -} - -pFRC_NotMatch.prototype.validate = function() { - value = this.field.getValue(); - if (value.match(this.pattern)) { - alert('This is an invalid value.'); - } -} - -pFRC_NotMatch.prototype.setValue = function(pattern) { - this.pattern = pattern; -} - -/* END: patForms::Rule::NotMatch */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_NotMatch('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'NotMatch'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "This is an invalid value.", - ), - "de" => array( - 1 => "Dies ist ein ungültiger Wert.", - ), - "fr" => array( - 1 => "This is an invalid value.", - ) - ); - - /** - * the regEx pattern - * @access private - * @var string - */ - var $_pattern; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - private $value = 10; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->_pattern = $value; - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (preg_match($this->_pattern, $element->getValue()) == 0){ - return true; - } - - $this->addValidationError(1); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - $script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/ValidValues.php b/airtime_mvc/library/propel/contrib/pat/patForms/Rule/ValidValues.php deleted file mode 100644 index 290ace0ed..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Rule/ValidValues.php +++ /dev/null @@ -1,182 +0,0 @@ - - * @license LGPL, see license.txt for details - * @link http://www.php-tools.net - */ -class patForms_Rule_ValidValues extends patForms_Rule -{ - /** - * script that will be displayed only once - * - * @access private - * @var array - */ - var $globalScript = array( - 'html' => "/* patForms::Rule::ValidValues */ - -Array.prototype.inArray = function(value) { - var i; - for (i=0; i < this.length; i++) { - if (this[i] === value) { - return true; - } - } - return false; -}; - -function pFRC_ValidValue(field) { - this.field = eval('pfe_' + field); -} - -pFRC_ValidValue.prototype.validate = function() { - value = this.field.getValue(); - for (var i = 0; i < this.values.length; i++) { - if (this.values[i] === value) { - return true; - } - } - var msg = 'Please enter one of the following values: '; - for (var i = 0; i < this.values.length; i++) { - msg = msg + this.values[i]; - if (i < this.values.length - 1) { - msg = msg + ', '; - } - } - alert(msg); -} - -pFRC_ValidValue.prototype.setValues = function(values) { - this.values = values; -} - -/* END: patForms::Rule::ValidValue */ -" - ); - - /** - * javascript that will be displayed once per instance - * - * @access private - * @var array - */ - var $instanceScript = array( - 'html' => "var pfr_[RULE::ID] = new pFRC_ValidValue('[CONTAINER::NAME]');\n" - ); - - /** - * properties that have to be replaced in the instance script. - * - * @access private - * @var array - */ - var $scriptPlaceholders = array( - 'RULE::SOURCE' => '_source', - ); - - /** - * name of the rule - * - * @abstract - * @access private - */ - var $ruleName = 'ValidValue'; - - /** - * define error codes and messages for the rule - * - * @access private - * @var array $validatorErrorCodes - * @todo translate error messages - */ - var $validatorErrorCodes = array( - "C" => array( - 1 => "Please enter one of the following values: [VALUES].", - ), - "de" => array( - 1 => "Bitte geben Sie einen der folgenden Werte ein: [VALUES].", - ), - "fr" => array( - 1 => "Please enter one of the following values: [VALUES].", - ) - ); - - /** - * possible values - * @access private - * @var array - */ - var $_values; - - /** - * field id that is used - * @access private - * @var string - */ - var $_field; - - public function __construct($params) { - - parent::__construct(); - - extract($params); - $this->_values = explode('|', $value); - } - - /** - * prepare the rule - * - * @access public - * @param object patForms - */ - function prepareRule(&$container) { - - patForms_Rule::prepareRule($container); - - $onChange = $container->getAttribute('onchange'); - $newHandler = sprintf('pfr_%s.validate();', $this->_id); - $container->setAttribute('onchange', $newHandler . $onChange); - - return true; - } - - /** - * method called by patForms or any patForms_Element to validate the - * element or the form. - * - * @access public - * @param object patForms form object - */ - function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) { - - if (in_array($element->getValue(), $this->_values)) { - return true; - } - - $this->addValidationError(1, array('values' => implode(', ', $this->_values))); - return false; - } - - /** - * - * - * @access public - */ - function registerJavascripts(&$form) { - - parent::registerJavascripts($form); - - foreach ($this->_values as $value) { - $values[] = "'$value'"; - } - $script = sprintf("pfr_%s.setValues(new Array(%s));\n", $this->_id, implode(', ', $values)); - $form->registerInstanceJavascript($script); - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/Storage/Propel.php b/airtime_mvc/library/propel/contrib/pat/patForms/Storage/Propel.php deleted file mode 100644 index f90c81dbb..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/Storage/Propel.php +++ /dev/null @@ -1,146 +0,0 @@ -peer = new $peername(); - $this->peername = $peername; - - $parts = explode('.', explode('.', $this->peer->getOMClass())); - $this->classname = array_pop($parts); - - $this->setPrimaryField('Id'); - } - - private function getCriteria($values) { - - $object = new $this->classname(); - //$object->populateFromArray($values); //TODO use a workaround until we'll get phpNamed keys in populateFromArray() - $object = $this->populateObjectFromArray($object, $values); - return $object->buildPkeyCriteria(); - } - - /** - * get an entry - * - * This tries to find an entry in the storage container - * that matches the current data that has been set in the - * form and populates the form with the data of this - * entry - * - * @access public - * @param object patForms patForms object that should be stored - * @return boolean true on success - */ - public function loadEntry(&$form) { - - if (!$object = $this->_entryExists($form->getValues())) { - // entry does not exists (why return an array here??) - return array(); - } - - $form->setValues($object->toArray()); - return true; - } - - public function validateEntry(&$form) { - - if (!$object = $this->_entryExists($form->getValues())) { - $object = new $this->classname(); - } - //$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray() - $object = $this->populateObjectFromArray($object, $form->getValues()); - $result = $object->validate(); - - if ($result !== true) { - $mapBuilder = $this->peer->getMapBuilder(); - $dbMap = $mapBuilder->getDatabaseMap(); - foreach ($result as $colname => $error) { - list($tablename, $colname) = explode('.', $colname); - $column = $dbMap->getTable($tablename)->getColumn($colname); - $element = $form->getElement($column->getPhpName()); - $element->addValidatorErrorCodes(array( - 'C' => array( - 1 => $error->getMessage() . ' (occured in Storage)', - ), - ), 1000); - $element->addValidationError(1001); - } - return false; - } - } - - /** - * adds an entry to the storage - * - * @param object patForms patForms object that should be stored - * @return boolean true on success - */ - public function _addEntry(&$form) { - - $object = new $this->classname(); - //$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray() - $object = $this->populateObjectFromArray($object, $form->getValues()); - $object->save(); - return true; - } - - /** - * updates an entry in the storage - * - * @param object patForms patForms object that should be stored - * @return boolean true on success - */ - public function _updateEntry(&$form, $primary) { - - $object = $this->_entryExists($form->getValues()); - //$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray() - $object = $this->populateObjectFromArray($object, $form->getValues()); - $object->save(); - return true; - } - - /** - * check, whether an entry exists - * - * @access private - * @param array - */ - public function _entryExists($values) { - - // This method gets called multiple times, e.g. when an existing - // object gets updated. We'll therefor cache results locally using - // a criteria string representation as hash. - - static $objects; - $criteria = $this->getCriteria($values); - $hash = $criteria->toString(); - - if (isset($objects[$hash])) { - return $objects[$hash]; - } - - $objects[$hash] = $this->peer->doSelectOne($criteria); - - if (empty($objects[$hash])) { - return false; - } - return $objects[$hash]; - } - - // this method is just a workaround - - private function populateObjectFromArray($object, $values) { - - foreach (array_keys($object->toArray()) as $key) { - if (array_key_exists($key, $values)) { - $object->{'set' . $key}($values[$key]); - } - } - return $object; - } -} diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/res/form.dynamic.tpl b/airtime_mvc/library/propel/contrib/pat/patForms/res/form.dynamic.tpl deleted file mode 100644 index 3935ea6c1..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/res/form.dynamic.tpl +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - {TITLE} - - - - - - - {START} - -
-

Validation failed

-

Sorry, your input could not be saved for the following reasons:

-
    - -
  • {FIELD}: {MESSAGE}
  • -
    -
-
-
- - - {ELEMENT} - - -
- -
{ELEMENT}
-
{DESCRIPTION}
-
-
-
-
- -
- {END} -
- - - -
\ No newline at end of file diff --git a/airtime_mvc/library/propel/contrib/pat/patForms/res/mysql-dump.bookstore.sql b/airtime_mvc/library/propel/contrib/pat/patForms/res/mysql-dump.bookstore.sql deleted file mode 100644 index 48c0ceeb1..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms/res/mysql-dump.bookstore.sql +++ /dev/null @@ -1,10 +0,0 @@ - -# This first example is tested with a Bookstore project on MySql -# (default setting Sqlite has not been tested) -# -# Additionally, you'll need some data in your tables. In case you -# don't have - here's a mini-dump to get the example running. - -INSERT INTO `author` VALUES (1, 'Martin', 'Heidegger'); -INSERT INTO `book` VALUES (1, 'Sein und Zeit', '3484701226', NULL, NULL); -INSERT INTO `publisher` VALUES (1, 'Max Niemeyer Verlag'); \ No newline at end of file diff --git a/airtime_mvc/library/propel/contrib/pat/patForms_Storage_Propel_test.php b/airtime_mvc/library/propel/contrib/pat/patForms_Storage_Propel_test.php deleted file mode 100644 index 04d3bdff1..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patForms_Storage_Propel_test.php +++ /dev/null @@ -1,97 +0,0 @@ - 2); - - -/** - * the rest should work out of the box if you don't have any unusal - * types in your database schema.xml (strings, int etc. should work) - */ - -require_once 'bookstore/' . $classname . '.php'; -Propel::init($propelConfFilename); - -// create a form definition - -$definition = patForms_Definition_Propel::create(array( - 'name' => $classname, - 'filename' => $path . '/form.' . $classname . '.xml', -)); - -// create a storage - -$storage = patForms::createStorage('Propel'); -$storage->setStorageLocation($classname . 'peer'); - -// create a form - -$form = &patForms::createCreator('Definition')->create($definition); -$form->setRenderer(patForms::createRenderer('Array')); -$form->setStorage($storage); -if (isset($pk)) { - $form->setValues($pk); -} - -// render it to a patTemplate (could be done by other template engines) - -$tpl = new patTemplate(); -$tpl->setRoot($path); -$tpl->readTemplatesFromInput('form.dynamic.tpl'); - -$tpl->addVar('page', 'title', 'Bookstore party'); -$tpl->addVar('form', 'start', $form->serializeStart()); -$tpl->addVar('form', 'end', $form->serializeEnd()); -$tpl->addRows('elements', $form->renderForm()); - -// this should be possible to be done in a more elegant way -if ($errors = $form->getValidationErrors()) { - foreach ($errors as $field => $error) { - $tpl->addVar('error', 'field', $field); - foreach ($error as $line) { - $tpl->addVar('error', 'message', $line['message']); - $tpl->addVar('error', 'code', $line['code']); - $tpl->parseTemplate('error', 'a'); - } - } - $tpl->setAttribute('errors', 'visibility', 'visible'); -} - -$tpl->displayParsedTemplate(); diff --git a/airtime_mvc/library/propel/contrib/pat/patTemplate.php b/airtime_mvc/library/propel/contrib/pat/patTemplate.php deleted file mode 100644 index 01347f63a..000000000 --- a/airtime_mvc/library/propel/contrib/pat/patTemplate.php +++ /dev/null @@ -1,2378 +0,0 @@ - - * @license LGPL - * @link http://www.php-tools.net - */ - -/** - * template already exists - */ -define( 'PATTEMPLATE_ERROR_TEMPLATE_EXISTS', 5010 ); - -/** - * template does not exist - */ -define ( 'PATTEMPLATE_WARNING_NO_TEMPLATE', 5011 ); - -/** - * unknown type - */ -define ( 'PATTEMPLATE_WARNING_UNKNOWN_TYPE', 5012 ); - -/** - * base class for module could not be found - */ -define( 'PATTEMPLATE_ERROR_BASECLASS_NOT_FOUND', 5050 ); - -/** - * module could not be found - */ -define( 'PATTEMPLATE_ERROR_MODULE_NOT_FOUND', 5051 ); - -/** - * array expected - */ -define( 'PATTEMPLATE_ERROR_EXPECTED_ARRAY', 5052 ); - -/** - * No input - */ -define( 'PATTEMPLATE_ERROR_NO_INPUT', 6000 ); - -/** - * patTemplate - * - * powerful templating engine - * - * @version 3.0.0 - * @package patTemplate - * @author Stephan Schmidt - * @license LGPL - * @link http://www.php-tools.net - */ -class patTemplate -{ - /** - * standard system vars that identify pat tools - * @var array - */ - var $_systemVars = array( - 'appName' => 'patTemplate', - 'appVersion' => '3.0.0', - 'author' => array( - 'Stephan Schmidt ' - ) - ); - - /** - * default attributes for new templates - * @access private - * @var array - */ - var $_defaultAttributes = array( - 'type' => 'standard', - 'visibility' => 'visible', - 'loop' => 1, - 'unusedvars' => 'strip', - 'whitespace' => 'keep', - 'autoclear' => 'off', - 'autoload' => 'on' - ); - - /** - * options for patTemplate - * - * Currently the following options are implemented: - * - maintainBc defines, whether patTemplate should be backwards compatible. - * This means, that you may use 'default' and 'empty' for subtemplates. - * - * @access private - * @var array - */ - var $_options = array( - 'startTag' => '{', - 'endTag' => '}', - 'root' => '.', - 'namespace' => 'patTemplate', - 'maintainBc' => true - ); - - /** - * start tag - * - * @access private - * @var string - */ - var $_startTag = '{'; - - /** - * end tag - * - * @access private - * @var string - */ - var $_endTag = '}'; - - /** - * loaded modules - * - * Modules are: - * - Readers - * - Caches - * - Variable modifiers - * - Filters - * - * @access private - * @var array - */ - var $_modules = array(); - - /** - * directories, where modules can be stored - * @access private - * @var array - */ - var $_moduleDirs = array(); - - /** - * stores all template names - * @access private - * @var array - */ - var $_templateList = array(); - - /** - * stores all template data - * @access private - * @var array - */ - var $_templates = array(); - - /** - * stores all global variables - * @access private - * @var array - */ - var $_globals = array(); - - /** - * stores all local variables - * @access private - * @var array - */ - var $_vars = array(); - - /** - * stores the name of the first template that has been - * found - * - * @access private - * @var string - */ - var $_root; - - /** - * output filters that should be used - * - * @access private - * @var array - */ - var $_outputFilters = array(); - - /** - * input filters that should be used - * - * @access private - * @var array - */ - var $_inputFilters = array(); - - /** - * template cache, that should be used - * - * @access private - * @var array - */ - var $_tmplCache = null; - - /** - * Create a new patTemplate instance. - * - * The constructor accepts the type of the templates as sole parameter. - * You may choose one of: - * - html (default) - * - tex - * - * The type influences the tags you are using in your templates. - * - * @access public - * @param string type (either html or tex) - */ - function patTemplate( $type = 'html' ) - { - if ( !defined( 'PATTEMPLATE_INCLUDE_PATH' ) ) - define( 'PATTEMPLATE_INCLUDE_PATH', dirname( __FILE__ ) . '/patTemplate' ); - - $this->setType( $type ); - } - - /** - * sets an option - * - * Currently, the following options are supported - * - maintainBc (true|false) - * - namespace (string) - * - * @access public - * @param string option to set - * @param string value of the option - */ - function setOption( $option, $value ) - { - $this->_options[$option] = $value; - } - - /** - * gets an option - * - * @access public - * @param string option to get - * @return mixed value of the option - */ - function getOption( $option ) - { - if ( !isset( $this->_options[$option] ) ) - return null; - return $this->_options[$option]; - } - - /** - * sets name of directory where templates are stored - * - * @access public - * @param string dir where templates are stored - * @deprecated please use patTemplate::setRoot() instead - */ - function setBasedir( $basedir ) - { - $this->_options['root'] = $basedir; - } - - /** - * sets root base for the template - * - * The parameter depends on the reader you are using. - * - * @access public - * @param string root base of the templates - */ - function setRoot( $root ) - { - $this->_options['root'] = $root; - } - - /** - * gets name of root base for the templates - * - * @access public - * @return mixed root base - */ - function getRoot() - { - return $this->_options['root']; - } - - /** - * sets namespace of patTemplate tags - * - * @access public - * @param string namespace - */ - function setNamespace( $ns ) - { - $this->_options['namespace'] = $ns; - } - - /** - * gets namespace of patTemplate tags - * - * @access public - * @return string namespace - */ - function getNamespace() - { - return $this->_options['namespace']; - } - - /** - * set default attribute - * - * @access public - * @param string attribute name - * @param mixed attribute value - */ - function setDefaultAttribute( $name, $value ) - { - $this->_defaultAttributes[$name] = $value; - } - - /** - * set default attributes - * - * @access public - * @param array attributes - */ - function setDefaultAttributes( $attributes ) - { - $this->_defaultAttributes = array_merge( $this->_defaultAttributes, $attributes ); - } - - /** - * get default attributes - * - * @access public - * @return return default attributes - */ - function getDefaultAttributes() - { - return $this->_defaultAttributes; - } - - /** - * set the type for the templates - * - * @access public - * @param string type (html or tex) - * @return boolean true on success - */ - function setType( $type ) - { - switch( strtolower( $type ) ) - { - case "tex": - $this->setTags( '<{', '}>' ); - break; - case "html": - $this->setTags( '{', '}' ); - break; - default: - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_UNKNOWN_TYPE, - "Unknown type '$type'. Please use 'html' or 'tex'." - ); - } - return true; - } - - /** - * set the start and end tag for variables - * - * @access public - * @param string start tag - * @param string end tag - * @return boolean true on success - */ - function setTags( $startTag, $endTag ) - { - $this->_options['startTag'] = $startTag; - $this->_options['endTag'] = $endTag; - - $this->_startTag = $startTag; - $this->_endTag = $endTag; - return true; - } - - /** - * get start tag for variables - * - * @access public - * @return string start tag - */ - function getStartTag() - { - return $this->_options['startTag']; - } - - /** - * get end tag for variables - * - * @access public - * @return string end tag - */ - function getEndTag() - { - return $this->_options['endTag']; - } - - /** - * add a directory where patTemplate should search for - * modules. - * - * You may either pass a string or an array of directories. - * - * patTemplate will be searching for a module in the same - * order you added them. If the module cannot be found in - * the custom folders, it will look in - * patTemplate/$moduleType. - * - * @access public - * @param string module type - * @param string|array directory or directories to search. - */ - function addModuleDir( $moduleType, $dir ) - { - if ( !isset( $this->_moduleDirs[$moduleType] ) ) - $this->_moduleDirs[$moduleType] = array(); - if ( is_array( $dir ) ) - $this->_moduleDirs[$moduleType] = array_merge( $this->_moduleDirs[$moduleType], $dir ); - else - array_push( $this->_moduleDirs[$moduleType], $dir ); - } - - /** - * Sets an attribute of a template - * - * supported attributes: visibilty, loop, parse, unusedvars - * - * @param string $template name of the template - * @param string $attribute name of the attribute - * @param mixed $value value of the attribute - * @access public - * @see setAttributes(),getAttribute(), clearAttribute() - */ - function setAttribute( $template, $attribute, $value ) - { - $template = strtolower( $template ); - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - - $attribute = strtolower( $attribute ); - $this->_templates[$template]['attributes'][$attribute] = $value; - return true; - } - - /** - * Sets several attribute of a template - * - * $attributes has to be a assotiative arrays containing attribute/value pairs - * supported attributes: visibilty, loop, parse, unusedvars - * - * @param string $template name of the template - * @param array $attributes attribute/value pairs - * @access public - * @see setAttribute(), getAttribute(), clearAttribute() - */ - function setAttributes( $template, $attributes ) - { - if ( !is_array( $attributes ) ) - { - return patErrorManager::raiseError( PATTEMPLATE_ERROR_EXPECTED_ARRAY, 'patTemplate::setAttributes: Expected array as second parameter, '.gettype( $attributes ).' given' ); - } - - $template = strtolower( $template ); - $attributes = array_change_key_case( $attributes ); - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - - $this->_templates[$template]['attributes'] = array_merge( $this->_templates[$template]['attributes'], $attributes ); - return true; - } - - /** - * Get all attributes of a template - * - * @param string name of the template - * @return array attributes - * @access public - */ - function getAttributes( $template ) - { - $template = strtolower( $template ); - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - return $this->_templates[$template]['attributes']; - } - - /** - * Gets an attribute of a template - * - * supported attributes: visibilty, loop, parse, unusedvars - * - * @param string $template name of the template - * @param string $attribute name of the attribute - * @return mixed value of the attribute - * @access public - * @see setAttribute(), setAttributes(), clearAttribute() - */ - function getAttribute( $template, $attribute ) - { - $template = strtolower( $template ); - $attribute = strtolower( $attribute ); - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - return $this->_templates[$template]['attributes'][$attribute]; - } - - /** - * Clears an attribute of a template - * - * supported attributes: visibilty, loop, parse, unusedvars - * - * @param string $template name of the template - * @param string $attribute name of the attribute - * @access public - * @see setAttribute(), setAttributes(), getAttribute() - */ - function clearAttribute( $template, $attribute ) - { - $template = strtolower( $template ); - $attribute = strtolower( $attribute ); - - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - $this->_templates[$template]['attributes'][$attribute] = '';; - return true; - } - - /** - * Prepare a template - * - * This can be used if you want to add variables to - * a template, that has not been loaded yet. - * - * @access public - * @param string template name - */ - function prepareTemplate( $name ) - { - $name = strtolower( $name ); - if ( !isset( $this->_vars[$name] ) ) - { - $this->_vars[$name] = array( - 'scalar' => array(), - 'rows' => array() - ); - } - } - - /** - * add a variable to a template - * - * A variable may also be an indexed array, but _not_ - * an associative array! - * - * @access public - * @param string $template name of the template - * @param string $varname name of the variable - * @param mixed $value value of the variable - */ - function addVar( $template, $varname, $value ) - { - $template = strtolower( $template ); - $varname = strtoupper( $varname ); - - if ( !is_array( $value ) ) - { - $this->_vars[$template]['scalar'][$varname] = $value; - return true; - } - - $cnt = count( $value ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( !isset( $this->_vars[$template]['rows'][$i] ) ) - $this->_vars[$template]['rows'][$i] = array(); - - $this->_vars[$template]['rows'][$i][$varname] = $value[$i]; - } - - return true; - } - - /** - * get the value of a variable - * - * @access public - * @param string name of the template - * @param string name of the variable - * @return string value of the variable, null if the variable is not set - */ - function getVar( $template, $varname ) - { - $template = strtolower( $template ); - $varname = strtoupper( $varname ); - - if ( isset( $this->_vars[$template]['scalar'][$varname] ) ) - return $this->_vars[$template]['scalar'][$varname]; - - $value = array(); - - $cnt = count( $this->_vars[$template]['rows'] ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( !isset( $this->_vars[$template]['rows'][$i][$varname] ) ) - continue; - array_push( $value, $this->_vars[$template]['rows'][$i][$varname] ); - } - if ( !empty( $value ) ) - return $value; - return null; - } - - /** - * Adds several variables to a template - * - * Each Template can have an unlimited amount of its own variables - * $variables has to be an assotiative array containing variable/value pairs - * - * @param string $template name of the template - * @param array $variables assotiative array of the variables - * @param string $prefix prefix for all variable names - * @access public - * @see addVar(), addRows(), addGlobalVar(), addGlobalVars() - */ - function addVars( $template, $variables, $prefix = '' ) - { - $template = strtolower( $template ); - $prefix = strtoupper( $prefix ); - $variables = array_change_key_case( $variables, CASE_UPPER ); - - foreach ( $variables as $varname => $value ) - { - $varname = $prefix.$varname; - - if ( !is_array( $value ) ) { - if (!is_scalar($value)) { - continue; - } - $this->_vars[$template]['scalar'][$varname] = $value; - continue; - } - - $cnt = count( $value ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( !isset( $this->_vars[$template]['rows'][$i] ) ) - $this->_vars[$template]['rows'][$i] = array(); - - $this->_vars[$template]['rows'][$i][$varname] = $value[$i]; - } - } - } - - /** - * Adds several rows of variables to a template - * - * Each Template can have an unlimited amount of its own variables - * Can be used to add a database result as variables to a template - * - * @param string $template name of the template - * @param array $rows array containing assotiative arrays with variable/value pairs - * @param string $prefix prefix for all variable names - * @access public - * @see addVar(), addVars(), addGlobalVar(), addGlobalVars() - */ - function addRows( $template, $rows, $prefix = '' ) - { - $template = strtolower( $template ); - $prefix = strtoupper( $prefix ); - - $cnt = count( $rows ); - for ( $i = 0; $i < $cnt; $i++ ) - { - if ( !isset( $this->_vars[$template]['rows'][$i] ) ) - $this->_vars[$template]['rows'][$i] = array(); - - $rows[$i] = array_change_key_case( $rows[$i], CASE_UPPER ); - - foreach ( $rows[$i] as $varname => $value ) - { - $this->_vars[$template]['rows'][$i][$prefix.$varname] = $value; - } - } - } - - /** - * Adds an object to a template - * - * All properties of the object will be available as template variables. - * - * @param string name of the template - * @param object|array object or array of objects - * @param string prefix for all variable names - * @access public - * @see addVar(), addRows(), addGlobalVar(), addGlobalVars() - */ - function addObject( $template, $object, $prefix = '' ) - { - if ( is_array( $object ) ) - { - $rows = array(); - foreach ( $object as $o ) - array_push( $rows, get_object_vars( $o ) ); - - $this->addRows( $template, $rows, $prefix ); - return true; - } - elseif ( is_object( $object ) ) - { - $this->addVars( $template, get_object_vars( $object ), $prefix ); - return true; - } - return false; - } - - /** - * Adds a global variable - * - * Global variables are valid in all templates of this object. - * A global variable has to be scalar, it will be converted to a string. - * - * @access public - * @param string $varname name of the global variable - * @param string $value value of the variable - * @return boolean true on success - * @see addGlobalVars(), addVar(), addVars(), addRows() - */ - function addGlobalVar( $varname, $value ) - { - $this->_globals[strtoupper( $varname )] = ( string )$value; - return true; - } - - /** - * Adds several global variables - * - * Global variables are valid in all templates of this object. - * - * $variables is an associative array, containing name/value pairs of the variables. - * - * @access public - * @param array $variables array containing the variables - * @param string $prefix prefix for variable names - * @return boolean true on success - * @see addGlobalVar(), addVar(), addVars(), addRows() - */ - function addGlobalVars( $variables, $prefix = '' ) - { - $variables = array_change_key_case( $variables, CASE_UPPER ); - $prefix = strtoupper( $prefix ); - foreach ( $variables as $varname => $value ) - { - $this->_globals[$prefix.$varname] = ( string )$value; - } - return true; - } - - /** - * get all global variables - * - * @access public - * @return array global variables - */ - function getGlobalVars() - { - return $this->_globals; - } - - /** - * checks wether a template exists - * - * @access public - * @param string name of the template - * @return boolean true, if the template exists, false otherwise - */ - function exists( $name ) - { - return in_array( strtolower( $name ), $this->_templateList ); - } - - /** - * enable a template cache - * - * A template cache will improve performace, as the templates - * do not have to be read on each request. - * - * @access public - * @param string name of the template cache - * @param array parameters for the template cache - * @return boolean true on success, patError otherwise - */ - function useTemplateCache( $cache, $params = array() ) - { - if ( !is_object( $cache ) ) - { - $cache = &$this->loadModule( 'TemplateCache', $cache, $params ); - } - if ( patErrorManager::isError( $cache ) ) - return $cache; - - $this->_tmplCache = &$cache; - return true; - } - - /** - * enable an output filter - * - * Output filters are used to modify the template - * result before it is sent to the browser. - * - * They are applied, when displayParsedTemplate() is called. - * - * @access public - * @param string name of the output filter - * @param array parameters for the output filter - * @return boolean true on success, patError otherwise - */ - function applyOutputFilter( $filter, $params = array() ) - { - if ( !is_object( $filter ) ) - { - $filter = &$this->loadModule( 'OutputFilter', $filter, $params ); - } - if ( patErrorManager::isError( $filter ) ) - return $filter; - - $this->_outputFilters[] = &$filter; - return true; - } - - /** - * enable an input filter - * - * input filters are used to modify the template - * stream before it is split into smaller templates- - * - * @access public - * @param string name of the input filter - * @param array parameters for the input filter - * @return boolean true on success, patError otherwise - */ - function applyInputFilter( $filter, $params = array() ) - { - if ( !is_object( $filter ) ) - { - $filter = &$this->loadModule( 'InputFilter', $filter, $params ); - } - if ( patErrorManager::isError( $filter ) ) - return $filter; - - $this->_inputFilters[] = &$filter; - return true; - } - - /** - * open a file and parse for patTemplate tags - * - * @access public - * @param name of the file - * @return true, if the template could be parsed - * @deprecated Use patTemplate::readTemplatesFromInput() instead, as the method name is misleading - * @see readTemplatesFromInput() - */ - function readTemplatesFromFile( $filename ) - { - return $this->readTemplatesFromInput( $filename, 'File' ); - } - - /** - * open any input and parse for patTemplate tags - * - * @access public - * @param string name of the input (filename, shm segment, etc.) - * @param string driver that is used as reader, you may also pass a Reader object - * @param array additional options that will only be used for this template - * @param string name of the template that should be used as a container, should not be used by public - * calls. - * @return boolean true, if the template could be parsed, false otherwise - */ - function readTemplatesFromInput( $input, $reader = 'File', $options = null, $parseInto = null ) - { - if ($input === '') { - return patErrorManager::raiseError(PATTEMPLATE_ERROR_NO_INPUT, 'No input to read has been passed.'); - } - - if ( is_array( $options ) ) - $options = array_merge( $this->_options, $options ); - else - $options = $this->_options; - - if ( !is_null( $parseInto ) ) - $parseInto = strtolower( $parseInto ); - - $templates = false; - if ( $this->_tmplCache !== null ) - { - /** - * get the unique cache key - */ - $key = $this->_tmplCache->getKey( $input, $options ); - - $templates = $this->_loadTemplatesFromCache( $input, $reader, $options, $key ); - - /** - * check for error returned from cache - */ - if ( patErrorManager::isError( $templates ) ) - return $templates; - } - - /** - * templates have not been loaded from cache - */ - if ( $templates === false ) - { - if ( !is_object( $reader ) ) - { - $reader = &$this->loadModule( 'Reader', $reader ); - if ( patErrorManager::isError( $reader ) ) - return $reader; - } - $reader->setOptions( $options ); - - /** - * set the root attributes - */ - if ( !is_null( $parseInto ) ) - { - $attributes = $this->getAttributes( $parseInto ); - if ( !patErrorManager::isError( $attributes ) ) - { - $reader->setRootAttributes( $attributes ); - } - } - - $templates = $reader->readTemplates( $input ); - - /** - * check for error returned from reader - */ - if ( patErrorManager::isError( $templates ) ) - return $templates; - - /** - * store the - */ - if ( $this->_tmplCache !== null ) - { - $this->_tmplCache->write( $key, $templates ); - } - } - - /** - * traverse all templates - */ - foreach ( $templates as $name => $spec ) - { - /** - * root template - */ - if ( $name == '__ptroot' ) - { - if ( $parseInto === false ) - { - continue; - } - if ( !in_array( $parseInto, $this->_templateList ) ) - continue; - - $spec['loaded'] = true; - $spec['attributes'] = $this->_templates[$parseInto]['attributes']; - $name = $parseInto; - } - else - { - /** - * store the name - */ - array_push( $this->_templateList, $name ); - } - - /** - * if this is the first template that has been loaded - * set it as the root template - */ - if ( $this->_root === null && is_null( $parseInto ) && isset( $spec['isRoot'] ) && $spec['isRoot'] == true ) - { - $this->_root = $name; - } - - /** - * set some default values - */ - $spec['iteration'] = 0; - $spec['lastMode'] = 'w'; - $spec['result'] = ''; - $spec['modifyVars'] = array(); - $spec['copyVars'] = array(); - $spec['defaultVars'] = array(); - - /** - * store the template - */ - $this->_templates[$name] = $spec; - - $this->prepareTemplate( $name ); - - /** - * store the default values of the variables - */ - foreach ( $spec['varspecs'] as $varname => $varspec ) - { - if ( isset( $varspec['modifier'] ) ) - { - $this->_templates[$name]['modifyVars'][$varname] = $varspec['modifier']; - } - - if ( isset( $varspec['copyfrom'] ) ) - { - $this->_templates[$name]['copyVars'][$varname] = $varspec['copyfrom']; - } - - if ( !isset( $varspec['default'] ) ) - continue; - - $this->_templates[$name]['defaultVars'][$varname] = $varspec['default']; - - if ( !is_null( $this->getVar( $name, $varname ) ) ) - continue; - - $this->addVar( $name, $varname, $varspec['default'] ); - } - - unset($this->_templates[$name]['varspecs']); - - /** - * autoload the template - * - * Some error management is needed here... - */ - if ( isset( $this->_templates[$name]['attributes']['src'] ) && $this->_templates[$name]['attributes']['autoload'] == 'on' ) - { - if ( $this->_templates[$name]['loaded'] !== true ) - { - if ( $this->_templates[$name]['attributes']['parse'] == 'on' ) - { - $this->readTemplatesFromInput( $this->_templates[$name]['attributes']['src'], $this->_templates[$name]['attributes']['reader'], $options, $name ); - } - else - { - $this->loadTemplateFromInput( $this->_templates[$name]['attributes']['src'], $this->_templates[$name]['attributes']['reader'], null, $name ); - } - $this->_templates[$name]['loaded'] = true; - } - } - } - - return true; - } - - /** - * load from template cache - * - * @access private - * @param string name of the input (filename, shm segment, etc.) - * @param string driver that is used as reader, you may also pass a Reader object - * @param array options for the reader - * @param string cache key - * @return array|boolean either an array containing the templates, or false - */ - function _loadTemplatesFromCache( $input, &$reader, $options, $key ) - { - if ( is_object( $reader ) ) - $statName = $reader->getName(); - else - $statName = $reader; - - $stat = &$this->loadModule( 'Stat', $statName ); - $stat->setOptions( $options ); - - /** - * get modification time - */ - $modTime = $stat->getModificationTime( $input ); - $templates = $this->_tmplCache->load( $key, $modTime ); - - return $templates; - } - - /** - * open any input and load content into template - * - * @access public - * @param string name of the input (filename, shm segment, etc.) - * @param string driver that is used as reader - * @param string name of the template that should be used as a container, - * @return boolean true, if the template could be parsed, false otherwise - */ - function loadTemplateFromInput( $input, $reader = 'File', $options = null, $parseInto = false ) - { - if ( is_array( $options ) ) - $options = array_merge( $this->_options, $options ); - else - $options = $this->_options; - - if ( !is_null( $parseInto ) ) - $parseInto = strtolower( $parseInto ); - - $reader = &$this->loadModule( 'Reader', $reader ); - if ( patErrorManager::isError( $reader ) ) - { - return $reader; - } - $reader->setOptions($options); - - $result = $reader->loadTemplate( $input ); - - if ( patErrorManager::isError( $result ) ) - { - return $result; - } - - $this->_templates[$parseInto]['content'] .= $result; - $this->_templates[$parseInto]['loaded'] = true; - return true; - } - - /** - * load a template that had autoload="off" - * - * This is needed, if you change the source of a template and want to - * load it, after changing the attribute. - * - * @access public - * @param string template name - * @return boolean true, if template could be loaded - */ - function loadTemplate( $template ) - { - $template = strtolower( $template ); - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - - if ( $this->_templates[$template]['loaded'] === true ) - return true; - - if ( $this->_templates[$template]['attributes']['parse'] == 'on' ) - { - return $this->readTemplatesFromInput( $this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], null, $template ); - } - else - { - return $this->loadTemplateFromInput( $this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], null, $template ); - } - } - - /** - * loads a patTemplate module - * - * Modules are located in the patTemplate folder and include: - * - Readers - * - Caches - * - Variable Modifiers - * - Filters - * - Functions - * - Stats - * - * @access public - * @param string moduleType (Reader|TemplateCache|Modifier|OutputFilter|InputFilter) - * @param string moduleName - * @param array parameters for the module - * @return object - */ - function &loadModule( $moduleType, $moduleName, $params = array() ) - { - if ( !isset( $this->_modules[$moduleType] ) ) - $this->_modules[$moduleType] = array(); - - $sig = md5( $moduleName . serialize( $params ) ); - - if ( isset( $this->_modules[$moduleType][$sig] ) ) - return $this->_modules[$moduleType][$sig]; - - if ( !class_exists( 'patTemplate_Module' ) ) - { - $file = sprintf( "%s/Module.php", $this->getIncludePath() ); - if ( !@include_once $file ) - return patErrorManager::raiseError( PATTEMPLATE_ERROR_BASECLASS_NOT_FOUND, 'Could not load module base class.' ); - } - - $baseClass = 'patTemplate_' . $moduleType; - if ( !class_exists( $baseClass ) ) - { - $baseFile = sprintf( "%s/%s.php", $this->getIncludePath(), $moduleType ); - if ( !@include_once $baseFile ) - return patErrorManager::raiseError( PATTEMPLATE_ERROR_BASECLASS_NOT_FOUND, "Could not load base class for $moduleType ($baseFile)." ); - } - - $moduleClass = 'patTemplate_' . $moduleType . '_' .$moduleName; - if ( !class_exists( $moduleClass ) ) - { - if ( isset( $this->_moduleDirs[$moduleType] ) ) - $dirs = $this->_moduleDirs[$moduleType]; - else - $dirs = array(); - array_push( $dirs, $this->getIncludePath() .'/'. $moduleType ); - - foreach ( $dirs as $dir ) - { - $moduleFile = sprintf( "%s/%s.php", $dir, str_replace( '_', '/', $moduleName ) ); - if ( @include_once $moduleFile ) - break; - return patErrorManager::raiseError( PATTEMPLATE_ERROR_MODULE_NOT_FOUND, "Could not load module $moduleClass ($moduleFile)." ); - } - } - - if ( !class_exists( $moduleClass ) ) - { - return patErrorManager::raiseError( PATTEMPLATE_ERROR_MODULE_NOT_FOUND, "Module file $moduleFile does not contain class $moduleClass." ); - } - - $this->_modules[$moduleType][$sig] = &new $moduleClass; - if ( method_exists( $this->_modules[$moduleType][$sig], 'setTemplateReference' ) ) - { - $this->_modules[$moduleType][$sig]->setTemplateReference( $this ); - } - - $this->_modules[$moduleType][$sig]->setParams( $params ); - - return $this->_modules[$moduleType][$sig]; - } - - /** - * checks whether a module exists. - * - * Modules are located in the patTemplate folder and include: - * - Readers - * - Caches - * - Variable Modifiers - * - Filters - * - Functions - * - Stats - * - * @access public - * @param string moduleType (Reader|TemplateCache|Modifier|OutputFilter|InputFilter) - * @param string moduleName - * @return boolean - */ - function moduleExists( $moduleType, $moduleName ) - { - if ( isset( $this->_moduleDirs[$moduleType] ) ) - $dirs = $this->_moduleDirs[$moduleType]; - else - $dirs = array(); - array_push( $dirs, $this->getIncludePath() .'/'. $moduleType ); - - foreach ( $dirs as $dir ) - { - $moduleFile = sprintf( "%s/%s.php", $dir, str_replace( '_', '/', $moduleName ) ); - if ( !file_exists( $moduleFile ) ) - continue; - if ( !is_readable( $moduleFile ) ) - continue; - return true; - } - return false; - } - - /** - * parses a template - * - * Parses a template and stores the parsed content. - * mode can be "w" for write (delete already parsed content) or "a" for append (appends the - * new parsed content to the already parsed content) - * - * @access public - * @param string name of the template - * @param string mode for the parsing - */ - function parseTemplate( $template, $mode = 'w' ) - { - $template = strtolower( $template ); - - if ( !isset( $this->_templates[$template] ) ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$template' does not exist." - ); - } - - /** - * template is not visible - */ - if ( $this->_templates[$template]['attributes']['visibility'] == 'hidden' ) - { - $this->_templates[$template]['result'] = ''; - $this->_templates[$template]['parsed'] = true; - return true; - } - - /** - * check, if the template has been loaded - * and load it if necessary. - */ - if ( $this->_templates[$template]['loaded'] !== true ) - { - if ( $this->_templates[$template]['attributes']['parse'] == 'on' ) - { - $result = $this->readTemplatesFromInput( $this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], null, $template ); - } - else - { - $result = $this->loadTemplateFromInput( $this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], null, $template ); - } - if ( patErrorManager::isError( $result ) ) - { - return $result; - } - } - - /** - * check for autoclear - */ - if ( - isset( $this->_templates[$template]['attributes']['autoclear'] ) && - $this->_templates[$template]['attributes']['autoclear'] == 'yes' && - $mode === 'w' && - $this->_templates[$template]['lastMode'] != 'a' - ) - { - $this->_templates[$template]['parsed'] = false; - } - - /** - * template has been parsed and mode is not 'append' - */ - if ( $this->_templates[$template]['parsed'] === true && $mode === 'w' ) - { - return true; - } - - $this->_templates[$template]['lastMode'] = $mode; - - $this->_initTemplate( $template ); - - if ( !isset( $this->_vars[$template]['rows'] ) ) - $this->_vars[$template]['rows'] = array(); - $loop = count( $this->_vars[$template]['rows'] ); - - /** - * loop at least one times - */ - if ( $loop < 1 ) - $loop = 1; - - if ( isset( $this->_templates[$template]['attributes']['maxloop'] ) ) - { - $loop = ceil( $loop / $this->_templates[$template]['attributes']['maxloop'] ) * $this->_templates[$template]['attributes']['maxloop']; - } - - $this->_templates[$template]['loop'] = max( $this->_templates[$template]['attributes']['loop'], $loop ); - - $start = 0; - if ( isset( $this->_templates[$template]['attributes']['limit'] ) ) - { - $p = strpos( $this->_templates[$template]['attributes']['limit'], ',' ); - if ( $p === false ) - { - $this->_templates[$template]['loop'] = min( $this->_templates[$template]['loop'], $this->_templates[$template]['attributes']['limit'] ); - $start = 0; - } - else - { - $start = substr( $this->_templates[$template]['attributes']['limit'], 0, $p ); - $end = substr( $this->_templates[$template]['attributes']['limit'], $p+1 )+$start; - - $this->_templates[$template]['loop'] = min( $this->_templates[$template]['loop'], $end ); - } - } - - /** - * template should be cleared before parsing - */ - if ( $mode == 'w' ) - { - $this->_templates[$template]['result'] = ''; - $this->_templates[$template]['iteration'] = $start; - } - - $loopCount = 0; - for ( $i = $start; $i < $this->_templates[$template]['loop']; $i++ ) - { - $finished = false; - - unset( $this->_templates[$template]['vars'] ); - - /** - * fetch the variables - */ - $this->_fetchVariables( $template ); - - /** - * fetch the template - */ - $result = $this->_fetchTemplate( $template ); - - if ( $result === false ) - { - $this->_templates[$template]['iteration']++; - continue; - } - - /** - * parse - */ - $this->_parseVariables( $template ); - $this->_parseDependencies( $template ); - - /** - * store result - */ - $this->_templates[$template]['result'] .= $this->_templates[$template]['work']; - - $this->_templates[$template]['iteration']++; - - ++$loopCount; - - /** - * check for maximum loops - */ - if ( isset( $this->_templates[$template]['attributes']['maxloop'] ) ) - { - if ( $loopCount == $this->_templates[$template]['attributes']['maxloop'] && $i < ( $loop-1 ) ) - { - $loopCount = 0; - $finished = true; - $this->_templates[$template]['parsed'] = true; - $this->parseTemplate( $this->_templates[$template]['attributes']['parent'], 'a' ); - $this->_templates[$template]['parsed'] = false; - $this->_templates[$template]['result'] = ''; - } - } - } - - if ( !$finished && isset( $this->_templates[$template]['attributes']['maxloop'] ) ) - { - $this->_templates[$template]['parsed'] = true; - $this->parseTemplate( $this->_templates[$template]['attributes']['parent'], 'a', false ); - $this->_templates[$template]['parsed'] = false; - $this->_templates[$template]['result'] = ''; - $this->_templates[$this->_templates[$template]['attributes']['parent']]['work'] = ''; - } - - $this->_parseGlobals($template); - - $this->_handleUnusedVars( $template ); - - $this->_templates[$template]['parsed'] = true; - - if ( isset( $this->_templates[$template]['attributes']['autoclear'] ) && $this->_templates[$template]['attributes']['autoclear'] == 'yes' ) - { - $this->_vars[$template] = array( - 'scalar' => array(), - 'rows' => array() - ); - } - - return true; - } - - /** - * Initialize a template - * - * This method checks the variable specifications and - * copys variables from other templates. - * - * @access private - * @param string name of the template - * @return boolean true on success - */ - function _initTemplate( $template ) - { - foreach ( $this->_templates[$template]['copyVars'] as $dest => $src ) - { - /** - * copy from the same template - */ - if ( !is_array( $src ) ) - { - $srcTemplate = $template; - $srcVar = $src; - } - else - { - $srcTemplate = $src[0]; - $srcVar = $src[1]; - } - - $copied = false; - - /** - * copy from another template - */ - if ( isset( $this->_vars[$srcTemplate] ) ) - { - if ( isset( $this->_vars[$srcTemplate]['scalar'][$srcVar] ) ) - { - $this->_vars[$template]['scalar'][$dest] = $this->_vars[$srcTemplate]['scalar'][$srcVar]; - continue; - } - - $rows = count( $this->_vars[$srcTemplate]['rows'] ); - - for ( $i = 0; $i < $rows; $i++ ) - { - if ( !isset( $this->_vars[$srcTemplate]['rows'][$i][$srcVar] ) ) - continue; - if ( !isset( $this->_vars[$template]['rows'][$i] ) ) - $this->_vars[$template]['rows'][$i] = array(); - $this->_vars[$template]['rows'][$i][$dest] = $this->_vars[$srcTemplate]['rows'][$i][$srcVar]; - $copied = true; - } - } - if ( !$copied && isset( $this->_globals[$srcVar] )) - { - $this->_vars[$template]['scalar'][$dest] = $this->_globals[$srcVar]; - } - - } - return true; - } - - /** - * parse all variables in a template - * - * @access private - * @param string - */ - function _parseVariables( $template ) - { - /** - * modify variables before parsing - */ - $this->_applyModifers($template, $this->_templates[$template]['vars']); - - foreach ( $this->_templates[$template]['vars'] as $key => $value ) - { - if ( is_array( $value ) ) - { - if ( count( $this->_templates[$template]['currentDependencies'] ) == 1 ) - { - $child = $this->_templates[$template]['currentDependencies'][0]; - } - else - { - if ( isset( $this->_templates[$template]['attributes']['child'] ) ) - $child = $this->_templates[$template]['attributes']['child']; - else - continue; - } - - $this->setAttribute( $child, 'autoclear', 'yes' ); - $this->addVar( $child, $key, $value ); - continue; - } - - $var = $this->_startTag.$key.$this->_endTag; - $this->_templates[$template]['work'] = @str_replace( $var, $value, $this->_templates[$template]['work'] ); - } - return true; - } - - /** - * parse global variables in the template - * - * @access private - * @param string name of the template - * @return boolean - */ - function _parseGlobals($template) - { - $globalVars = $this->_globals; - $this->_applyModifers($template, $globalVars); - - foreach ( $globalVars as $key => $value ) - { - if ( is_array( $value ) ) - { - continue; - } - - $var = $this->_startTag.$key.$this->_endTag; - $this->_templates[$template]['result'] = str_replace( $var, $value, $this->_templates[$template]['result'] ); - } - return true; - } - - /** - * apply variable modifiers - * - * The variables will be passed by reference. - * - * @access private - * @param string name of the template (use modifiers from this template) - * @param array variables to which the modifiers should be applied - * @return boolean - */ - function _applyModifers($template, &$vars) - { - foreach ( $this->_templates[$template]['modifyVars'] as $varname => $modifier ) - { - if ( !isset( $vars[$varname] ) ) - continue; - - if ( ( $modifier['type'] === 'php' || $modifier['type'] === 'auto' ) && is_callable( $modifier['mod'] ) ) - { - $vars[$varname] = call_user_func( $modifier['mod'], $vars[$varname] ); - continue; - } - - if ( $modifier['type'] === 'php' ) - continue; - - $mod = &$this->loadModule( 'Modifier', ucfirst( $modifier['mod'] ) ); - $vars[$varname] = $mod->modify( $vars[$varname], $modifier['params'] ); - } - return true; - } - - /** - * parse all dependencies in a template - * - * @access private - * @param string - */ - function _parseDependencies( $template ) - { - $countDep = count( $this->_templates[$template]['currentDependencies'] ); - for ( $i = 0; $i < $countDep; $i++ ) - { - $depTemplate = $this->_templates[$template]['currentDependencies'][$i]; - $this->parseTemplate( $depTemplate ); - $var = $this->_startTag.'TMPL:'.strtoupper( $depTemplate) .$this->_endTag; - $this->_templates[$template]['work'] = str_replace( $var, $this->_templates[$depTemplate]['result'], $this->_templates[$template]['work'] ); - } - return true; - } - - /** - * fetch plain template - * - * The template content will be stored in the template - * configuration so it can be used by other - * methods. - * - * @access private - * @param string template name - * @return boolean - */ - function _fetchTemplate( $template ) - { - switch( $this->_templates[$template]['attributes']['type'] ) - { - /** - * condition template - */ - case 'condition': - $value = $this->_getConditionValue( $template, $this->_templates[$template]['attributes']['conditionvar'] ); - if ( $value === false ) - { - $this->_templates[$template]['work'] = ''; - $this->_templates[$template]['currentDependencies'] = array(); - } - else - { - $this->_templates[$template]['work'] = $this->_templates[$template]['subtemplates'][$value]['data']; - $this->_templates[$template]['currentDependencies'] = $this->_templates[$template]['subtemplates'][$value]['dependencies']; - } - break; - - /** - * condition template - */ - case 'simplecondition': - foreach ( $this->_templates[$template]['attributes']['requiredvars'] as $var ) - { - if ( $var[0] !== $template ) - $this->_fetchVariables($var[0]); - - if ( isset( $this->_templates[$var[0]]['vars'][$var[1]] ) && strlen( $this->_templates[$var[0]]['vars'][$var[1]] ) > 0 ) - continue; - if (isset($this->_templates[$template]['attributes']['useglobals'])) - { - if (isset($this->_globals[$var[1]]) && strlen($this->_globals[$var[1]]) > 1) - continue; - } - - $this->_templates[$template]['work'] = ''; - $this->_templates[$template]['currentDependencies'] = array(); - break 2; - } - $this->_templates[$template]['work'] = $this->_templates[$template]['content']; - $this->_templates[$template]['currentDependencies'] = $this->_templates[$template]['dependencies']; - break; - - /** - * modulo template - */ - case 'modulo': - // check for empty template - if ($this->_hasVariables($template)) { - $value = ( $this->_templates[$template]['iteration'] + 1 ) % $this->_templates[$template]['attributes']['modulo']; - } else { - $value = '__empty'; - } - - $value = $this->_getConditionValue( $template, $value, false ); - if ( $value === false ) - { - $this->_templates[$template]['work'] = ''; - $this->_templates[$template]['currentDependencies'] = array(); - } - else - { - $this->_templates[$template]['work'] = $this->_templates[$template]['subtemplates'][$value]['data']; - $this->_templates[$template]['currentDependencies'] = $this->_templates[$template]['subtemplates'][$value]['dependencies']; - } - break; - - /** - * standard template - */ - default: - $this->_templates[$template]['work'] = $this->_templates[$template]['content']; - $this->_templates[$template]['currentDependencies'] = $this->_templates[$template]['dependencies']; - break; - } - return true; - } - - /** - * check, whether a template contains variables - * - * @access private - * @param string template name - * @return boolean - */ - function _hasVariables($template) - { - if (!empty($this->_vars[$template]['scalar'])) { - return true; - } - if (isset($this->_vars[$template]['rows'][$this->_templates[$template]['iteration']])) { - return true; - } - return false; - } - - /** - * fetch the value of a condition variable - * - * _fetchVariables() has to be called before this - * method is being called. - * - * @access private - * @param string template name - * @param string condition value - * @param boolean flag that indicates whether value is the name of the variable that should be resolved - * - * @todo split this method into smaller check methods that will be called according to - * a priority list - */ - function _getConditionValue( $template, $value, $isVar = true ) - { - if ( $isVar === true ) - { - if ( isset( $this->_templates[$template]['attributes']['conditiontmpl'] ) ) - { - $_template = $this->_templates[$template]['attributes']['conditiontmpl']; - $this->_fetchVariables( $_template ); - } - else - { - $_template = $template; - } - - /** - * get the value from the template variables - */ - if ( !isset( $this->_templates[$_template]['vars'][$value] ) || strlen( $this->_templates[$_template]['vars'][$value] ) === 0 ) - { - if ( $this->_templates[$template]['attributes']['useglobals'] == 'yes' || $this->_templates[$template]['attributes']['useglobals'] == 'useglobals' ) - { - if ( isset( $this->_globals[$value] ) && strlen( $this->_globals[$value] ) > 0 ) - { - $value = $this->_globals[$value]; - } - else - { - $value = '__empty'; - } - } - else - { - $value = '__empty'; - } - } - else - { - $value = $this->_templates[$_template]['vars'][$value]; - } - } - else - { - $_template = $template; - } - - /** - * is __first? - */ - if ( $this->_templates[$_template]['iteration'] == 0 ) - { - if ( isset( $this->_templates[$template]['subtemplates']['__first'] ) ) - { - return '__first'; - } - } - - /** - * is __last? - */ - $max = $this->_templates[$_template]['loop'] - 1; - if ( $this->_templates[$_template]['iteration'] == $max ) - { - if ( isset( $this->_templates[$template]['subtemplates']['__last'] ) ) - { - return '__last'; - } - } - - /** - * found an exact match - */ - if ( isset( $this->_templates[$template]['subtemplates'][$value] ) ) - { - return $value; - } - - /** - * is __default? - */ - if ( isset( $this->_templates[$template]['subtemplates']['__default'] ) ) - { - return '__default'; - } - - return false; - } - - /** - * fetch variables for a template - * - * The variables will be stored in the template - * configuration so they can be used by other - * methods. - * - * @access private - * @param string template name - * @return boolean - */ - function _fetchVariables( $template ) - { - /** - * variables already have been fetched - */ - if ( isset( $this->_templates[$template]['vars'] ) ) - { - return true; - } - - $iteration = $this->_templates[$template]['iteration']; - - if ( isset( $this->_templates[$template]['attributes']['varscope'] ) ) - { - $scopeTemplate = $this->_templates[$template]['attributes']['varscope']; - if ($this->exists($scopeTemplate)) { - $this->_fetchVariables( $scopeTemplate ); - $vars = $this->_templates[$scopeTemplate]['vars']; - } else { - patErrorManager::raiseWarning(PATTEMPLATE_WARNING_NO_TEMPLATE, 'Template \''.$scopeTemplate.'\' does not exist, referenced in varscope attribute of template \''.$template.'\''); - $vars = array(); - } - } - else - { - $vars = array(); - } - - /** - * get the scalar variables - */ - if ( isset( $this->_vars[$template] ) && isset( $this->_vars[$template]['scalar'] ) ) - { - $vars = array_merge( $vars, $this->_vars[$template]['scalar'] ); - } - - /** - * get the row variables - */ - if ( isset( $this->_vars[$template]['rows'][$iteration] ) ) - { - $vars = array_merge( $vars, $this->_vars[$template]['rows'][$iteration] ); - } - - /** - * add some system variables - */ - $currentRow = $iteration + 1; - $vars['PAT_ROW_VAR'] = $currentRow; - - if ( $this->_templates[$template]['attributes']['type'] == 'modulo' ) - { - $vars['PAT_MODULO_REP'] = ceil( $currentRow / $this->_templates[$template]['attributes']['modulo'] ); - $vars['PAT_MODULO'] = ( $this->_templates[$template]['iteration'] + 1 ) % $this->_templates[$template]['attributes']['modulo']; - } - - if ( $this->_templates[$template]['attributes']['addsystemvars'] !== false ) - { - $vars['PATTEMPLATE_VERSION'] = $this->_systemVars['appVersion']; - $vars['PAT_LOOPS'] = $this->_templates[$template]['loop']; - - switch ($this->_templates[$template]['attributes']['addsystemvars']) - { - case 'boolean': - $trueValue = 'true'; - $falseValue = 'false'; - break; - case 'integer': - $trueValue = '1'; - $falseValue = '0'; - break; - default: - $trueValue = $this->_templates[$template]['attributes']['addsystemvars']; - $falseValue = ''; - break; - } - - $vars['PAT_IS_ODD'] = ( $currentRow % 2 == 1 ) ? $trueValue : $falseValue; - $vars['PAT_IS_EVEN'] = ( $currentRow % 2 == 0 ) ? $trueValue : $falseValue; - $vars['PAT_IS_FIRST'] = ( $currentRow == 1 ) ? $trueValue : $falseValue; - $vars['PAT_IS_LAST'] = ( $currentRow == $this->_templates[$template]['loop'] ) ? $trueValue : $falseValue; - } - - $this->_templates[$template]['vars'] = $vars; - return true; - } - - /** - * handle all unused variables in a template - * - * This is influenced by the 'unusedvars' attribute of the - * template - * - * @access private - * @param string - */ - function _handleUnusedVars( $template ) - { - $regexp = '/('.$this->_startTag.'[^a-z]+'.$this->_endTag.')/U'; - - switch( $this->_templates[$template]['attributes']['unusedvars'] ) - { - case 'comment': - $this->_templates[$template]['result'] = preg_replace( $regexp, '', $this->_templates[$template]['result'] ); - break; - case 'strip': - $this->_templates[$template]['result'] = preg_replace( $regexp, '', $this->_templates[$template]['result'] ); - break; - case 'nbsp': - $this->_templates[$template]['result'] = preg_replace( $regexp, ' ', $this->_templates[$template]['result'] ); - break; - case 'ignore': - break; - default: - $this->_templates[$template]['result'] = preg_replace( $regexp, $this->_templates[$template]['attributes']['unusedvars'], $this->_templates[$template]['result'] ); - break; - } - return true; - } - - /** - * returns a parsed Template - * - * If the template already has been parsed, it just returns the parsed template. - * If the template has not been loaded, it will be loaded. - * - * @access public - * @param string name of the template - * @return string Content of the parsed template - * @see displayParsedTemplate() - */ - function getParsedTemplate( $name = null ) - { - if ( is_null( $name ) ) - $name = $this->_root; - - $name = strtolower( $name ); - - $result = $this->parseTemplate( $name ); - - if ( patErrorManager::isError( $result ) ) - return $result; - - return $this->_templates[$name]['result']; - } - - /** - * displays a parsed Template - * - * If the template has not been loaded, it will be loaded. - * - * @see getParsedTemplate() - * @param string name of the template - * @return boolean true on success - * @access public - */ - function displayParsedTemplate( $name = null ) - { - $result = $this->getParsedTemplate( $name ); - - /** - * error happened - */ - if ( patErrorManager::isError( $result ) ) - return $result; - - $cnt = count( $this->_outputFilters ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $result = $this->_outputFilters[$i]->apply( $result ); - } - - echo $result; - return true; - } - - /** - * parse a template and push the result into a variable of any other - * template - * - * If the template already has been parsed, it will just be pushed into the variable. - * If the template has not been loaded, it will be loaded. - * - * @access public - * @param string name of the template - * @return string Content of the parsed template - * @param boolean if set to true, the value will be appended to the value already stored. - * @see getParsedTemplate() - * @see addVar() - */ - function parseIntoVar( $srcTmpl, $destTmpl, $var, $append = false ) - { - $srcTmpl = strtolower( $srcTmpl ); - $destTmpl = strtolower( $destTmpl ); - $var = strtoupper($var); - - $result = $this->parseTemplate( $srcTmpl ); - - if ( patErrorManager::isError( $result ) ) - return $result; - - if ( $append !== true || !isset( $this->_vars[$destTmpl]['scalar'][$var] ) ) - $this->_vars[$destTmpl]['scalar'][$var] = ''; - - $this->_vars[$destTmpl]['scalar'][$var] .= $this->_templates[$srcTmpl]['result']; - - return true; - } - - /** - * clears a parsed Template - * - * Parsed Content, variables and the loop attribute are cleared - * - * If you will not be using this template anymore, then you should - * call freeTemplate() - * - * @access public - * @param string name of the template - * @param boolean set this to true to clear all child templates, too - * @see clearAllTemplates() - * @see freeTemplate() - */ - function clearTemplate( $name, $recursive = false ) - { - $name = strtolower( $name ); - $this->_templates[$name]['parsed'] = false; - $this->_templates[$name]['work'] = ''; - $this->_templates[$name]['iteration'] = 0; - $this->_templates[$name]['result'] = ''; - $this->_vars[$name] = array( - 'scalar' => array(), - 'rows' => array() - ); - if (!empty($this->_templates[$name]['defaultVars'])) { - foreach ($this->_templates[$name]['defaultVars'] as $varname => $value) { - $this->addVar($name, $varname, $value); - } - } - - /** - * clear child templates as well - */ - if ( $recursive === true ) - { - $deps = $this->_getDependencies( $name ); - foreach ( $deps as $dep ) - { - $this->clearTemplate( $dep, true ); - } - } - return true; - } - - /** - * clears all templates - * - * @access public - * @uses clearTemplate() - */ - function clearAllTemplates() - { - $templates = array_keys( $this->_templates ); - $cnt = count( $templates ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $this->clearTemplate( $templates[$i] ); - } - return true; - } - - /** - * frees a template - * - * All memory consumed by the template - * will be freed. - * - * @access public - * @param string name of the template - * @param boolean clear dependencies of the template - * @see freeAllTemplates() - */ - function freeTemplate( $name, $recursive = false ) - { - $name = strtolower( $name ); - $key = array_search( $name, $this->_templateList ); - if ( $key === false ) - { - return patErrorManager::raiseWarning( - PATTEMPLATE_WARNING_NO_TEMPLATE, - "Template '$name' does not exist." - ); - } - - unset( $this->_templateList[$key] ); - $this->_templateList = array_values( $this->_templateList ); - - /** - * free child templates as well - */ - if ( $recursive === true ) - { - $deps = $this->_getDependencies( $name ); - foreach ( $deps as $dep ) - { - $this->freeTemplate( $dep, true ); - } - } - - unset( $this->_templates[$name] ); - unset( $this->_vars[$name] ); - - return true; - } - - /** - * frees all templates - * - * All memory consumed by the templates - * will be freed. - * - * @access public - * @see freeTemplate() - */ - function freeAllTemplates() - { - $this->_templates = array(); - $this->_vars = array(); - } - - /** - * get _all_ dependencies of a template, - * regardless of the subtemplates - * - * @access private - * @param string template name - * @return array list of all subtemplates - */ - function _getDependencies( $template ) - { - $deps = array(); - if ( isset( $this->_templates[$template]['dependencies'] ) ) - $deps = $this->_templates[$template]['dependencies']; - - if ( isset( $this->_templates[$template]['subtemplates'] ) ) - { - foreach ( $this->_templates[$template]['subtemplates'] as $sub ) - { - if ( isset( $sub['dependencies'] ) ) - $deps = array_merge( $deps, $sub['dependencies'] ); - } - } - $deps = array_unique( $deps ); - return $deps; - } - - /** - * Displays useful information about all or named templates - * - * This method breaks BC, as it now awaits an array instead of - * unlimited parameters. - * - * @param mixed array of templates that should be dumped, or null if you - * want all templates to be dumped - * @param string dumper - * @access public - */ - function dump( $restrict = null, $dumper = 'Html' ) - { - if ( is_string( $restrict ) ) - $restrict = array( $restrict ); - - $dumper = &$this->loadModule( 'Dump', $dumper ); - - if ( patErrorManager::isError( $dumper ) ) - { - return $dumper; - } - - if ( is_null( $restrict ) ) - { - $templates = $this->_templates; - $vars = $this->_vars; - } - else - { - $restrict = array_map( 'strtolower', $restrict ); - - $templates = array(); - $vars = array(); - - foreach ( $this->_templates as $name => $spec ) - { - if ( !in_array( $name, $restrict ) ) - continue; - $templates[$name] = $spec; - $vars[$name] = $this->_vars[$name]; - } - } - - $dumper->displayHeader(); - $dumper->dumpGlobals( $this->_globals ); - $dumper->dumpTemplates( $templates, $vars ); - $dumper->displayFooter(); - - return true; - } - - /** - * get the include path - * - * @access public - */ - function getIncludePath() - { - return PATTEMPLATE_INCLUDE_PATH; - } - - /** - * apply input filters that have been set - * - * This is being called by the readers. - * - * @access public - * @param string template - * @return string filtered templeta - */ - function applyInputFilters( $template ) - { - $cnt = count( $this->_inputFilters ); - for ( $i = 0; $i < $cnt; $i++ ) - { - $template = $this->_inputFilters[$i]->apply( $template ); - } - return $template; - } - - /** - * Convert the template to its string representation. - * - * This method allows you to just echo the patTemplate - * object in order to display the template. - * - * Requires PHP5 - * - * - * $tmpl = new patTemplate(); - * $tmpl->readTemplatesFromFile( 'myfile.tmpl' ); - * echo $tmpl; - * - * - * @access private - * @return string - */ - function __toString() - { - return $this->getParsedTemplate(); - } -} diff --git a/airtime_mvc/library/propel/contrib/pear/HTML_QuickForm_Propel/Propel.php b/airtime_mvc/library/propel/contrib/pear/HTML_QuickForm_Propel/Propel.php deleted file mode 100644 index 6a51e84fa..000000000 --- a/airtime_mvc/library/propel/contrib/pear/HTML_QuickForm_Propel/Propel.php +++ /dev/null @@ -1,909 +0,0 @@ -. - */ - -require_once 'HTML/QuickForm.php'; - -define('HTML_QUICKFORM_PROPEL_NO_COLUMNS', 2); -define('HTML_QUICKFORM_PROPEL_ALL_COLUMNS', 3); -define('HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE', 4); -define('HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN', 5); - -/* On large foreign table resultsets propel choked */ -# ini_set('memory_limit', '50M'); - -/** - * - * NOTE: HTML_QuickForm_Propel extends HTML_QuickForm, so all QuickForm functionality is available. - * - * A fictive example: - * - * $className = 'book'; - * $id = '7'; // existing item - * $id = null; // when no id is passed, it's assumed we are creating a new item - * - * $quickForm = new HTML_QuickForm_Propel($className, $id); // optionally pass it to the constructor - * $quickForm->setAction('/Bookstore/Form'); - * $quickForm->addElement('header', '', 'HTML_QuickForm_Propel'); - * $quickForm->setId($id); - * $quickForm->setClassName($className); - * $quickForm->setTarget('_self'); - * $quickForm->setMethod('post'); - * - * // use this to override the default behaviour for - * // foreign table select boxes, UserPeer::UNAME will be shown in the select list. - * // It defaults to the first string column in the foreign table. - * - * $quickForm->joinColumn(bookPeer::PUBLISHER_ID,UserPeer::UNAME); - * - * // default to all columns shown - * $quickForm->setColumnMode(HTML_QUICKFORM_PROPEL_ALL_COLUMNS); - * $quickForm->hideColumn('PASS'); - * - * // or default to no columns shown - * $quickForm->setColumnMode(HTML_QUICKFORM_PROPEL_NO_COLUMNS); - * $quickForm->showColumn('NAME'); // column name without table prefix. - * $quickForm->showColumn('UNAME'); - * $quickForm->showColumn('USER_INFO'); - * $quickForm->showColumn('EMAIL'); - * $quickForm->showColumn('FEMAIL'); - * $quickForm->showColumn('URL'); - * $quickForm->showColumn('PASS'); - * - * // generate the form - * $quickForm->build(); - * - * // after the form is build, it's possible to modify the generated elements - * $quickForm->getElement('NAME')->setSize(10); // manually tune this element - * - * if ($quickForm->validate()) { - * $quickForm->freeze(); - * - * // save the object we have editted - * $quickForm->save(); - * } else { - * $quickForm->toHtml(); // or any other QuickForm render option - * } - * - * TODO: map all creoleTypes to usefull formelements - * - * @author Rob Halff - * some improvements by Zoltan Nagy (sunshine@freemail.hu) - * @version $Rev: 1347 $ - * @copyright Copyright (c) 2005 Rob Halff: LGPL - See LICENCE - * @package propel.contrib - */ - -class HTML_QuickForm_Propel extends HTML_QuickForm { - - /** - * ID of the Propel Object. - * @var integer - * @access private - */ - private $id; - - /** - * Contains column visibility information. - * @var array - * @access private - */ - private $columnVisibility = array(); - - /** - * Contains titles of columns. - * @var array - * @access private - */ - private $columnTitle = array(); - - /** - * The Column visibility mode either. - * Possible values: - * - * HTML_QUICKFORM_PROPEL_ALL_COLUMNS - * HTML_QUICKFORM_PROPEL_NO_COLUMNS - * - * @var integer - * @access private - */ - private $columnMode; - - /** - * String containing the peerName. - * @var string - * @access private - */ - private $peerName; - - /** - * String containing the className of the propel Object. - * @var string - * @access private - */ - private $className; - - /** - * The Column objects. - * - * @var array - * @access private - */ - private $cols; - - /** - * The Object being operated on. - * @var object - * @access private - */ - private $obj; - - /** - * Seperator value. - * - * In case the option list will be build by multiple values - * This is the value these fields will be seperated with - * - * @var string - * @access private - */ - private $seperator = ' '; - - /** - * - * Not used yet. - * - * @var array - * @access private - */ - private $joinMap = array(); - - /** - * The default QuickForm rule type to use. - * Either server or client - * - * @var string - * @access private - */ - private $defaultRuleType = 'server'; - - - /** - * This is used in the QuickForm DateElement - * @var string - * @access private - */ - private $lang = 'en'; - - /** - * Rulemapping should cover all available propel rules - * - * @var array - * @access private - */ - private $ruleMapping = array( - 'mask'=>'regex', - 'maxLength'=>'maxlength', - 'minLength'=>'minlength', - 'maxValue'=>'maxvalue', - 'minValue'=>'minvalue', - 'required'=>'required', - 'validValues'=>'validvalues', - 'unique'=>'unique' - ); - - /** - * - * CreoleType to QuickForm element mapping - * - * @var array - * @access private - */ - private $typeMapping = array( - CreoleTypes::BOOLEAN =>'radio', - CreoleTypes::BIGINT =>'text', - CreoleTypes::SMALLINT =>'text', - CreoleTypes::TINYINT =>'text', - CreoleTypes::INTEGER =>'text', - CreoleTypes::NUMERIC =>'text', - CreoleTypes::DECIMAL =>'text', - CreoleTypes::REAL =>'text', - CreoleTypes::FLOAT =>'text', - CreoleTypes::DOUBLE =>'text', - CreoleTypes::CHAR =>'text', - CreoleTypes::VARCHAR =>'text', - CreoleTypes::LONGVARCHAR=>'textarea', - CreoleTypes::TEXT =>'textarea', - CreoleTypes::TIME =>'text', - CreoleTypes::TIMESTAMP =>'date', - CreoleTypes::DATE =>'date', - CreoleTypes::YEAR =>'text', - CreoleTypes::VARBINARY =>'text', - CreoleTypes::BLOB =>'text', - CreoleTypes::CLOB =>'text', - CreoleTypes::BINARY =>'text', - CreoleTypes::LONGVARBINARY=>'text', - CreoleTypes::ARR =>'text', - CreoleTypes::OTHER =>'text' - ); - - /** - * - * The Constructor - * - * Classname and id are specific to HTML_QuickForm_Propel - * - * The other parameters are needed to construct the parent QuickForm Class. - * - * @param string className - * @param string id - * @param string formName - * @param string method - * @param string action - * @param string target - * @param array attributes - * @param boolean trackSubmit - * - */ - public function __construct($className = null, $id = null, $formName='HTML_QuickForm_Propel', $method='post', $action='', $target='_self', $attributes=null, $trackSubmit = false) - { - $this->setClassName($className); - $this->setPeerName($className.'Peer'); // Is this always true ? - $this->setId($id); - parent::HTML_QuickForm($formName, $method, $action, $target, $attributes, $trackSubmit); - - // set the default column policy - $this->setColumnMode(HTML_QUICKFORM_PROPEL_ALL_COLUMNS); - } - - /** - * - * NOT IMPLEMENTED - * - * Allows for creating complex forms. - * Note that limit 1 will always be added to the criteria. - * Because we can only edit one record/row at a time. - * - * However we will be able to join tables in complex ways. - * - * @param Criteria - * - */ - public function setCriteria(Criteria $c) - { - $c->setLimit(1); - $this->criteria = $c; - } - - /** - * - * Set the action of this form - * - * @param string action - * - */ - public function setAction($action) - { - $attributes = array('action'=>$action); - $this->updateAttributes($attributes); - } - - /** - * - * Set method of this form, e.g. post or get - * - * @param string method - * - */ - public function setMethod($method) - { - $attributes = array('method'=>$method); - $this->updateAttributes($attributes); - } - - /** - * - * Set the target of this form - * - * @param string target - * - */ - public function setTarget($target) - { - $attributes = array('target'=>$target); - $this->updateAttributes($attributes); - } - - /** - * - * Set the id of the object we need to get - * - * @param string id - * - */ - public function setId($id) - { - $this->id = $id; - } - - /** - * - * Set the class - * - * @param string className - * - */ - public function setClassName($className) - { - $this->className = $className; - } - - /** - * - * Get the class name - * - * @return string className - * - */ - public function getClassName() - { - return $this->className; - } - - private function setPeerName($peerName) - { - $this->peerName = $peerName; - } - - /** - * - * Get the peer name - * - * @return string peerName - * - */ - public function getPeerName() - { - return $this->peerName; - } - - /** - * Build the form - * - * @return void - * - */ - public function build() - { - - if (!class_exists($this->peerName)) { - // some autoloading, dunno if it should belong here. - // or in the users autoload function - //$dbMap = call_user_func(array($this->peerName, 'getMapBuilder')); - // TODO: implement this. - } - - if (empty($this->id)) { - // create empty instance of this class - $this->obj = new $this->className(); - } else { - // find the object. - if (!$this->obj = call_user_func(array($this->peerName, 'retrieveByPK'), $this->id)) { - // for help me god.. what to do ? - throw new PropelException("HTML_QuickForm_Propel::build(): $this->peerName::retrieveByPK($this->id) failed."); - } - - } - - // note: getTableMap is protected by default. - // so do this handstand to get the tableMap - $mapBuilder = call_user_func(array($this->peerName, 'getMapBuilder')); - - // Note: $dbMap is re-used below to determine foreign table - $dbMap = $mapBuilder->getDatabaseMap(); - - // Get the column names for this table. - $this->cols = $dbMap->getTable(constant("$this->peerName::TABLE_NAME"))->getColumns(); - - // Do it the HTML_QuickForm way and use defaultValues - // instead of setValue() on every element. - // we have to first loop through the columns - foreach ($this->cols as $colName=>$col) { - - - $elementType = $this->typeMapping[$col->getCreoleType()]; - - if ($elementType == 'date') { - // null returns timestamp - $value = $this->obj->{'get'.$col->getPhpName()}(null); - } else { - - $value = $this->obj->{'get'.$col->getPhpName()}(); - - } - - $defaultValues[$colName] = $value; - } - - $this->setDefaults($defaultValues); - - foreach ($this->cols as $colName=>$col) { - - if ($this->isColumnHidden($colName)) { - continue; - } - - if ($col->isPrimaryKey()) { - // create a hidden field with primary key - if (!$this->checkColumn($colName, HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE)) { - $this->addElement('hidden', $col->getColumnName(), $col->getColumnName()); - continue; - } - } - - // element's title - $colTitle = $this->getColumnTitle($colName); - - if ($col->isForeignKey()) { - - // TODO: check if user created an optional method for populating the select form - // this populating of the select box is just some way to show joined items in a form. - // it could also be checkboxes, radio buttons or whatever kind of widget. - - $relatedTable = $dbMap->getTable($col->getRelatedTableName()); - $relatedCols = $relatedTable->getColumns(); - $relatedPeer = $relatedTable->getPhpName().'Peer'; - - if (is_callable($relatedPeer, 'doSelect')) { - - - // TODO: allow set this criteria. - $c = new Criteria; - - $relatedList = call_user_func(array($relatedPeer,'doSelect'), $c); - - $colConstant = constant($this->peerName.'::'.$colName); - //$relatedColConstant = constant($relatedPeer.'::'.$relatedCol->getColumnName()); - $relatedGetter = 'getPrimaryKey'; - - - // TODO: this needs to be array based, to support multiple foreign columns - if (isset($this->joinMap[$colConstant])) { - // translate to getter - $relatedColConstant = $this->joinMap[$colConstant]; - if (!$relatedTable->containsColumn($relatedColConstant)) { - // throw exception, there is no such column - throw new PropelException('HTML_QuickForm_Propel::build(): there is no column named '.$relatedTable->normalizeColName($relatedConstant).'in '.$relatedTable->getTableName().' while trying to build the select list'); - } - $nameColumn = $relatedTable->getColumn($relatedColConstant); - $relatedGetter = 'get'.$nameColumn->getPhpName(); - } else { - //auto detection - // determine the first string column - foreach ($relatedCols as $relatedCol) { - if ($relatedCol->getType() == 'string') { - $relatedGetter = 'get'.$relatedCol->getPhpName(); - break; - } - } - } - - - $selectList = array(); - - // TODO: not hardcoded here. - $selectList[null] = _('Please selection an option'); - - foreach ($relatedList as $relObj) { - $key = $relObj->getPrimaryKey(); - - if (false OR $yesWannaUseEntireObjectsToUseItInTemplate) { - // TODO: IMPLEMENT THIS. - $selectList[$key] = $relObj; - } elseif (false OR $forceSomeKindOfColumnToBeDisplayed) { - // TODO: IMPLEMENT THIS. - } else { - $selectList[$key] = $relObj->{$relatedGetter}(); - } - } - - if (count($selectList) > 1) { // value of 1 depends on select message being set. - $select =& $this->addElement('select', $colName, $colTitle, $selectList); - } else { - // what to do if no records exists in the foreign table ? - $this->addElement('static', $colName, $colTitle, _('No Records')); - } - - } - - // do some recursion ? - - } else { - - //TODO: the mapping is not so generic anymore (to many exceptions) - $elementType = $this->typeMapping[$col->getCreoleType()]; - - if ($col->getCreoleType() == CreoleTypes::BOOLEAN) { - // TODO: describe how to override these options. - $radio = array(); - $radio[] = HTML_QuickForm::createElement('radio', null, null, 'Yes', true); - $radio[] = HTML_QuickForm::createElement('radio', null, null, 'No', false); - $el = $this->addGroup($radio, $colName, $colName); - - - } else { - - $el = $this->addElement( - $elementType, - $colName, - $colTitle); - - if ($elementType == 'text') { - $el->setMaxLength($col->getSize()); - } - - if ($col->getCreoleType() == CreoleTypes::TIMESTAMP) { - - /* Option Info: - var $_options = array( - 'language' => 'en', - 'format' => 'dMY', - 'minYear' => 2001, - 'maxYear' => 2010, - 'addEmptyOption' => false, - 'emptyOptionValue' => '', - 'emptyOptionText' => ' ', - 'optionIncrement' => array('i' => 1, 's' => 1) - ); - */ - - // hmm, don't like it but there seems to be no public method - // to set an option afterwards - $el->_options['language'] = $this->lang; - // TODO: is the format always the same in propel ? - $el->_options['format'] = 'Y-F-d H:i:s'; - - } - - } - // add an html id to the element - $this->addElementId($el, $colName); - - //$el->setValue($value); - - // required rule for NOT NULL columns - if ($col->isNotNull()) { - // TODO: What error message should we use? - $this->addRule($colName, - $this->getColumnTitle($colName) . ' is required', - 'required'); - } - - if ($col->hasValidators()) { - - foreach ($col->getValidators() as $validatorMap) { - - $this->addRule($colName, - $validatorMap->getMessage(), - $this->ruleMapping[$validatorMap->getName()], - $validatorMap->getValue(), - $this->defaultRuleType - ); - - } - } - - } - } - - // should HTML_QuickForm_Propel add this ? - $this->addElement('submit', 'submit', 'Submit'); - - // do this for the developer, can't think of any case where this is unwanted. - $this->applyFilter('__ALL__', 'trim'); - - } - - /** - * - * Use it to change the locale used for the Date element - * - * @param string locale - * @return void - * - */ - public function setLang($lang) - { - $this->lang = $lang; - } - - /** - * - * Save the form. - * - * @return void - * - */ - public function save() - { - $this->copyToObj(); - $this->obj->save(); - } - - /** - * - * Copy form values to Obj. - * - * @return void - * - */ - public function copyToObj() - { - // TODO: check what process does, if we leave out anything important. - - if (!isset($this->cols)) { - // throw some error, form cannot be saved before it is build. - throw new PropelException('HTML_QuickForm_Propel::save(): form cannot be saved before it is build.'); - } - - foreach ($this->cols as $colName=>$col) { - - // Has the form got this element? - if ($this->isColumnHidden($colName)) - { - continue; - } - - $value = $this->getElementValue($colName); - if ($value instanceof HTML_QuickForm_Error) - { - // TODO: What should we do if an error has occured? - continue; - } - $elementType = $this->typeMapping[$col->getCreoleType()]; - - // quickform doesn't seem to give back a timestamp, so calculate the date manually. - if ($elementType == 'date') { - - $date = array( - 'D' => null, - 'l' => null, - 'd' => null, - 'M' => null, - 'm' => null, - 'F' => null, - 'Y' => null, - 'y' => null, - 'h' => null, - 'H' => null, - 'i' => null, - 's' => null, - 'a' => null, - 'A' => null - ); - - foreach ($value as $key=>$val) { - $date[$key] = $val[0]; - - } - - $value = mktime($date['h'], $date['m'], $date['s'], $date['M'], $date['d'], $date['Y']); - } - - $this->obj->{'set'.$col->getPhpName()}($value); - } - } - - /** - * - * Get the object we are operating on. - * - * @return object a propel object - * - */ - public function getObj() - { - return $this->obj; - } - - /** - * What to do if a delete button is added - * and the user clicks on it, after the object has been delete in save() - */ - public function onDelete() - { - - - } - - public function createDeleteButton() - { - return $this->addElement('submit', 'delete', 'Delete'); - } - - public function isColumnHidden($column) - { - if ($this->checkColumn($column, HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN) && $this->columnMode == HTML_QUICKFORM_PROPEL_ALL_COLUMNS) { - return true; - } - - if (!$this->checkColumn($column, HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE) && $this->columnMode == HTML_QUICKFORM_PROPEL_NO_COLUMNS) { - return true; - } - - return false; - } - - private function checkColumn($column, $state) - { - if (isset($this->columnVisibility[$column])) { - return ($this->columnVisibility[$column] == $state); - } else { - return false; - } - } - - /** - * - * Sets the default visibility mode - * - * This must be either: - * HTML_QUICKFORM_PROPEL_NO_COLUMNS or - * HTML_QUICKFORM_PROPEL_ALL_COLUMNS - * - * @param string $column column name - * @return void - * - */ - public function setColumnMode($mode) - { - - if ($mode != HTML_QUICKFORM_PROPEL_NO_COLUMNS && $mode != HTML_QUICKFORM_PROPEL_ALL_COLUMNS) { - - throw new PropelException('HTML_QuickForm_Propel::setColumnMode(): invalid mode passed.'); - - } - - $this->columnMode = $mode; - } - - /** - * - * Tell HTML_QuickForm_Propel it should hide this column - * It is now passed like ID instead of somePeer::ID - * The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID - * - * @param string $column column name - * @return void - * - */ - - public function hideColumn($column) - { - $this->columnVisibility[$column] = HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN; - } - - /** - * - * Tell HTML_QuickForm_Propel it should show this column - * - * It is now passed like ID instead of somePeer::ID - * The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID - * - * @param string $column column name - * @param string $title Title for the column, not required - * @return void - */ - public function showColumn($column, $title = NULL) - { - $this->columnVisibility[$column] = HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE; - if ($title !== NULL) - { - $this->setColumnTitle($column, $title); - } - } - - /** - * - * assign a title to the column - * - * @param string $column - * @param string $title - * @return void - */ - public function setColumnTitle($column, $title) - { - $this->columnTitles[$column] = $title; - } - - /** - * - * returns column's title - * - * @param string $column - * @return void - */ - public function getColumnTitle($column) - { - // TODO: check if $column exists - return (array_key_exists($column, $this->columnTitles)) - ? $this->columnTitles[$column] - : $column; - } - - /** - * - * Try to automatically join all relatedTables. - * NOT IMPLEMENTED - * - * @param boolean $bool - * @return void - */ - public function autoJoin($bool) - { - $this->autoJoin = $bool; - } - - /** - * Override this if you don't like the (strtolower) default - * - * @param HTML_QuickForm_Element $el - * @param string $colName - * @return void - */ - protected function addElementId($el, $colName) - { - $el->updateAttributes(array('id'=>strtolower($colName))); - } - - /** - * - * Set the default rule typef - * @param string $type - * @return void - * - */ - public function setDefaultRuleType($type) - { - $this->defaultRuleType = $type; - } - - /** - * - * UNFINISHED - * - * Probably it would be nice to be able to add this to the schema xml - * - * TODO: further implement multiple columns for the select list - * - * @var colName constant - * @var foreignColName mixed (constant/array of columnName constants) - * @var $seperator string Only used if foreignColName is an array - */ - - public function joinColumn($colName, $foreignColName, $seperator = null) - { - if (isset($seperator)) { - $this->seperator = $seperator; - } - $this->joinMap[$colName] = $foreignColName; - } - -} diff --git a/airtime_mvc/library/propel/contrib/pear/Structures_DataGrid_Propel/Propel.php b/airtime_mvc/library/propel/contrib/pear/Structures_DataGrid_Propel/Propel.php deleted file mode 100644 index fcbf8afee..000000000 --- a/airtime_mvc/library/propel/contrib/pear/Structures_DataGrid_Propel/Propel.php +++ /dev/null @@ -1,352 +0,0 @@ -. - */ - -require_once 'Structures/DataGrid.php'; - -define('STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS', 2); -define('STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS', 3); -define('STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE', 4); -define('STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN', 5); - -/** - * - * NOTE: Structures_DataGrid_Propel extends Structures_DataGrid, so all Datagrid functionality is available. - * - * A fictive example: - * // Propel and Propel project classes must be in the include_path - * - * // Propel Class name : Report - * $dg =& new Structures_DataGrid_Propel('Report'); - * - * // limit to 10 rows - * $c = new Criteria(); - * $c->setLimit(10); - * $dg->setCriteria($c); - * - * // choose what columns must be displayed - * $dg->setColumnMode(STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS); - * $dg->showColumn('ACTIVE'); - * $dg->showColumn('TITLE'); - * $dg->showColumn('ID'); - * - * // generate the datagrid - * $dg->build(); - * - * // add two columns to edit the row and checkbox for further operations - * $dg->addColumn(new Structures_DataGrid_Column('', null, null, array('width' => '4%'), null, 'printEditLink()')); - * $dg->addColumn(new Structures_DataGrid_Column('', null, null, array('width' => '1%'), null, 'printCheckbox()')); - * - * // Display the datagrid - * $dg->render(); - * - * @author Marc - * @version $Rev: 1347 $ - * @copyright Copyright (c) 2005 Marc: LGPL - See LICENCE - * @package propel.contrib - */ - -class Structures_DataGrid_Propel extends Structures_DataGrid { - - /** - * Contains column visibility information. - * @var array - * @access private - */ - private $columnVisibility = array(); - - /** - * The Column visibility mode. - * Possible values: - * - * STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS - * STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS - * - * @var integer - * @access private - */ - private $columnMode; - - /** - * String containing the peerName. - * @var string - * @access private - */ - private $peerName; - - /** - * String containing the className of the propel Object. - * @var string - * @access private - */ - private $className; - - /** - * Criteria of the Select query. - * @var criteria - * @access private - */ - private $criteria; - - /** - * List of primary keys - * @var array - * @access public - */ - public $primaryKeys; - - /** - * - * The Constructor - * - * Classname is specific to Structures_Datagrid_Propel - * - * The other parameters are needed to construct the parent Structures_DataGrid Class. - * - * @param string className - * @param string limit - * @param string render - * - */ - public function __construct($className = null, $limit = null, $render = DATAGRID_RENDER_HTML_TABLE) - { - - include_once $className.'.php'; - include_once $className.'Peer'.'.php'; - - $this->setClassName($className); - $this->setPeerName($className.'Peer'); // Is this always true ? - parent::Structures_DataGrid($limit,null,$render); - - // set the default column policy - $this->setColumnMode(STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS); - $this->criteria = new Criteria(); - } - - /** - * - * Set the criteria for select query - * - * @param Criteria c - * - */ - public function setCriteria(Criteria $c) - { - $this->criteria = $c; - } - - /** - * - * Set the class - * - * @param string className - * - */ - public function setClassName($className) - { - $this->className = $className; - } - - /** - * - * Get the class name - * - * @return string className - * - */ - public function getClassName() - { - return $this->className; - } - - private function setPeerName($peerName) - { - $this->peerName = $peerName; - } - - /** - * - * Get the peer name - * - * @return string peerName - * - */ - public function getPeerName() - { - return $this->peerName; - } - - /** - * - * Get the visibility of a column - * - * @return boolean true if column is set to hidden - * - */ - public function isColumnHidden($column) - { - if ($this->checkColumn($column, STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN) && $this->columnMode == STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) { - return true; - } - - if (!$this->checkColumn($column, STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE) && $this->columnMode == STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS) { - return true; - } - - return false; - } - - /** - * - * Check the state of a column - * - * @return boolean true if column is set to state - * - */ - private function checkColumn($column, $state) - { - if (isset($this->columnVisibility[$column])) { - return ($this->columnVisibility[$column] == $state); - } else { - return false; - } - } - - /** - * - * Sets the default visibility mode - * - * This must be either: - * STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS or - * STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS - * - * @param string $column column name - * @return void - * - */ - public function setColumnMode($mode) - { - - if ($mode != STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS && $mode != STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) { - throw new PropelException('STRUCTURES_DATAGRID_PROPEL::setColumnMode(): invalid mode passed.'); - } - - $this->columnMode = $mode; - } - - /** - * - * Tell Structures_Datagrid_Propel it should hide this column - * It is now passed like ID instead of somePeer::ID - * The latter is better, but the array_keys of the columns are - * in ID format and not somePeer::ID - * - * @param string $column column name - * @return void - * - */ - public function hideColumn($column) - { - $this->columnVisibility[$column] = STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN; - } - - /** - * - * Tell Structures_Datagrid_Propel it should show this column - * - * It is now passed like ID instead of somePeer::ID - * The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID - * - * @param string $column column name - * @return void - */ - public function showColumn($column) - { - $this->columnVisibility[$column] = STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE; - } - - /** - * - * Build the datagrid - * - * @return void - */ - public function build() - { - $mapBuilder = call_user_func(array($this->getPeerName(), 'getMapBuilder')); - $dbMap = $mapBuilder->getDatabaseMap(); - $cols = $dbMap->getTable(constant($this->getPeerName()."::TABLE_NAME"))->getColumns(); - $stmt = call_user_func(array( $this->getPeerName(), 'doSelectStmt'), $this->criteria); - - $dataset = array(); - $columns = array(); - $this->primaryKeys = array(); - $class = $this->getClassName(); - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { // use Creole ResultSet methods to iterate over resultset - $obj = new $class(); - $obj->hydrate($row); - - $row = array(); - foreach ($cols as $tmp_id => $col) - { - // save the PK in an array - if ($col->isPrimaryKey()) { - $this->primaryKeys[$col->getColumnName()] = $col->getColumnName(); - } - - $value = $obj->{'get'.$col->getPhpName()}(null); - // save the row value - - $row[$col->getColumnName()] = $value; - // save the list of propel header column name - $columns[$col->getColumnName()] = $col->getColumnName(); - - } - // add the row to dataset - $dataset[] = $row; - } - - $this->bind($dataset); - - if ($this->columnMode == STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) { - foreach ($columns as $tmp_id => $column) { - - if (!$this->isColumnHidden($column)) { - - $this->addColumn(new Structures_DataGrid_Column($column, $column, $column, null)); - } - } - } else { - - foreach ($this->columnVisibility as $column => $visibility) { - - if (!$this->isColumnHidden($column)) { - $this->addColumn(new Structures_DataGrid_Column($column, $column, $column, null)); - } - } - } - - $this->renderer->setTableHeaderAttributes(array('class' => 'title')); - $this->renderer->setTableAttribute('class', 'list'); - $this->renderer->sortIconASC = '?'; - $this->renderer->sortIconDESC = '?'; - } - -} diff --git a/airtime_mvc/library/propel/docs/behavior/aggregate_column.txt b/airtime_mvc/library/propel/docs/behavior/aggregate_column.txt deleted file mode 100644 index e071425a7..000000000 --- a/airtime_mvc/library/propel/docs/behavior/aggregate_column.txt +++ /dev/null @@ -1,130 +0,0 @@ -= Aggregate Column Behavior = - -The `aggregate_column` behavior keeps a column updated using an aggregate function executed on a related table. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `aggregate_column` behavior to a table. You must provide parameters for the aggregate column `name`, the foreign table name, and the aggegate `expression`. For instance, to add an aggregate column keeping the comment count in a `post` table: - -{{{ -#!xml - - - - - - - - -
- - - - - - -
-}}} - -Rebuild your model, and insert the table creation sql again. The model now has an additional `nb_comments` column, of type `integer` by default. And each time an record from the foreign table is added, modified, or removed, the aggregate column is updated: - -{{{ -#!php -setTitle('How Is Life On Earth?'); -$post->save(); -echo $post->getNbComments(); // 0 -$comment1 = new Comment(); -$comment1->setPost($post); -$comment1->save(); -echo $post->getNbComments(); // 1 -$comment2 = new Comment(); -$comment2->setPost($post); -$comment2->save(); -echo $post->getNbComments(); // 2 -$comment2->delete(); -echo $post->getNbComments(); // 1 -}}} - -The aggregate column is also kept up to date when related records get modified through a Query object: - -{{{ -#!php -filterByPost($post) - ->delete(): -echo $post->getNbComments(); // 0 -}}} - -== Customizing The Aggregate Calculation == - -Any aggregate function can be used on any of the foreign columns. For instance, you can use the `aggregate_column` behavior to keep the latest update date of the related comments, or the total votes on the comments. You can even keep several aggregate columns in a single table: - -{{{ -#!xml - - - - - - - - - - - - - - - - - - -
- - - - - - - - -
-}}} - -The behavior adds a `computeXXX()` method to the `Post` class to compute the value of the aggregate function. This method, called each time records are modified in the related `comment` table, is the translation of the behavior settings into a SQL query: - -{{{ -#!php -prepare('SELECT COUNT(id) FROM `comment` WHERE comment.POST_ID = :p1'); - $stmt->bindValue(':p1', $this->getId()); - $stmt->execute(); - return $stmt->fetchColumn(); -} -}}} - -You can override this method in the model class to customize the aggregate column calculation. - -== Customizing The Aggregate Column == - -By default, the behavior adds one columns to the model. If this column is already described in the schema, the behavior detects it and doesn't add it a second time. This can be useful if you need to use a custom `type` or `phpName` for the aggregate column: - -{{{ -#!xml - - - - - - - - - -
-}}} diff --git a/airtime_mvc/library/propel/docs/behavior/alternative_coding_standards.txt b/airtime_mvc/library/propel/docs/behavior/alternative_coding_standards.txt deleted file mode 100644 index bc7462357..000000000 --- a/airtime_mvc/library/propel/docs/behavior/alternative_coding_standards.txt +++ /dev/null @@ -1,89 +0,0 @@ -= Alternative Coding Standards Behavior = - -The `alternative_coding_standards` behavior changes the coding standards of the model classes generated by Propel to match your own coding style. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `alternative_coding_standards` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, and you're ready to go. The code of the model classes now uses an alternative set of coding standards: - -{{{ -#!php -title !== $v) - { - $this->title = $v; - $this->modifiedColumns[] = BookPeer::TITLE; - } - - return $this; - } - -// instead of - - /** - * Set the value of [title] column. - * - * @param string $v new value - * @return Table4 The current object (for fluent API support) - */ - public function setTitle($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->title !== $v) { - $this->title = $v; - $this->modifiedColumns[] = BookPeer::TITLE; - } - - return $this; - } // setTitle() -}}} - -The behavior replaces tabulations by whitespace (2 spaces by default), places opening brackets on newlines, removes closing brackets comments, and can even strip every comments in the generated classes if you wish. - -== Parameters == - -Each of the new coding style rules has corresponding parameter in the behavior description. Here is the default configuration: - -{{{ -#!xml - - - - - - - - - - -
-}}} - -You can change these settings to better match your own coding styles. diff --git a/airtime_mvc/library/propel/docs/behavior/auto_add_pk.txt b/airtime_mvc/library/propel/docs/behavior/auto_add_pk.txt deleted file mode 100644 index 214ddf020..000000000 --- a/airtime_mvc/library/propel/docs/behavior/auto_add_pk.txt +++ /dev/null @@ -1,73 +0,0 @@ -= AutoAddPk Behavior = - -The `auto_add_pk` behavior adds a primary key columns to the tables that don't have one. Using this behavior allows you to omit the declaration of primary keys in your tables. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `auto_add_pk` behavior to a table: -{{{ -#!xml - - - -
-}}} - -Rebuild your model, and insert the table creation sql. You will notice that the `book` table has two columns and not just one. The behavior added an `id` column, of type integer and autoincremented. This column can be used as any other column: - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -echo $b->getId(); // 1 -}}} - -This behavior is more powerful if you add it to the database instead of a table. That way, it will alter all tables not defining a primary key column - and leave the others unchanged. - -{{{ -#!xml - - - - -
-
-}}} - -You can even enable it for all your database by adding it to the default behaviors in your `build.properties` file: - -{{{ -#!ini -propel.behavior.default = auto_add_pk -}}} - -== Parameters == - -By default, the behavior adds a column named `id` to the table if the table has no primary key. You can customize all the attributes of the added column by setting corresponding parameters in the behavior definition: - -{{{ -#!xml - - - - - - - -
-
-}}} - -Once you regenerate your model, the column is now named differently: - -{{{ -#!php -setTitle('War And Peace'); -$b->setIdentifier(1); -$b->save(); -echo $b->getIdentifier(); // 1 -}}} diff --git a/airtime_mvc/library/propel/docs/behavior/nested_set.txt b/airtime_mvc/library/propel/docs/behavior/nested_set.txt deleted file mode 100644 index ad0f45077..000000000 --- a/airtime_mvc/library/propel/docs/behavior/nested_set.txt +++ /dev/null @@ -1,370 +0,0 @@ -= NestedSet Behavior = - -The `nested_set` behavior allows a model to become a tree structure, and provides numerous methods to traverse the tree in an efficient way. - -Many applications need to store hierarchical data in the model. For instance, a forum stores a tree of messages for each discussion. A CMS sees sections and subsections as a navigation tree. In a business organization chart, each person is a leaf of the organization tree. [http://en.wikipedia.org/wiki/Nested_set_model Nested sets] are the best way to store such hierachical data in a relational database and manipulate it. The name "nested sets" describes the algorithm used to store the position of a model in the tree ; it is also known as "modified preorder tree traversal". - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `nested_set` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has the ability to be inserted into a tree structure, as follows: - -{{{ -#!php -setTitle('Home'); -$s1->makeRoot(); // make this node the root of the tree -$s1->save(); -$s2 = new Section(); -$s2->setTitle('World'); -$s2->insertAsFirstChildOf($s1); // insert the node in the tree -$s2->save(); -$s3 = new Section(); -$s3->setTitle('Europe'); -$s3->insertAsFirstChildOf($s2); // insert the node in the tree -$s3->save() -$s4 = new Section(); -$s4->setTitle('Business'); -$s4->insertAsNextSiblingOf($s2); // insert the node in the tree -$s4->save(); -/* The sections are now stored in the database as a tree: - $s1:Home - | \ -$s2:World $s4:Business - | -$s3:Europe -*/ -}}} - -You can continue to insert new nodes as children or siblings of existing nodes, using any of the `insertAsFirstChildOf()`, `insertAsLastChildOf()`, `insertAsPrevSiblingOf()`, and `insertAsNextSiblingOf()` methods. - -Once you have built a tree, you can traverse it using any of the numerous methods the `nested_set` behavior adds to the query and model objects. For instance: - -{{{ -#!php -findRoot(); // $s1 -$worldNode = $rootNode->getFirstChild(); // $s2 -$businessNode = $worldNode->getNextSibling(); // $s4 -$firstLevelSections = $rootNode->getChildren(); // array($s2, $s4) -$allSections = $rootNode->getDescendants(); // array($s2, $s3, $s4) -// you can also chain the methods -$europeNode = $rootNode->getLastChild()->getPrevSibling()->getFirstChild(); // $s3 -$path = $europeNode->getAncestors(); // array($s1, $s2) -}}} - -The nodes returned by these methods are regular Propel model objects, with access to the properties and related models. The `nested_set` behavior also adds inspection methods to nodes: - -{{{ -#!php -isRoot(); // false -echo $s2->isLeaf(); // false -echo $s2->getLevel(); // 1 -echo $s2->hasChildren(); // true -echo $s2->countChildren(); // 1 -echo $s2->hasSiblings(); // true -}}} - -Each of the traversal and inspection methods result in a single database query, whatever the position of the node in the tree. This is because the information about the node position in the tree is stored in three columns of the model, named `tree_left`, `tree_left`, and `tree_level`. The value given to these columns is determined by the nested set algorithm, and it makes read queries much more effective than trees using a simple `parent_id` foreign key. - -== Manipulating Nodes == - -You can move a node - and its subtree - across the tree using any of the `moveToFirstChildOf()`, `moveToLastChildOf()`, `moveToPrevSiblingOf()`, and `moveToLastSiblingOf()` methods. These operations are immediate and don't require that you save the model afterwards: - -{{{ -#!php -moveToFirstChildOf($s4); -/* The tree is modified as follows: -$s1:Home - | -$s4:Business - | -$s2:World - | -$s3:Europe -*/ -// now move the "Europe" section directly under root, after "Business" -$s2->moveToFirstChildOf($s4); -/* The tree is modified as follows: - $s1:Home - | \ -$s4:Business $s3:Europe - | -$s2:World -*/ -}}} - -You can delete the descendants of a node using `deleteDescendants()`: - -{{{ -#!php -deleteDescendants($s4); -/* The tree is modified as follows: - $s1:Home - | \ -$s4:Business $s3:Europe -*/ -}}} - -If you `delete()` a node, all its descendants are deleted in cascade. To avoid accidental deletion of an entire tree, calling `delete()` on a root node throws an exception. Use the `delete()` Query method instead to delete an entire tree. - -== Filtering Results == - -The `nested_set` behavior adds numerous methods to the generated Query object. You can use these methods to build more complex queries. For instance, to get all the children of the root node ordered by title, build a Query as follows: - -{{{ -#!php -childrenOf($rootNode) - ->orderByTitle() - ->find(); -}}} - -Alternatively, if you already have an existing query method, you can pass it to the model object's methods to filter the results: - -{{{ -#!php -orderByTitle(); -$children = $rootNode->getChildren($orderQuery); -}}} - -== Multiple Trees == - -When you need to store several trees for a single model - for instance, several threads of posts in a forum - use a ''scope'' for each tree. This requires that you enable scope tree support in the behavior definition by setting the `use_scope` parameter to `true`: - -{{{ -#!xml - - - - - - - - - - -
-}}} - -Now, after rebuilding your model, you can have as many trees as required: - -{{{ -#!php -findPk(123); -$firstPost = PostQuery::create()->findRoot($thread->getId()); // first message of the discussion -$discussion = PostQuery::create()->findTree(thread->getId()); // all messages of the discussion -PostQuery::create()->inTree($thread->getId())->delete(); // delete an entire discussion -$firstPostOfEveryDiscussion = PostQuery::create()->findRoots(); -}}} - -== Using a RecursiveIterator == - -An alternative way to browse a tree structure extensively is to use a [http://php.net/RecursiveIterator RecursiveIterator]. The `nested_set` behavior provides an easy way to retrieve such an iterator from a node, and to parse the entire branch in a single iteration. - -For instance, to display an entire tree structure, you can use the following code: - -{{{ -#!php -findRoot(); -foreach ($root->getIterator() as $node) { - echo str_repeat(' ', $node->getLevel()) . $node->getTitle() . "\n"; -} -}}} - -The iterator parses the tree in a recursive way by retrieving the children of every node. This can be quite effective on very large trees, since the iterator hydrates only a few objects at a time. - -Beware, though, that the iterator executes many queries to parse a tree. On smaller trees, prefer the `getBranch()` method to execute only one query, and hydrate all records at once: - -{{{ -#!php -findRoot(); -foreach ($root->getBranch() as $node) { - echo str_repeat(' ', $node->getLevel()) . $node->getTitle() . "\n"; -} -}}} - -== Parameters == - -By default, the behavior adds three columns to the model - four if you use the scope feature. You can use custom names for the nested sets columns. The following schema illustrates a complete customization of the behavior: - -{{{ -#!xml - - - - - - - - - - - - - - - - - -
-}}} - -Whatever name you give to your columns, the `nested_sets` behavior always adds the following proxy methods, which are mapped to the correct column: - -{{{ -#!php -getLeftValue(); // returns $post->lft -$post->setLeftValue($left); -$post->getRightValue(); // returns $post->rgt -$post->setRightValue($right); -$post->getLevel(); // returns $post->lvl -$post->setLevel($level); -$post->getScopeValue(); // returns $post->thread_id -$post->setScopeValue($scope); -}}} - -If your application used the old nested sets builder from Propel 1.4, you can enable the `method_proxies` parameter so that the behavior generates method proxies for the methods that used a different name (e.g. `createRoot()` for `makeRoot()`, `retrieveFirstChild()` for `getFirstChild()`, etc. - -{{{ -#!xml - - - - - - -
-}}} - -== Complete API == - -Here is a list of the methods added by the behavior to the model objects: - -{{{ -#!php -` tag to add the `query_cache` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -After you rebuild your model, all the queries on this object can now be cached. To trigger the query cache on a particular query, just give it a query key using the `setQueryKey()` method. The key is a unique identifier that you can choose, later used for cache lookups: - -{{{ -#!php -setQueryKey('search book by title') - ->filterByTitle($title) - ->findOne(); -}}} - -The first time Propel executes the termination method, it computes the SQL translation of the Query object and stores it into a cache backend (APC by default). Next time you run the same query, it executes faster, even with different parameters: - -{{{ -#!php -setQueryKey('search book by title') - ->filterByTitle($title) - ->findOne(); -}}} - -'''Tip''': The more complex the query, the greater the boost you get from the query cache behavior. - -== Parameters == - -You can change the cache backend and the cache lifetime (in seconds) by setting the `backend` and `lifetime` parameters: - -{{{ -#!xml - - - - - - - -
-}}} - -To implement a custom cache backend, just override the generated `cacheContains()`, `cacheFetch()` and `cacheStore()` methods in the Query object. For instance, to implement query cache using Zend_Cache and memcached, try the following: - -{{{ -#!php -getCacheBackend()->test($key); - } - - public function cacheFetch($key) - { - return $this->getCacheBackend()->load($key); - } - - public function cacheStore($key, $value) - { - return $this->getCacheBackend()->save($key, $value); - } - - protected function getCacheBackend() - { - if (self::$cacheBackend === null) { - $frontendOptions = array( - 'lifetime' => 7200, - 'automatic_serialization' => true - ); - $backendOptions = array( - 'servers' => array( - array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => true - ) - ) - ); - self::$cacheBackend = Zend_Cache::factory('Core', 'Memcached', $frontendOptions, $backendOptions); - } - - return self::$cacheBackend; - } -} -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/behavior/sluggable.txt b/airtime_mvc/library/propel/docs/behavior/sluggable.txt deleted file mode 100644 index beb454a16..000000000 --- a/airtime_mvc/library/propel/docs/behavior/sluggable.txt +++ /dev/null @@ -1,135 +0,0 @@ -= Sluggable Behavior = - -The `sluggable` behavior allows a model to offer a human readable identifier that can be used for search engine friendly URLs. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `sluggable` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has an additional getter for its slug, which is automatically set before the object is saved: - -{{{ -#!php -setTitle('Hello, World!'); -$p1->save(); -echo $p1->getSlug(); // 'hello-world' -}}} - -By default, the behavior uses the string representation of the object to build the slug. In the example above, the `title` column is defined as `primaryString`, so the slug uses this column as a base string. The string is then cleaned up in order to allow it to appear in a URL. In the process, blanks and special characters are replaced by a dash, and the string is lowercased. - -'''Tip''': The slug is unique by design. That means that if you create a new object and that the behavior calculates a slug that already exists, the string is modified to be unique: - -{{{ -#!php -setTitle('Hello, World!'); -$p2->save(); -echo $p2->getSlug(); // 'hello-world-1' -}}} - -The generated model query offers a `findOneBySlug()` method to easily retrieve a model object based on its slug: - -{{{ -#!php -findOneBySlug('hello-world'); -}}} - -== Parameters == - -By default, the behavior adds one columns to the model. If this column is already described in the schema, the behavior detects it and doesn't add it a second time. The behavior parameters allow you to use custom patterns for the slug composition. The following schema illustrates a complete customization of the behavior: - -{{{ -#!xml - - - - - - - - - - - - -
-}}} - -Whatever `slug_column` name you choose, the `sluggable` behavior always adds the following proxy methods, which are mapped to the correct column: - -{{{ -#!php -getSlug(); // returns $post->url -$post->setSlug($slug); // $post->url = $slug -}}} - -The `slug_pattern` parameter is the rule used to build the raw slug based on the object properties. Any substring enclosed between brackets '{}' is turned into a getter, so the `Post` class generates slugs as follows: - -{{{ -#!php -getTitle(); -} -}}} - -Incidentally, that means that you can use names that don't match a real column phpName, as long as your model provides a getter for it. - -The `replace_pattern` parameter is a regular expression that shows all the characters that will end up replaced by the `replacement` parameter. In the above example, special characters like '!' or ':' are replaced by '-', but not letters, digits, nor '/'. - -The `separator` parameter is the character that separates the slug from the incremental index added in case of non-unicity. Set as '/', it makes `Post` objects sharing the same title have the following slugs: - -{{{ -'posts/hello-world' -'posts/hello-world/1' -'posts/hello-world/2' -... -}}} - -A `permanent` slug is not automatically updated when the fields that constitute it change. This is useful when the slug serves as a permalink, that should work even when the model object properties change. Note that you can still manually change the slug in a model using the `permanent` setting by calling `setSlug()`; - -== Further Customization == - -The slug is generated by the object when it is saved, via the `createSlug()` method. This method does several operations on a simple string: - -{{{ -#!php -createRawSlug(); - // truncate the slug to accomodate the size of the slug column - $slug = $this->limitSlugSize($slug); - // add an incremental index to make sure the slug is unique - $slug = $this->makeSlugUnique($slug); - - return $slug; -} - -protected function createRawSlug() -{ - // here comes the string composition code, generated according to `slug_pattern` - $slug = 'posts/' . $this->cleanupSlugPart($this->getTitle()); - // cleanupSlugPart() cleans up the slug part - // based on the `replace_pattern` and `replacement` parameters - - return $slug; -} -}}} - -You can override any of these methods in your model class, in order to implement a custom slug logic. diff --git a/airtime_mvc/library/propel/docs/behavior/soft_delete.txt b/airtime_mvc/library/propel/docs/behavior/soft_delete.txt deleted file mode 100644 index 0105edbf1..000000000 --- a/airtime_mvc/library/propel/docs/behavior/soft_delete.txt +++ /dev/null @@ -1,116 +0,0 @@ -= SoftDelete Behavior = - -The `soft_delete` behavior overrides the deletion methods of a model object to make them 'hide' the deleted rows but keep them in the database. Deleted objects still don't show up on select queries, but they can be retrieved or undeleted when necessary. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `soft_delete` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has one new column, `deleted_at`, that stores the deletion date. Select queries don't return the deleted objects: - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -$b->delete(); -echo $b->isDeleted(); // false -echo $b->getDeletedAt(); // 2009-10-02 18:14:23 -$books = BookQuery::create()->find(); // empty collection -}}} - -Behind the curtain, the behavior adds a condition to every SELECT query to return only records where the `deleted_at` column is null. That's why the deleted objects don't appear anymore upon selection. - -You can turn off the query alteration globally by calling the static method `disableSoftDelete()` on the related Query object: - -{{{ -#!php -find(); -$book = $books[0]; -echo $book->getTitle(); // 'War And Peace' -}}} - -Note that `find()` and other selection methods automatically re-enable the `soft_delete` filter. You can also enable it manually by calling the `enableSoftDelete()` method on Peer objects. - -If you want to recover a deleted object, use the `unDelete()` method: - -{{{ -#!php -unDelete(); -$books = BookQuery::create()->find(); -$book = $books[0]; -echo $book->getTitle(); // 'War And Peace' -}}} - -If you want to force the real deletion of an object, call the `forceDelete()` method: - -{{{ -#!php -forceDelete(); -echo $book->isDeleted(); // true -$books = BookQuery::create()->find(); // empty collection -}}} - -The query methods `delete()` and `deleteAll()` also perform a soft deletion, unless you disable the behavior on the peer class: - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); - -BookQuery::create()->delete($b); -$books = BookQuery::create()->find(); // empty collection -// the rows look deleted, but they are still there -BookQuery::disableSoftDelete(); -$books = BookQuery::create()->find(); -$book = $books[0]; -echo $book->getTitle(); // 'War And Peace' - -// To perform a true deletion, disable the softDelete feature -BookQuery::disableSoftDelete(); -BookQuery::create()->delete(); -// Alternatively, use forceDelete() -BookQuery::create()->forceDelete(); -}}} - -== Parameters == - -You can change the name of the column added by the behavior by setting the `deleted_column` parameter: - -{{{ -#!xml - - - - - - - -
-}}} - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -$b->delete(); -echo $b->getMyDeletionDate(); // 2009-10-02 18:14:23 -$books = BookQuery::create()->find(); // empty collection -}}} diff --git a/airtime_mvc/library/propel/docs/behavior/sortable.txt b/airtime_mvc/library/propel/docs/behavior/sortable.txt deleted file mode 100644 index b45c12843..000000000 --- a/airtime_mvc/library/propel/docs/behavior/sortable.txt +++ /dev/null @@ -1,285 +0,0 @@ -= Sortable Behavior = - -The `sortable` behavior allows a model to become an ordered list, and provides numerous methods to traverse this list in an efficient way. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `sortable` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has the ability to be inserted into an ordered list, as follows: - -{{{ -#!php -setTitle('Wash the dishes'); -$t1->save(); -echo $t1->getRank(); // 1, the first rank to be given (not 0) -$t2 = new Task(); -$t2->setTitle('Do the laundry'); -$t2->save(); -echo $t2->getRank(); // 2 -$t3 = new Task(); -$t3->setTitle('Rest a little'); -$t3->save() -echo $t3->getRank(); // 3 -}}} - -As long as you save new objects, Propel gives them the first available rank in the list. - -Once you have built an ordered list, you can traverse it using any of the methods added by the `sortable` behavior. For instance: - -{{{ -#!php -findOneByRank(1); // $t1 -$secondTask = $firstTask->getNext(); // $t2 -$lastTask = $secondTask->getNext(); // $t3 -$secondTask = $lastTask->getPrevious(); // $t2 - -$allTasks = TaskQuery::create()->findList(); -// => collection($t1, $t2, $t3) -$allTasksInReverseOrder = TaskQuery::create()->orderByRank('desc')->find(); -// => collection($t3, $t2, $t2) -}}} - -The results returned by these methods are regular Propel model objects, with access to the properties and related models. The `sortable` behavior also adds inspection methods to objects: - -{{{ -#!php -isFirst(); // false -echo $t2->isLast(); // false -echo $t2->getRank(); // 2 -}}} - -== Manipulating Objects In A List == - -You can move an object in the list using any of the `moveUp()`, `moveDown()`, `moveToTop()`, `moveToBottom()`, `moveToRank()`, and `swapWith()` methods. These operations are immediate and don't require that you save the model afterwards: - -{{{ -#!php -moveToTop(); -// The list is now 1 - Do the laundry, 2 - Wash the dishes, 3 - Rest a little -$t2->moveToBottom(); -// The list is now 1 - Wash the dishes, 2 - Rest a little, 3 - Do the laundry -$t2->moveUp(); -// The list is 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little -$t2->swapWith($t1); -// The list is now 1 - Do the laundry, 2 - Wash the dishes, 3 - Rest a little -$t2->moveToRank(3); -// The list is now 1 - Wash the dishes, 2 - Rest a little, 3 - Do the laundry -$t2->moveToRank(2); -}}} - -By default, new objects are added at the bottom of the list. But you can also insert them at a specific position, using any of the `insertAtTop(), `insertAtBottom()`, and `insertAtRank()` methods. Note that the `insertAtXXX` methods don't save the object: - -{{{ -#!php -setTitle('Clean windows'); -$t4->insertAtRank(2); -$t4->save(); -// The list is now 1 - Wash the dishes, 2 - Clean Windows, 3 - Do the laundry, 4 - Rest a little -}}} - -Whenever you `delete()` an object, the ranks are rearranged to fill the gap: - -{{{ -#!php -delete(); -// The list is now 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little -}}} - -'''Tip''': You can remove an object from the list without necessarily deleting it by calling `removeFromList()`. Don't forget to `save()` it afterwards so that the other objects in the lists are rearranged to fill the gap. - -== Multiple Lists == - -When you need to store several lists for a single model - for instance, one task list for each user - use a ''scope'' for each list. This requires that you enable scope support in the behavior definition by setting the `use_scope` parameter to `true`: - -{{{ -#!xml - - - - - - - - - - - -
-}}} - -Now, after rebuilding your model, you can have as many lists as required: - -{{{ -#!php -setTitle('Wash the dishes'); -$t1->setUser($paul); -$t1->save(); -echo $t1->getRank(); // 1 -$t2 = new Task(); -$t2->setTitle('Do the laundry'); -$t2->setUser($paul); -$t2->save(); -echo $t2->getRank(); // 2 -$t3 = new Task(); -$t3->setTitle('Rest a little'); -$t3->setUser($john); -$t3->save() -echo $t3->getRank(); // 1, because John has his own task list -}}} - -The generated methods now accept a `$scope` parameter to restrict the query to a given scope: - -{{{ -#!php -findOneByRank($rank = 1, $scope = $paul->getId()); // $t1 -$lastPaulTask = $firstTask->getNext(); // $t2 -$firstJohnTask = TaskPeer::create()->findOneByRank($rank = 1, $scope = $john->getId()); // $t1 -}}} - -Models using the sortable behavior with scope benefit from one additional Query methods named `inList()`: - -{{{ -#!php -inList($scope = $paul->getId())->find(); -}}} - -== Parameters == - -By default, the behavior adds one columns to the model - two if you use the scope feature. If these columns are already described in the schema, the behavior detects it and doesn't add them a second time. The behavior parameters allow you to use custom names for the sortable columns. The following schema illustrates a complete customization of the behavior: - -{{{ -#!xml - - - - - - - - - - - - - -
-}}} - -Whatever name you give to your columns, the `sortable` behavior always adds the following proxy methods, which are mapped to the correct column: - -{{{ -#!php -getRank(); // returns $task->my_rank_column -$task->setRank($rank); -$task->getScopeValue(); // returns $task->user_id -$task->setScopeValue($scope); -}}} - -The same happens for the generated Query object: - -{{{ -#!php -filterByRank(); // proxies to filterByMyRankColumn() -$query = TaskQuery::create()->orderByRank(); // proxies to orderByMyRankColumn() -$tasks = TaskQuery::create()->findOneByRank(); // proxies to findOneByMyRankColumn() -}}} - -'''Tip''': The behavior adds columns but no index. Depending on your table structure, you might want to add a column index by hand to speed up queries on sorted lists. - -== Complete API == - -Here is a list of the methods added by the behavior to the model objects: - -{{{ -#!php - $rank associative array -// only for behavior with use_scope -array inList($scope) -}}} - -The behavior also adds a few methods to the Peer classes: - -{{{ -#!php - $rank associative array -// only for behavior with use_scope -array retrieveList($scope) -int countList($scope) -int deleteList($scope) -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/behavior/timestampable.txt b/airtime_mvc/library/propel/docs/behavior/timestampable.txt deleted file mode 100644 index 146b694e9..000000000 --- a/airtime_mvc/library/propel/docs/behavior/timestampable.txt +++ /dev/null @@ -1,92 +0,0 @@ -= Timestampable Behavior = - -The `timestampable` behavior allows you to keep track of the date of creation and last update of your model objects. - -== Basic Usage == - -In the `schema.xml`, use the `` tag to add the `timestampable` behavior to a table: -{{{ -#!xml - - - - -
-}}} - -Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has two new columns, `created_at` and `updated_at`, that store a timestamp automatically updated on save: - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -echo $b->getCreatedAt(); // 2009-10-02 18:14:23 -echo $b->getUpdatedAt(); // 2009-10-02 18:14:23 -$b->setTitle('Anna Karenina'); -$b->save(); -echo $b->getCreatedAt(); // 2009-10-02 18:14:23 -echo $b->getUpdatedAt(); // 2009-10-02 18:14:25 -}}} - -The object query also has specific methods to retrieve recent objects and order them according to their update date: - -{{{ -#!php -recentlyUpdated() // adds a minimum value for the update date - ->lastUpdatedFirst() // orders the results by descending update date - ->find(); -}}} - -You can use any of the following methods in the object query: - -{{{ -#!php - - - - - - - - - - -}}} - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -echo $b->getMyCreateDate(); // 2009-10-02 18:14:23 -echo $b->getMyUpdateDate(); // 2009-10-02 18:14:23 -$b->setTitle('Anna Karenina'); -$b->save(); -echo $b->getMyCreateDate(); // 2009-10-02 18:14:23 -echo $b->getMyUpdateDate(); // 2009-10-02 18:14:25 -}}} diff --git a/airtime_mvc/library/propel/docs/build.xml b/airtime_mvc/library/propel/docs/build.xml deleted file mode 100644 index cc876c4b4..000000000 --- a/airtime_mvc/library/propel/docs/build.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/docs/cookbook/Add-Custom-SQL.txt b/airtime_mvc/library/propel/docs/cookbook/Add-Custom-SQL.txt deleted file mode 100644 index fd672f7ea..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Add-Custom-SQL.txt +++ /dev/null @@ -1,34 +0,0 @@ -= Adding Additional SQL Files = - -In many cases you may wish to have the ''insert-sql'' task perform additional SQL operations (e.g. add views, stored procedures, triggers, sample data, etc.). Rather than have to run additional SQL statements yourself every time you re-build your object model, you can have the Propel generator do this for you. - -== 1. Create the SQL DDL files == - -Create any additional SQL files that you want executed against the database (after the base ''schema.sql'' file is applied). - -For example, if we wanted to add a default value to a column that was unsupported in the schema (e.g. where value is a SQL function): - -{{{ -#!sql --- (for postgres) -ALTER TABLE my_table ALTER COLUMN my_column SET DEFAULT CURRENT_TIMESTAMP; -}}} - -Now we save that as '''my_column-default.sql''' in the same directory as the generated '''schema.sql''' file (usually in projectdir/build/sql/). - -== 2. Tell Propel Generator about the new file == - -In that same directory (where your '''schema.sql''' is located), there is a '''sqldb.map''' file which contains a mapping of SQL DDL files to the database that they should be executed against. After running the propel generator, you will probably have a single entry in that file that looks like: - -{{{ -schema.sql=your-db-name -}}} - -We want to simply add the new file we created to this file (future builds will preserve anything you add to this file). When we're done, the file will look like this: - -{{{ -schema.sql=your-db-name -my_column-default.sql=your-db-name -}}} - -Now when you execute the ''insert-sql'' Propel generator target, the '''my_column-default.sql''' file will be executed against the ''your-db-name'' database. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Copying-Objects.txt b/airtime_mvc/library/propel/docs/cookbook/Copying-Objects.txt deleted file mode 100644 index 5a67eaa4f..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Copying-Objects.txt +++ /dev/null @@ -1,47 +0,0 @@ -= Copying Persisted Objects = - -Propel provides the {{{copy()}}} method to perform copies of mapped row in the database. Note that Propel does '''not''' override the {{{__clone()}}} method; this allows you to create local duplicates of objects that map to the same persisted database row (should you need to do this). - -The {{{copy()}}} method by default performs shallow copies, meaning that any foreign key references will remain the same. - -{{{ -#!php -setFirstName("Aldous"); -$a->setLastName("Huxley"); - -$p = new Publisher(); -$p->setName("Harper"); - -$b = new Book(); -$b->setTitle("Brave New World"); -$b->setPublisher($p); -$b->setAuthor($a); - -$b->save(); // so that auto-increment IDs are created - -$bcopy = $b->copy(); -var_export($bcopy->getId() == $b->getId()); // FALSE -var_export($bcopy->getAuthorId() == $b->getAuthorId()); // TRUE -var_export($bcopy->getAuthor() === $b->getAuthor()); // TRUE -?> -}}} - -== Deep Copies == - -By calling {{{copy()}}} with a {{{TRUE}}} parameter, Propel will create a deep copy of the object; this means that any related objects will also be copied. - -To continue with example from above: - -{{{ -#!php -copy(true); -var_export($bcopy->getId() == $b->getId()); // FALSE -var_export($bcopy->getAuthorId() == $b->getAuthorId()); // FALSE -var_export($bcopy->getAuthor() === $b->getAuthor()); // FALSE -?> -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Customizing-Build.txt b/airtime_mvc/library/propel/docs/cookbook/Customizing-Build.txt deleted file mode 100644 index acfe99406..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Customizing-Build.txt +++ /dev/null @@ -1,153 +0,0 @@ -= Customizing Build = -It is possible to customize the Propel build process by overriding values in your propel __build.properties__ file. For maximum flexibility, you can even create your own Phing __build.xml__ file. - -== Customizing the build.properties == -The easiest way to customize your Propel build is to simply specify build properties in your project's __build.properties__ file. - -=== Understanding Phing build properties === -''Properties'' are essentially variables. These variables can be specified on the commandline or in ''properties files''. - -For example, here's how a property might be specified on the commandline: -{{{ -$> phing -Dpropertyname=value -}}} - -More typically, properties are stored in files and loaded by Phing. For those not familiar with Java properties files, these files look like PHP INI files; the main difference is that values in properties files can be references to other properties (a feature that will probably exist in in INI files in PHP 5.1). - -'''Importantly:''' properties, once loaded, are not overridden by properties with the same name unless explicitly told to do so. In the Propel build process, the order of precedence for property values is as follows: - 1. Commandline properties - 1. Project __build.properties__ - 1. Top-level __build.properties__ - 1. Top-level __default.properties__ - -This means, for example, that values specified in the project's __build.properties__ files will override those in the top-level __build.properties__ and __default.properties__ files. - -=== Changing values === -To get an idea of what you can modify in Propel, simply look through the __build.properties__ and __default.properties__ files. - -''Note, however, that some of the current values exist for legacy reasons and will be cleaned up in Propel 1.1.'' - -==== New build output directories ==== -This can easily be customized on a project-by-project basis. For example, here is a __build.properties__ file for the ''bookstore ''project that puts the generated classes in __/var/www/bookstore/classes__ and puts the generated SQL in __/var/www/bookstore/db/sql__: -{{{ -propel.project = bookstore -propel.database = sqlite -propel.database.url = sqlite://localhost/./test/bookstore.db -propel.targetPackage = bookstore - -# directories -prope.output.dir = /var/www/bookstore -propel.php.dir = ${propel.output.dir}/classes -propel.phpconf.dir = ${propel.output.dir}/conf -propel.sql.dir = ${propel.output.dir}/db/sql -}}} - -The ''targetPackage'' property is also used in determining the path of the generated classes. In the example above, the __Book.php__ class will be located at __/var/www/bookstore/classes/bookstore/Book.php__. You can change this __bookstore__ subdir by altering the ''targetPackage'' property: -{{{ -propel.targetPackage = propelom -}}} - -Now the class will be located at __/var/www/bookstore/classes/propelom/Book.php__ - -''Note that you can override the targetPackage property by specifying a package="" attribute in the tag or even the tag of the schema.xml.'' - -== Creating a custom build.xml file == - -If you want to make more major changes to the way the build script works, you can setup your own Phing build script. This actually is not a very scary task, and once you've managed to create a Phing build script, you'll probably want to create build targets for other aspects of your project (e.g. running batch unit tests is now supported in Phing 2.1-CVS). - -To start with, I suggest taking a look at the __build-propel.xml__ script (the build.xml script is just a wrapper script). Note, however, that the __build-propel.xml__ script does a lot & has a lot of complexity that is designed to make it easy to configure using properties (so, don't be scared). - -Without going into too much detail about how Phing works, the important thing is that Phing build scripts XML and they are grouped into ''targets'' which are kinda like functions. The actual work of the scripts is performed by ''tasks'', which are PHP5 classes that extend the base Phing ''Task'' class and implement its abstract methods. Propel provides some Phing tasks that work with templates to create the object model. - -=== Step 1: register the needed tasks === - -The Propel tasks must be registered so that Phing can find them. This is done using the '''' tag. You can see this near the top of the __build-propel.xml__ file. - -For example, here is how we register the ''propel-om'' task, which is the task that creates the PHP classes for your object model: -{{{ - -}}} - -Simple enough. Phing will now associate the '''' tag with the ''PropelOMTask'' class, which it expects to find at __propel/phing/PropelOMTask.php__ (on your ''include_path''). If Propel generator classes are not on your ''include_path'', you can specify that path in your '''' tag: -{{{ - -}}} - -Or, for maximum re-usability, you can create a '''' object, and then reference it (this is the way __build-propel.xml__ does it): -{{{ - - - - - -}}} - -=== Step 2: invoking the new task === - -Now that the '''' task has been registered with Phing, it can be invoked in your build file. -{{{ - - - -}}} - -In the example above, it's worth pointing out that the '''' task can actually transform multiple __schema.xml__ files, which is why there is a '''' sub-element. Phing ''filesets'' are beyond the scope of this HOWTO, but hopefully the above example is obvious enough. - -=== Step 3: putting it together into a build.xml file === - -Now that we've seen the essential elements of our custom build file, it's time to look at how to assemble them into a working whole: -{{{ - - - - - - - - - - - - - - - - - - - - - - - -}}} - -If that build script was named __build.xml__ then it could be executed by simply running ''phing'' in the directory where it is located: -{{{ -$> phing om -}}} - -Actually, specifying the ''om'' target is not necessary since it is the default. - -Refer to the __build-propel.xml__ file for examples of how to use the other Propel Phing tasks -- e.g. '''' for generating the DDL SQL, '''' for inserting the SQL, etc. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Existing-Database.txt b/airtime_mvc/library/propel/docs/cookbook/Existing-Database.txt deleted file mode 100644 index 3505c0f42..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Existing-Database.txt +++ /dev/null @@ -1,95 +0,0 @@ -= Working With Existing Databases = - -The following topics are targeted for developers who already have a working database solution in place, but would like to use Propel to work with the data. For this case, Propel provides a number of command-line utilities helping with migrations of data and data structures. - -== Working with Database Structures == - -Propel uses an abstract XML schema file to represent databases (the [wiki:Documentation/1.5/Schema schema]). Propel builds the SQL specific to a database based on this schema. Propel also provides a way to reverse-engineer the generic schema file based on database metadata. - -=== Creating an XML Schema from a DB Structure === - -To generate a schema file, create a new directory for your project & specify the connection information in your `build.properties` file for that project. For example, to create a new project, `legacyapp`, follow these steps: - - 1. Create the `legacyapp` project directory anywhere on your filesystem: -{{{ -> mkdir legacyapp -> cd legacyapp -}}} - 1. Create a `build.properties` file in `legacyapp/` directory with the DB connection parameters for your existing database, e.g.: -{{{ -propel.project = legacyapp - -# The Propel driver to use for generating SQL, etc. -propel.database = mysql - -# This must be a PDO DSN -propel.database.url = mysql:dbname=legacyapp -propel.database.user = root -# propel.database.password = -}}} - 1. Run the `reverse` task to generate the `schema.xml`: -{{{ -> propel-gen reverse -}}} - 1. Pay attention to any errors/warnings issued by Phing during the task execution and then examine the generated `schema.xml` file to make any corrections needed. - 1. '''You're done! ''' Now you have a `schema.xml` file in the `legacyapp/` project directory. You can now run the default Propel build to generate all the classes. - -The generated `schema.xml` file should be used as a guide, not a final answer. There are some datatypes that Propel may not be familiar with; also some datatypes are simply not supported by Propel (e.g. arrays in PostgreSQL). Unfamiliar datatypes will be reported as warnings and substituted with a default VARCHAR datatype. - -Tip: The reverse engineering classes may not be able to provide the same level of detail for all databases. In particular, metadata information for SQLite is often very basic since SQLite is a typeless database. - -=== Migrating Structure to a New RDBMS === - -Because Propel has both the ability to create XML schema files based on existing database structures and to create RDBMS-specific DDL SQL from the XML schema file, you can use Propel to convert one database into another. - -To do this you would simply: - 1. Follow the steps above to create the `schema.xml` file from existing db. - 1. Then you would change the target database type and specify connection URL for new database in the project's `build.properties` file: -{{{ -propel.database = pgsql -propel.database.url = pgsql://unix+localhost/newlegacyapp -}}} - 1. And then run the `sql` task to generate the new DDL: -{{{ -> propel-gen sql -}}} - 1. And (optionally) the `insert-sql` task to create the new database: -{{{ -> propel-gen insert-sql -}}} - -== Working with Database Data == - -Propel also provides several tasks to facilitate data import/export. The most important of these are `datadump` and `datasql`. The first dumps data to XML and the second converts the XML data dump to a ready-to-insert SQL file. - -Tip: Both of these tasks require that you already have generated the `schema.xml` for your database. - -=== Dumping Data to XML === - -Once you have created (or reverse-engineered) your `schema.xml` file, you can run the `datadump` task to dump data from the database into a `data.xml` file. - -{{{ -> propel-gen datadump -}}} - -The task transfers database records to XML using a simple format, where each row is an element, and each column is an attribute. So for instance, the XML representation of a row in a `publisher` table: - -||'''publisher_id'''||'''name'''|| -||1||William Morrow|| - -... is rendered in the `data.xml` as follows: -{{{ - - ... - - ... - -}}} - -=== Creating SQL from XML === - -To create the SQL files from the XML, run the `datasql` task: -{{{ -> propel-gen datasql -}}} -The generated SQL is placed in the `build/sql/` directory and will be inserted when you run the `insert-sql` task. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/LOB-Columns.txt b/airtime_mvc/library/propel/docs/cookbook/LOB-Columns.txt deleted file mode 100644 index d4b776d0b..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/LOB-Columns.txt +++ /dev/null @@ -1,73 +0,0 @@ -= Working with LOB Columns = - -Propel uses PHP streams internally for storing ''Binary'' Locator Objects (BLOBs). This choice was made because PDO itself uses streams as a convention when returning LOB columns in a resultset and when binding values to prepared statements. Unfortunately, not all PDO drivers support this (see, for example, http://bugs.php.net/bug.php?id=40913); in those cases, Propel creates a {{{php://temp}}} stream to hold the LOB contents and thus provide a consistent API. - -Note that CLOB (''Character'' Locator Objects) are treated as strings in Propel, as there is no convention for them to be treated as streams by PDO. - -== Getting BLOB Values == - -BLOB values will be returned as PHP stream resources from the accessor methods. Alternatively, if the value is NULL in the database, then the accessors will return the PHP value NULL. - -{{{ -#!php -getCoverImage(); -if ($fp !== null) { - echo stream_get_contents($fp); -} -}}} - -== Setting BLOB Values == - -When setting a BLOB column, you can either pass in a stream or the blob contents. - -=== Setting using a stream === -{{{ -#!php -setCoverImage($fp); -}}} - -=== Setting using file contents === -{{{ -#!php -setCoverImage(file_get_contents("/path/to/file.ext")); -}}} - -Regardless of which setting method you choose, the BLOB will always be represented internally as a stream resource -- ''and subsequent calls to the accessor methods will return a stream.'' - -For example: -{{{ -#!php -setCoverImage(file_get_contents("/path/to/file.ext")); - -$fp = $media->getCoverImage(); -print gettype($fp); // "resource" -}}} - -=== Setting BLOB columns and isModified() === - -Note that because a stream contents may be externally modified, ''mutator methods for BLOB columns will always set the '''isModified()''' to report true'' -- even if the stream has the same identity as the stream that was returned. - -For example: -{{{ -#!php -getCoverImage(); -$media->setCoverImage($fp); - -var_export($media->isModified()); // TRUE -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Master-Slave.txt b/airtime_mvc/library/propel/docs/cookbook/Master-Slave.txt deleted file mode 100644 index 2e28f4903..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Master-Slave.txt +++ /dev/null @@ -1,94 +0,0 @@ -= Replication = - -Propel can be used in a master-slave replication environment. These environments are set up to improve the performance of web applications by dispatching the database-load to multiple database-servers. While a single master database is responsible for all write-queries, multiple slave-databases handle the read-queries. The slaves are synchronised with the master by a fast binary log (depending on the database). - -== Configuring Propel for Replication == - - * Set up a replication environment (see the Databases section below) - * Use the latest Propel-Version from SVN - * add a slaves-section to your {{{runtime-conf.xml}}} file - * verify the correct setup by checking the masters log file (should not contain "select ..." statements) - -You can configure Propel to support replication by adding a element with nested element(s) to your {{{runtime-conf.xml}}}. - -The section is at the same level as the master and contains multiple nested elements with the same information as the top-level (master) . It is recommended that they are numbered. The follwing example shows a slaves section with a several slave connections configured where "localhost" is the master and "slave-server1" and "slave-server2" are the slave-database connections. - -{{{ -#!xml - - - - propel-bookstore - console - 7 - - - - - sqlite - - mysql:host=localhost;dbname=bookstore - testuser - password - - - - mysql:host=slave-server1; dbname=bookstore - testuser - password - - - mysql:host=slave-server2; dbname=bookstore - testuser - password - - - - - - -}}} - -== Implementation == - -The replication functionality is implemented in the Propel connection configuration and initialization code and in the generated Peer and Object classes. - -=== Propel::getConnection() === - -When requesting a connection from Propel ('''Propel::getConnection()'''), you can either specify that you want a READ connection (slave) or WRITE connection (master). Methods that are designed to perform READ operations, like the '''doSelect*()''' methods of your generated Peer classes, will always request a READ connection like so: -{{{ -#!php -query('SELECT * FROM my'); -/* ... */ -}}} - -=== Propel::setForceMasterConnection() === - -You can force Propel to always return a WRITE (master) connection from '''Propel::getConnection()''' by calling '''Propel::setForceMasterConnection(true);'''. This can be useful if you must be sure that you are getting the most up-to-date data (i.e. if there is some latency possible between master and slaves). - -== Databases == - -=== MySql === - -http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html - -== References == - - * Henderson Carl (2006): Building Scalable Web Sites. The Flickr Way. O'Reilly. ISBN-596-10235-6. - diff --git a/airtime_mvc/library/propel/docs/cookbook/Multi-Component.txt b/airtime_mvc/library/propel/docs/cookbook/Multi-Component.txt deleted file mode 100644 index f033ce70c..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Multi-Component.txt +++ /dev/null @@ -1,297 +0,0 @@ -= Multi-Component Data Model = - -Propel comes along with packaging capabilities that allow you to more easily integrate Propel into a packaged or modularized application. - -== Muliple Schemas == - -You can use as many `schema.xml` files as you want. Schema files have to be named `(*.)schema.xml`, so names like `schema.xml`, `package1.schema.xml`, `core.package1.schema.xml` are all acceptable. These files ''have'' to be located in your project directory. - -Each schema file has to contain a `` element with a `name` attribute. This name references the connection settings to be used for this database (and configured in the `runtime-conf.xml`), so separated schemas can share a common database name. - -Whenever you call a propel build taks, Propel will consider all these schema files and build the classes (or the SQL) for all the tables. - -== Understanding Packages == - -In Propel, a ''package'' represents a group of models. This is a convenient way to organize your code in a modularized way, since classes and SQL files of a given package are be grouped together and separated from the other packages. By carefully choosing the package of each model, applications end up in smaller, independent modules that are easier to manage. - -=== Package Cascade === - -The package is defined in a configuration cascade. You can set it up for the whole project, for all the tables of a schema, or for a single table. - -For the whole project, the main package is set in the `build.properties`: - -{{{ -#!ini -propel.targetPackage = my_project -}}} - -By default, all the tables of all the schemas in the project use this package. However, you can override the package for a given `` by setting its `package` attribute: - -{{{ -#!xml - - -
- -
-
- - - - - -
- - -
-
-}}} - -In this example, thanks to the `package` attribute, the tables are grouped into the following packages: - - * `my_project.author` package: `author` table - * `my_project.book` package: `book` and `review` tables - -'''Warning''': If you separate tables related by a foreign key into separate packages (like `book` and `author` in this example), you must enable the `packageObjectModel` build property to let Propel consider other packages for relations. - -You can also override the `package` attribute at the `` element level. - -{{{ -#!xml - - -
- -
-
- - - - - -
- - -
-
-}}} - -This ends up in the following package: - - * `my_project.author` package: `author` table - * `my_project.book` package: `book` table - * `my_project.review` package: `review` table - -Notice that tables can end up in separated packages even though they belong to the same schema file. - -'''Tip''': You can use dots in a package name to add more package levels. - -=== Packages and Generated Model Files === - -The `package` attribute of a table translates to the directory in which Propel generates the Model classes for this table. - -For instance, if no `package` attribute is defined at the database of table level, Propel places all classes according to the `propel.targetPackage` from the `build.properties`: - -{{{ -build/ - classes/ - my_project/ - om/ - map/ - Author.php - AuthorPeer.php - AuthorQuery.php - Book.php - BookPeer.php - BookQuery.php - Review.php - ReviewPeer.php - ReviewQuery.php -}}} - -You can further tweak the location where Propel puts the created files by changing the `propel.output.dir` build property. By default this property is set to: - -{{{ -#!ini -propel.output.dir = ${propel.project.dir}/build -}}} - -You can change it to use any other directory as your build directory. - -If you set up packages for `` elements, Propel splits up the generated model classes into subdirectories named after the package attribute: - -{{{ -build/ - classes/ - my_project/ - author/ - om/ - map/ - Author.php - AuthorPeer.php - AuthorQuery.php - book/ - om/ - map/ - Book.php - BookPeer.php - BookQuery.php - Review.php - ReviewPeer.php - ReviewQuery.php -}}} - -And of course, if you specialize the `package` attribute per table, you can have one table use its own package: - -{{{ -build/ - classes/ - my_project/ - author/ - om/ - map/ - Author.php - AuthorPeer.php - AuthorQuery.php - book/ - om/ - map/ - Book.php - BookPeer.php - BookQuery.php - review/ - om/ - map/ - Review.php - ReviewPeer.php - ReviewQuery.php -}}} - -=== Packages And SQL Files === - -Propel also considers packages for SQL generation. In practice, Propel generates one SQL file per package. Each file contains the CREATE TABLE SQL statements necessary to create all the tables of a given package. - -So by default, all the tables end up in a single SQL file: - -{{{ -build/ - sql/ - schema.sql -}}} - -If you specialize the `package` for each `` element, Propel uses it for SQL files: - -{{{ -build/ - sql/ - author.schema.sql // contains CREATE TABLE author - book.schema.sql // contains CREATE TABLE book and CREATE TABLE review -}}} - -And, as you probably expect it, a package overridden at the table level also accounts for an independent SQL file: - -{{{ -build/ - sql/ - author.schema.sql // contains CREATE TABLE author - book.schema.sql // contains CREATE TABLE book - review.schema.sql // contains CREATE TABLE review -}}} - -== Understanding The packageObjectModel Build Property == - -The `propel.packageObjectModel` build property enables the "packaged" build process. This modifies the build tasks behavior by joining `` elements of the same name - but keeping their packages separate. That allows to split a large schema into several files, regardless of foreign key dependencies, since Propel will join all schemas using the same database name. - -To switch this on, simply add the following line to the `build.properties` file in your project directory: -{{{ -propel.packageObjectModel = true -}}} - -== The Bookstore Packaged Example == - -In the bookstore-packaged example you'll find the following schema files: - - * author.schema.xml - * book.schema.xml - * club.schema.xml - * media.schema.xml - * publisher.schema.xml - * review.schema.xml - * log.schema.xml - -Each schema file has to contain a `` tag that has its `package` attribute set to the package name where ''all'' of the tables in this schema file/database belong to. - -For example, in the bookstore-packaged example the `author.schema.xml` contains the following `` tag: - -{{{ - -}}} - -That means, that the Author OM classes will be created in a subdirectory `core/author/` of the build output directory. - -You can have more than one schema file that belong to one package. For example, in the the bookstore-packaged example both the `book.schema.xml` and `media.schema.xml` belong to the same package "core.book". The generated OM classes for these schemas will therefore end up in the same `core/book/` subdirectory. - -=== The OM build === - -To run the packaged bookstore example build simply go to the `propel/test/fixtures/bookstore-packages/` directory and type: - -{{{ -../../../generator/bin/propel-gen om -}}} - -This should run without any complaints. When you have a look at the projects/bookstore-packaged/build/classes directory, the following directory tree should have been created: -{{{ -addon/ - club/ - BookClubList.php - BookClubListPeer.php - BookListRel.php - BookListRelPeer.php -core/ - author/ - Author.php - AuthorPeer.php - book/ - Book.php - BookPeer.php - - Media.php - MediaPeer.php - publisher/ - Publisher.php - PublisherPeer.php - review/ - Review.php - ReviewPeer.php -util/ - log/ - BookstoreLog.php - BookstoreLogPeer.php -}}} - -(The additional subdirectories map/ and om/ in each of these directories have been omitted for clarity.) - -== The SQL build == - -From the same schema files, run the SQL generation by calling: - -{{{ -../../../generator/bin/propel-gen sql -}}} - -Then, have a look at the `build/sql/` directory: you will see that for each package (that is specified as a package attribute in the schema file database tags), one sql file has been created: - - * addon.club.schema.sql - * core.author.schema.sql - * core.book.schema.sql - * core.publisher.schema.sql - * core.review.schema.sql - * util.log.schema.sql - -These files contain the CREATE TABLE SQL statements necessary for each package. - -When you now run the insert-sql task by typing: -{{{ -../../../generator/bin/propel-gen insert-sql -}}} -these SQL statements will be executed on a SQLite database located in the Propel/generator/test/ directory. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Namespaces.txt b/airtime_mvc/library/propel/docs/cookbook/Namespaces.txt deleted file mode 100644 index 705d5ed68..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Namespaces.txt +++ /dev/null @@ -1,133 +0,0 @@ -= How to Use PHP 5.3 Namespaces = - -The generated model classes can use a namespace. It eases the management of large database models, and makes the Propel model classes integrate with PHP 5.3 applications in a clean way. - -== Namespace Declaration And Inheritance == - -To define a namespace for a model class, you just need to specify it in a `namespace` attribute of the `` element for a single table, or in the `` element to set the same namespace to all the tables. - -Here is an example schema using namespaces: - -{{{ -#!xml - - - -
- - - - - - - - - - - - -
- - - - - - -
- - - - -
- - - - - -
- -
-}}} - -The `` element defines a `namespace` attribute. The `book` and `author` tables inherit their namespace from the database, therefore the generated classes for these tables will be `\Bookstore\Book` and `\Bookstore\Author`. - -The `publisher` table defines a `namespace` attribute on ots own, which ''extends'' the database namespace. That means that the generated class will be `\Bookstore\Book\Publisher`. - -As for the `user` table, it defines an absolute namespace (starting with a backslash), which ''overrides'' the database namespace. The generated class for the `user` table will be `Admin\User`. - -'''Tip''': You can use subnamespaces (i.e. namespaces containing backslashes) in the `namespace` attribute. - -== Using Namespaced Models == - -Namespaced models benefit from the Propel runtime autoloading just like the other model classes. You just need to alias them, or to use their fully qualified name. - -{{{ -#!php -setAuthor($author); -$book->save(); -}}} - -The namespace is used for the ActiveRecord class, but also for the Query and Peer classes. Just remember that when you use relation names ina query, the namespace should not appear: - -{{{ -#!php -useBookQuery() - ->filterByPrice(array('max' => 10)) - ->endUse() - ->findOne(); -}}} - -Related tables can have different namespaces, it doesn't interfere with the functionality provided by the object model: - -{{{ -#!php -findOne(); -echo get_class($book->getPublisher()); -// \Bookstore\Book\Publisher -}}} - -'''Tip''': Using namespaces make generated model code incompatible with versions of PHP less than 5.3. Beware that you will not be able to use your model classes in an older PHP application. - -== Using Namespaces As A Directory Structure == - -In a schema, you can define a `package` attribute on a `` or a `` tag to generate model classes in a subdirectory (see [wiki:Documentation/1.5/Multi-Component]). If you use namespaces to autoload your classes based on a SplClassAutoloader (see http://groups.google.com/group/php-standards), then you may find yourself repeating the `namespace` data in the `package` attribute: - -{{{ -#!xml - -}}} - -To avoid such repetitions, just set the `propel.namespace.autoPackage` setting to `true` in your `build.properties`: - -{{{ -#!ini -propel.namespace.autoPackage = true -}}} - -Now Propel will automatically create a `package` attribute, and therefore distribute model classes in subdirectories, based on the `namespace` attribute, and you can omit the manual `package` attribute in the schema: - -{{{ -#!xml - -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/cookbook/Nested-Set.txt b/airtime_mvc/library/propel/docs/cookbook/Nested-Set.txt deleted file mode 100644 index 8cf7fed7e..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Nested-Set.txt +++ /dev/null @@ -1,183 +0,0 @@ -= !NestedSet support in Propel = - -'''Warning''': Since Propel 1.5, the support for nested sets was moved to the `nested_set` behavior. The method described here is deprecated.''' - -== Description == - -With !NestedSet implementation, trees are stored using different approach in databases: [http://www.sitepoint.com/article/hierarchical-data-database] - -Nested Set implementation requires three dedicated fields in table structure - - * left - * right - -Plus an optional fields for multi nested set support - * scope - -''NB: fields name are free and must be defined in schema.xml'' - -To enable !NestedSet support in table, schema.xml must define some specific attributes: -'''treeMode''' which must take the value '''!NestedSet''' - -{{{ -#!xml -
-}}} - -Then, left and right field must be defined that way '''nestedSetLeftKey''' as a boolean value as '''nestedSetRightKey''' - -{{{ -#!xml - - -}}} - -For multi nestedset support, an other column must be defined with boolean attribute '''treeScopeKey''' set to true -{{{ -#!xml - -}}} - -And then, let's the propel generator automagically create all the needed model and stub classes. - -== !NestedSet usage in Propel == - -''ex:'' -'''schema.xml''' extract -{{{ -#!xml -
- - - - - - - - - - - - - - - -
-}}} - -=== !NestedSet insertion === -{{{ -#!php -setText('Google'); -$root->setLink('http://www.google.com'); - -$root->makeRoot(); -$root->save(); - -$menu = new Menu(); -$menu->setText('Google Mail'); -$menu->setLink('http://mail.google.com'); -$menu->insertAsLastChildOf($root); -$menu->save(); - -$child = new Menu(); -$child->setText('Google Maps'); -$child->setLink('http://maps.google.com'); -$child->insertAsLastChildOf($root); -$child->save(); - -$sibling = new Menu(); -$sibling->setText('Yahoo!'); -$sibling->setLink('http://www.yahoo.com'); -$sibling->insertAsNextSiblingOf($root); -$sibling->save(); - -$child = new Menu(); -$child->setText('Yahoo! Mail'); -$child->setLink('http://mail.yahoo.com'); -$child->insertAsLastChildOf($sibling); -$child->save(); -}}} - -=== Multi !NestedSet insertion === -{{{ -#!php -setText('Google'); -$root->setLink('http://www.google.com'); - -$root->makeRoot(); -$root->setScopeIdValue(1); // Tree 1 -$root->save(); - -$menu = new Menu(); -$menu->setText('Google Mail'); -$menu->setLink('http://mail.google.com'); -$menu->insertAsLastChildOf($root); -$menu->save(); - -// Create secund root node -$root2 = new Menu(); -$root2->setText('Yahoo!'); -$root2->setLink('http://www.yahoo.com'); - -$root2->makeRoot(); -$root2->setScopeIdValue(2); // Tree 2 -$root2->save(); - -$menu = new Menu(); -$menu->setText('Yahoo! Mail'); -$menu->setLink('http://mail.yahoo.com'); -$menu->insertAsLastChildOf($root2); -$menu->save(); -}}} - -=== Tree retrieval === -{{{ -#!php -getDepth()); - } - - function endChildren() { - echo str_repeat("\t", $this->getDepth() - 1); - } -} - -$menu = MenuPeer::retrieveTree($scopeId); -$it = new myMenuOutput($menu); -foreach($it as $m) { - echo $m->getText(), '[', $m->getLeftValue(), '-', $m->getRightValue(), "]\n"; -} -}}} -=== Tree traversal === - -!NestetSet implementation use the [http://somabo.de/talks/200504_php_quebec_spl_for_the_masses.pdf SPL RecursiveIterator] as suggested by soenke - -== !NestedSet known broken behaviour == - -=== Issue description === -For every changes applied on the tree, several entries in the database can be involved. So all already loaded nodes have to be refreshed with their new left/right values. - -=== InstancePool enabled === -In order to refresh all loaded nodes, an automatic internal call is made after each tree change to retrieve all instance in InstancePool and update them. -And it works fine. - -=== InstancePool disabled === -When InstancePool is disabled, their is no way to retrieve references to all already loaded node and get them updated. -So in most case, all loaded nodes are not updated and it leads to an inconsistency state. -So, workaround is to do an explicit reload for any node you use after tree change. - - diff --git a/airtime_mvc/library/propel/docs/cookbook/Runtime-Introspection.txt b/airtime_mvc/library/propel/docs/cookbook/Runtime-Introspection.txt deleted file mode 100644 index dce769231..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Runtime-Introspection.txt +++ /dev/null @@ -1,164 +0,0 @@ -= Model Introspection At Runtime = - -In addition to the object and peer classes used to do C.R.U.D. operations, Propel generates an object mapping for your tables to allow runtime introspection. - -The intospection objects are instances of the map classes. Propel maps databases, tables, columns, validators, and relations into objects that you can easily use. - -== Retrieving a TableMap == - -The starting point for runtime introspection is usually a table map. This objects stores every possible property of a table, as defined in the `schema.xml`, but accessible at runtime. - -To retrieve a table map for a table, use the `getTableMap()` static method of the related peer class. For instance, to retrieve the table map for the `book` table, just call: - -{{{ -#!php -getName(); // 'table' -echo $bookTable->getPhpName(); // 'Table' -echo $bookTable->getPackage(); // 'bookstore' -echo $bookTable->isUseIdGenerator(); // true -}}} - -Tip: A TableMap object also references the `DatabaseMap` that contains it. From the database map, you can also retrieve other table maps using the table name or the table phpName: -{{{ -#!php -getDatabaseMap(); -$authorTable = $dbMap->getTable('author'); -$authorTable = $dbMap->getTablebyPhpName('Author'); -}}} - -To introspect the columns of a table, use any of the `getColumns()`, `getPrimaryKeys()`, and `getForeignKeys()` `TableMap` methods. They all return an array of `ColumnMap` objects. - -{{{ -#!php -getColumns(); -foreach ($bookColumns as $column) { - echo $column->getName(); -} -}}} - -Alternatively, if you know a column name, you can retrieve the corresponding ColumnMap directly using the of `getColumn($name)` method. - -{{{ -#!php -getColumn('title'); -}}} - -The `DatabaseMap` object offers a shortcut to every `ColumnMap` object if you know the fully qualified column name: -{{{ -#!php -getColumn('book.TITLE'); -}}} - -== ColumnMaps == - -A `ColumnMap` instance offers a lot of information about a table column. Check the following examples: - -{{{ -#!php -getTableName(); // 'book' -$bookTitleColumn->getTablePhpName(); // 'Book' -$bookTitleColumn->getType(); // 'VARCHAR' -$bookTitleColumn->getSize(); // 255 -$bookTitleColumn->getDefaultValue(); // null -$bookTitleColumn->isLob(); // false -$bookTitleColumn->isTemporal(); // false -$bookTitleColumn->isEpochTemporal(); // false -$bookTitleColumn->isNumeric(); // false -$bookTitleColumn->isText(); // true -$bookTitleColumn->isPrimaryKey(); // false -$bookTitleColumn->isForeignKey(); // false -$bookTitleColumn->hasValidators(); // false -}}} - -`ColumnMap` objects also keep a reference to their parent `TableMap` object: - -{{{ -#!php -getTable(); -}}} - -Foreign key columns give access to more information, including the related table and column: - -{{{ -#!php -getColumn('publisher_id'); -echo $bookPublisherIdColumn->isForeignKey(); // true -echo $bookPublisherIdColumn->getRelatedName(); // 'publisher.ID' -echo $bookPublisherIdColumn->getRelatedTableName(); // 'publisher' -echo $bookPublisherIdColumn->getRelatedColumnName(); // 'ID' -$publisherTable = $bookPublisherIdColumn->getRelatedTable(); -$publisherRelation = $bookPublisherIdColumn->getRelation(); -}}} - -== RelationMaps == - -To get an insight on all the relationships of a table, including the ones relying on a foreign key located in another table, you must use the `RelationMap` objects related to a table. - -If you know its name, you can retrieve a `RelationMap` object using `TableMap::getRelation($relationName)`. Note that the relation name is the phpName of the related table, unless the foreign key defines a phpName in the schema. For instance, the name of the `RelationMap` object related to the `book.PUBLISHER_ID` column is 'Publisher'. - -{{{ -#!php -getRelation('Publisher'); -}}} - -alternatively, you can access a `RelationMap` from a foreign key column using `ColumnMap::getRelation()`, as follows: - -{{{ -#!php -getColumn('publisher_id')->getRelation(); -}}} - -Once you have a `RelationMap` instance, inspect its properties using any of the following methods: - -{{{ -#!php -getType(); // RelationMap::MANY_TO_ONE -echo $publisherRelation->getOnDelete(); // 'SET NULL' -$bookTable = $publisherRelation->getLocalTable(); -$publisherTable = $publisherRelation->getForeignTable(); -print_r($publisherRelation->getColumnMappings()); - // array('book.PUBLISHER_ID' => 'publisher.ID') -print_r(publisherRelation->getLocalColumns()); - // array($bookPublisherIdColumn) -print_r(publisherRelation->getForeignColumns()); - // array($publisherBookIdColumn) -}}} - -This also works for relationships referencing the current table: - -{{{ -#!php -getRelation('Review'); -echo $reviewRelation->getType(); // RelationMap::ONE_TO_MANY -echo $reviewRelation->getOnDelete(); // 'CASCADE' -$reviewTable = $reviewRelation->getLocalTable(); -$bookTable = $reviewRelation->getForeignTable(); -print_r($reviewRelation->getColumnMappings()); - // array('review.BOOK_ID' => 'book.ID') -}}} - -To retrieve all the relations of a table, call `TableMap::getRelations()`. You can then iterate over an array of `RelationMap` objects. - -Tip: RelationMap objects are lazy-loaded, which means that the `TableMap` will not instanciate any relation object until you call `getRelations()`. This allows the `TableMap` to remain lightweight for when you don't use relationship introspection. diff --git a/airtime_mvc/library/propel/docs/cookbook/Writing-Behavior.txt b/airtime_mvc/library/propel/docs/cookbook/Writing-Behavior.txt deleted file mode 100644 index 33ceebc63..000000000 --- a/airtime_mvc/library/propel/docs/cookbook/Writing-Behavior.txt +++ /dev/null @@ -1,424 +0,0 @@ -= How to Write A Behavior = - -Behaviors are a good way to reuse code across models without requiring inheritance (a.k.a. horizontal reuse). This step-by-step tutorial explains how to port model code to a behavior, focusing on a simple example. - -In the tutorial "[http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat Keeping an Aggregate Column up-to-date]", posted in the [http://propel.posterous.com/ Propel blog], the `TotalNbVotes` property of a `PollQuestion` object was updated each time a related `PollAnswer` object was saved, edited, or deleted. This "aggregate column" behavior was implemented by hand using hooks in the model classes. To make it truly reusable, the custom model code needs to be refactored and moved to a Behavior class. - -== Boostrapping A Behavior == - -A behavior is a class that can alter the generated classes for a table of your model. It must only extend the [browser:branches/1.5/generator/lib/model/Behavior.php `Behavior`] class and implement special "hook" methods. Here is the class skeleton to start with for the `aggregate_column` behavior: - -{{{ -#!php - null, - ); -} -}}} - -Save this class in a file called `AggregateColumnBehavior.php`, and set the path for the class file in the project `build.properties` (just replace directory separators with dots). Remember that the `build.properties` paths are relative to the include path: - -{{{ -#!ini -propel.behavior.aggregate_column.class = path.to.AggregateColumnBehavior -}}} - -Test the behavior by adding it to a table of your model, for instance to a `poll_question` table: - -{{{ -#!xml - - - - - - - -
-
-}}} - -Rebuild your model, and check the generated `PollQuestionTableMap` class under the `map` subdirectory of your build class directory. This class carries the structure metadata for the `PollQuestion` ActiveRecord class at runtime. The class should feature a `getBehaviors()` method as follows, proving that the behavior was correctly applied: - -{{{ -#!php - array('name' => 'total_nb_votes', ), - ); - } // getBehaviors() -} -}}} - -== Adding A Column == - -The behavior works, but it still does nothing at all. Let's make it useful by allowing it to add a column. In the `AggregateColumnBehavior` class, just implement the `modifyTable()` method with the following code: - -{{{ -#!php -getTable(); - if (!$columnName = $this->getParameter('name')) { - throw new InvalidArgumentException(sprintf( - 'You must define a \'name\' parameter for the \'aggregate_column\' behavior in the \'%s\' table', - $table->getName() - )); - } - // add the aggregate column if not present - if(!$table->containsColumn($columnName)) { - $table->addColumn(array( - 'name' => $columnName, - 'type' => 'INTEGER', - )); - } - } -} -}}} - -This method shows that a behavior class has access to the `` defined for it in the `schema.xml` through the `getParameter()` command. Behaviors can also always access the `Table` object attached to them, by calling `getTable()`. A `Table` can check if a column exists and add a new one easily. The `Table` class is one of the numerous generator classes that serve to describe the object model at buildtime, together with `Column`, `ForeignKey`, `Index`, and a lot more classes. You can find all the buildtime model classes under the [browser:branches/1.5/generator/lib/model generator/lib/model] directory. - -'''Tip''': Don't mix up the ''runtime'' database model (`DatabaseMap`, `TableMap`, `ColumnMap`, `ValidatorMap`, `RelationMap`) with the ''buildtime'' database model (`Database`, `Table`, `Column`, `Validator`, etc.). The buildtime model is very detailed, in order to ease the work of the builders that write the ActiveRecord and Query classes. On the other hand, the runtime model is optimized for speed, and carries minimal information to allow correct hydration and binding at runtime. Behaviors use the buildtime object model, because they are run at buildtime, so they have access to the most powerful model. - -Now rebuild the model and the SQL, and sure enough, the new column is there. `BasePollQuestion` offers a `getTotalNbVotes()` and a `setTotalNbVotes()` method, and the table creation SQL now includes the additional `total_nb_votes` column: - -{{{ -#!sql -DROP TABLE IF EXISTS poll_question; -CREATE TABLE poll_question -( - id INTEGER NOT NULL AUTO_INCREMENT, - title VARCHAR(100), - total_nb_votes INTEGER, - PRIMARY KEY (id) -)Type=InnoDB; -}}} - -'''Tip''': The behavior only adds the column if it's not present (`!$table->containsColumn($columnName)`). So if a user needs to customize the column type, or any other attribute, he can include a `` tag in the table with the same name as defined in the behavior, and the `modifyTable()` will then skip the column addition. - -== Adding A Method To The ActiveRecord Class == - -In the previous post, a method of the ActiveRecord class was in charge of updating the `total_nb_votes` column. A behavior can easily add such methods by implementing the `objectMethods()` method: - -{{{ -#!php -addUpdateAggregateColumn(); - return $script; - } - - protected function addUpdateAggregateColumn() - { - $sql = sprintf('SELECT %s FROM %s WHERE %s = ?', - $this->getParameter('expression'), - $this->getParameter('foreign_table'), - $this->getParameter('foreign_column') - ); - $table = $this->getTable(); - $aggregateColumn = $table->getColumn($this->getParameter('name')); - $columnPhpName = $aggregateColumn->getPhpName(); - $localColumn = $table->getColumn($this->getParameter('local_column')); - return " -/** - * Updates the aggregate column {$aggregateColumn->getName()} - * - * @param PropelPDO \$con A connection object - */ -public function update{$columnPhpName}(PropelPDO \$con) -{ - \$sql = '{$sql}'; - \$stmt = \$con->prepare(\$sql); - \$stmt->execute(array(\$this->get{$localColumn->getPhpName()}())); - \$this->set{$columnPhpName}(\$stmt->fetchColumn()); - \$this->save(\$con); -} -"; - } -} -}}} - -The ActiveRecord class builder expects a string in return to the call to `Behavior::objectMethods()`, and appends this string to the generated code of the ActiveRecord class. Don't bother about indentation: builder classes know how to properly indent a string returned by a behavior. A good rule of thumb is to create one behavior method for each added method, to provide better readability. - -Of course, the schema must be modified to supply the necessary parameters to the behavior: - -{{{ -#!xml - - - - - - - - - - - -
- - - - - - - - -
-
-}}} - -Now if you rebuild the model, you will see the new `updateTotalNbVotes()` method in the generated `BasePollQuestion` class: - -{{{ -#!php -prepare($sql); - $stmt->execute(array($this->getId())); - $this->setTotalNbVotes($stmt->fetchColumn()); - $this->save($con); - } -} -}}} - -Behaviors offer similar hook methods to allow the addition of methods to the query classes (`queryMethods()`) and to the peer classes (`peerMethods()`). And if you need to add attributes, just implement one of the `objectAttributes()`, `queryAttributes()`, or `peerAttributes()` methods. - -== Using a Template For Generated Code == - -The behavior's `addUpdateAggregateColumn()` method is somehow hard to read, because of the large string containing the PHP code canvas for the added method. Propel behaviors can take advantage of Propel's simple templating system to use an external file as template for the code to insert. - -Let's refactor the `addUpdateAggregateColumn()` method to take advantage of this feature: - -{{{ -#!php -getParameter('expression'), - $this->getParameter('foreign_table'), - $this->getParameter('foreign_column') - ); - $table = $this->getTable(); - $aggregateColumn = $table->getColumn($this->getParameter('name')); - return $this->renderTemplate('objectUpdateAggregate', array( - 'aggregateColumn' => $aggregateColumn, - 'columnPhpName' => $aggregateColumn->getPhpName(), - 'localColumn' => $table->getColumn($this->getParameter('local_column')), - 'sql' => $sql, - )); - } -} -}}} - -The method no longer returns a string created by hand, but a ''rendered template''. Propel templates are simple PHP files executed in a sandbox - they have only access to the variables declared as second argument of the `renderTemplate()` call. - -Now create a `templates/` directory in the same directory as the `AggregateColumnBehavior` class file, and add in a `objectUpdateAggregate.php` file with the following code: - -{{{ -#!php -/** - * Updates the aggregate column getName() ?> - * - * @param PropelPDO $con A connection object - */ -public function update(PropelPDO $con) -{ - $sql = ''; - $stmt = $con->prepare($sql); - $stmt->execute(array($this->getgetPhpName() ?>())); - $this->set($stmt->fetchColumn()); - $this->save($con); -} -}}} - -No need to escape dollar signs anymore: this syntax allows for a cleaner separation, and is very convenient for large behaviors. - -== Adding Another Behavior From A Behavior == - -This is where it's getting tricky. In the [http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat blog post] describing the column aggregation technique, the calls to the `updateTotalNbVotes()` method come from the `postSave()` and `postDelete()` hooks of the `PollAnswer` class. But the current behavior is applied to the `poll_question` table, how can it modify the code of a class based on another table? - -The short answer is: it can't. To modify the classes built for the `poll_answer` table, a behavior must be registered on the `poll_answer` table. But a behavior is just like a column or a foreign key: it has an object counterpart in the buildtime database model. So the trick here is to modify the `AggregateColumnBehavior::modifyTable()` method to ''add a new behavior'' to the foreign table. This second behavior will be in charge of implementing the `postSave()` and `postDelete()` hooks of the `PollAnswer` class. - -{{{ -#!php -getDatabase()->getTable($this->getParameter('foreign_table')); - if (!$foreignTable->hasBehavior('concrete_inheritance_parent')) { - require_once 'AggregateColumnRelationBehavior.php'; - $relationBehavior = new AggregateColumnRelationBehavior(); - $relationBehavior->setName('aggregate_column_relation'); - $relationBehavior->addParameter(array( - 'name' => 'foreign_table', - 'value' => $table->getName() - )); - $relationBehavior->addParameter(array( - 'name' => 'foreign_column', - 'value' => $this->getParameter('name') - )); - $foreignTable->addBehavior($relationBehavior); - } - } -} -}}} - -In practice, everything now happens as if the `poll_answer` had its own behavior: - -{{{ -#!xml - - - - - - - - -
-
-}}} - -Adding a behavior to a `Table` instance, as well as adding a `Parameter` to a `Behavior` instance, is quite straightforward. And since the second behavior class file is required in the `modifyTable()` method, there is no need to add a path for it in the `build.properties`. - -== Adding Code For Model Hooks == - -The new `AggregateColumnRelationBehavior` is yet to write. It must implement a call to `PollQuestion::updateTotalNbVotes()` in the `postSave()` and `postDelete()` hooks. - -Adding code to hooks from a behavior is just like adding methods: add a method with the right hook name returning a code string, and the code will get appended at the right place. Unsurprisingly, the behavior hook methods for `postSave()` and `postDelete()` are called `postSave()` and `postDelete()`: - -{{{ -#!php - null, - 'foreignColumn' => null, - ); - - public function postSave() - { - $table = $this->getTable(); - $foreignTable = $table->getDatabase()->getTable($this->getParameter('foreign_table')); - $foreignColumn = $foreignTable->getColumn($this->getParameter('foreign_column')); - $foreignColumnPhpName = $foreignColumn->getPhpName(); - return "\$this->updateRelated{$foreignColumnPhpName}(\$con)"; - } - - public function postDelete() - { - return $this->postSave(); - } - - public function objectMethods() - { - $script = ''; - $script .= $this->addUpdateRelatedAggregateColumn(); - return $script; - } - - protected function addUpdateRelatedAggregateColumn() - { - $table = $this->getTable(); - $foreignTable = $table->getDatabase()->getTable($this->getParameter('foreign_table')); - $foreignTablePhpName = foreignTable->getPhpName(); - $foreignColumn = $foreignTable->getColumn($this->getParameter('foreign_column')); - $foreignColumnPhpName = $foreignColumn->getPhpName(); - return " -/** - * Updates an aggregate column in the foreign {$foreignTable->getName()} table - * - * @param PropelPDO \$con A connection object - */ -protected function updateRelated{$foreignColumnPhpName}(PropelPDO \$con) -{ - if (\$parent{$foreignTablePhpName} = \$this->get{$foreignTablePhpName}()) { - \$parent{$foreignTablePhpName}->update{$foreignColumnPhpName}(\$con); - } -} -"; - } -} -}}} - -The `postSave()` and `postDelete()` behavior hooks will not add code to the ActiveRecord `postSave()` and `postDelete()` methods - to allow users to further implement these methods - but instead it adds code directly to the `save()` and `delete()` methods, inside a transaction. Check the generated `BasePollAnswer` class for the added code in these methods: - -{{{ -#!php -updateRelatedTotalNbVotes($con); -}}} - -You will also see the new `updateRelatedTotalNbVotes()` method added by `AggregateColumnBehavior::objectMethods()`: - -{{{ -#!php -getPollQuestion()) { - $parentPollQuestion->updateTotalNbVotes($con); - } -} -}}} - -== What's Left == - -These are the basics of behavior writing: implement one of the methods documented in the [wiki:Documentation/1.5/Behaviors#WritingaBehavior behaviors chapter] of the Propel guide, and return strings containing the code to be added to the ActiveRecord, Query, and Peer classes. In addition to the behavior code, you should always write unit tests - all the behaviors bundled with Propel have full unit test coverage. And to make your behavior usable by others, documentation is highly recommended. Once again, Propel core behaviors are fully documented, to let users understand the behavior usage without having to peek into the code. - -As for the `AggregateColumnBehavior`, the job is not finished. The [http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat blog post] emphasized the need for hooks in the Query class, and these are not yet implemented in the above code. Besides, the post kept quiet about one use case that left the aggregate column not up to date (when a question is detached from a poll without deleting it). Lastly, the parameters required for this behavior are currently a bit verbose, especially concerning the need to define the foreign table and the foreign key - this could be simplified thanks to the knowledge of the object model that behaviors have. - -All this is left to the reader as an exercise. Fortunately, the final behavior is part of the Propel core behaviors, so the [browser:branches/1.5/generator/lib/behavior/aggregate_column code], [browser:branches/1.5/test/testsuite/generator/behavior/aggregate_column unit tests], and [wiki:Documentation/1.5/Behaviors/aggregate_column documentation] are all ready to help you to further understand the power of Propel's behavior system. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/guide/01-Installation.txt b/airtime_mvc/library/propel/docs/guide/01-Installation.txt deleted file mode 100644 index f5ca02442..000000000 --- a/airtime_mvc/library/propel/docs/guide/01-Installation.txt +++ /dev/null @@ -1,164 +0,0 @@ -= Installing Propel = - -[[PageOutline]] - -Propel is available as a [http://pear.php.net/manual/en/installation.getting.php PEAR] package, as a "traditional" tgz or zip package, and as a checkout from a Subversion repository. Whatever installation method you may choose, getting Propel to work is pretty straightforward. - -== Prerequisites == - -Propel requirements are very light, allowing it to run on most PHP platforms: - - * [http://www.php.net/ PHP 5.2.4] or newer, with the DOM (libxml2) module enabled - * A supported database (MySQL, MS SQL Server, PostgreSQL, SQLite, Oracle) - -'''Tip''': Propel uses the PDO and SPL components, which are bundled and enabled by default in PHP5. - -== Propel Components == - -The Propel library is made of two components: a '''generator''', and a '''runtime library'''. These components are not co-dependent, and can be installed independently from each other. - -The generator is needed to build the object model, but is not required for running applications that use Propel. - -The runtime classes provide the shared functionality that is used by the Propel-generated object model classes. These are necessary to run applications that use Propel to access the database. - -Usually, both the generator and the runtime components are installed on development environments, while the actual test or production servers need only the runtime components installed. For your first contact with Propel, just install both. - -== Installing Propel == - -=== Installing Propel From PEAR === - -In order to install the Propel packages, you must add the `pear.propelorm.org` channel to your PEAR environment. Once the channel is discovered, you can install the generator package, or the runtime package, or both. Use the '-a' option to let PEAR download and install dependencies. - -{{{ -#!sh -> pear channel-discover pear.propelorm.org -> pear install -a propel/propel_generator -> pear install -a propel/propel_runtime -}}} - -Propel is now installed, and you can test it by following the instructions of the '''Testing Propel Installation''' section at the end of this page. - -Tip: If you want to install non-stable versions of Propel, change your `preferred_state` PEAR environment variable before installoing the Propel packages. Valid states include 'stable', 'beta', 'alpha', and 'devel': - -{{{ -#!sh -> pear config-set preferred_state beta -}}} - -=== Dependencies for Tarball and Subversion Versions === - -The Propel generator uses [http://phing.info/ Phing 2.3.3] to manage command line tasks; both the generator and the runtime classes use [http://pear.php.net/package/Log/ PEAR Log] to log events. - -If you choose to install Propel via PEAR, these components will be automatically installed as dependencies. If you choose to install Propel from a tarball or a Subversion checkout, you'll have to install them manually: - -{{{ -#!sh -> pear channel-discover pear.phing.info -> pear install phing/phing -> pear install Log -}}} - -Refer to their respective websites for alternative installation strategies for Phing and Log. - -=== Installing Propel From Subversion === - -Installing from SVN trunk ensures that you have the most up-to-date source code. - -{{{ -#!sh -> svn checkout http://svn.propelorm.org/branches/1.5 /usr/local/propel -}}} - -This will export both the generator and runtime components to your local `propel` directory. In addition, you'll also get Propel documentation and unit tests - that's why this method is the preferred installation method for Propel contributors. - -Once this is done, you'll need to setup your PHP environment to use this library - see the '''Setting Up PHP for Propel''' section below. - -Note: `branches/1.5` is currently more uptodate code than `trunk`; trunk is what will become 2.0, however it has had very little work done to it in a long time. - -=== Installing Propel From a Tarball === - -Download a tarball of each of the Propel components from the Propel website, and uncompress them into the location that best suits your need. For instance, in Linux: - -{{{ -#!sh -> cd /usr/local -> mkdir propel -> cd propel -> wget http://pear.propelorm.org/get/propel_generator-1.5.0.tgz -> tar zxvf propel_generator-1.5.0.tgz -> wget http://pear.propelorm.org/get/propel_runtime-1.5.0.tgz -> tar zxvf propel_runtime-1.5.0.tgz -}}} - -Once this is done, you'll need to setup your PHP environment to use this library. - -== Setting Up PHP for the Propel Generator == - -The following instructions are only required if you installed Propel from a tarball, or from Subversion. - -The Propel generator component bundles a `propel-gen` sh script (and a `propel-gen.bat` script for Windows). This script simplifies the commandline invocation of the Propel generator by hiding any references to Phing. - -You can call it directly from the command line: - -{{{ -#!sh -> /usr/local/propel/generator/bin/propel-gen -}}} - -In order to allow an easier execution the script, you can also: - - * add the propel generator's `bin/` directory to your PATH, - * or copy the `propel-gen` script to a location on your PAH, - * or (on Linux systems) create a symlink. For example: - -{{{ -#!sh -> cd /usr/local/bin -> ln -s /usr/local/propel/generator/bin/propel-gen propel-gen -}}} - -== Testing Propel Installation == - -You can test that the '''Propel generator''' component is properly installed by calling the `propel-gen` script from the CLI: - -{{{ -#!sh -> propel-gen -}}} - -The script should output a few lines before displaying a 'BUILD FAILED' message, which is normal - you haven't defined a database model yet. - -You can test that the '''Propel runtime''' component is properly installed by requiring the `Propel.php` script, as follows: - -{{{ -#!php -` tag: - -{{{ -#!xml - - - - -}}} - -The `name` attribute defines the name of the connection that Propel uses for the tables in this schema. It is not necessarily the name of the actual database. In fact, Propel uses a second file to link a connection name with real connection settings (like databae name, user and password). This `runtime-conf.xml` file will be explained later in this chapter. - -The `defaultIdMethod` attribute indicates that the tables in this schema use the database's "native" auto-increment/sequence features to handle id columns that are set to auto-increment. - -'''Tip''': You can define several schemas for a single project. Just make sure that each of the schema filenames end with `schema.xml`. - -=== Tables And Columns === - -Within the `` tag, Propel expects one `` tag for each table: - -{{{ -#!xml - - -
- -
- - -
- - -
-
-}}} - -This time, the `name` attributes are the real table names. The `phpName` is the name that Propel will use for the generated PHP class. By default, Propel uses a CamelCase version of the table name as its phpName - that means that you could omit the `phpName` attribute in the example above. - -Within each set of `` tags, define the columns that belong to that table: - -{{{ -#!xml - - -
- - - - - -
- - - - -
- - - -
-
-}}} - -Each column has a `name` (the one used by the database), and an optional `phpName` attribute. Once again, the Propel default behavior is to use a CamelCase version of the `name` as `phpName` when not specified. - -Each column also requires a `type`. The XML schema is database agnostic, so the column types and attributes are probably not exactly the same as the one you use in your own database. But Propel knows how to map the schema types with SQL types for many database vendors. Existing Propel column types are boolean, tinyint, smallint, integer, bigint, double, float, real, decimal, char, varchar, longvarchar, date, time, timestamp, blob, and clob. Some column types use a `size` (like `varchar` and `int`), some have unlimited size (`longvarchar`, `clob`, `blob`). - -As for the other column attributes, `required`, `primaryKey`, and `autoIncrement`, they mean exactly what their names suppose. - -'''Tip''': Propel supports namespaces (for PHP > 5.3). If you specify a `namespace` attribute in a `` element, the generated PHP classes for this table will use this namespace. - -=== Foreign Keys === - -A table can have several `` tags, describing foreign keys to foreign tables. Each `` tag consists of one or more mappings between a local column and a foreign column. - -{{{ -#!xml - - -
- - - - - - - - - - - -
- - - - -
- - - -
-
-}}} - -A foreign key represents a relationship. Just like a table or a column, a relationship has a `phpName`. By default, Propel uses the `phpName` of the foreign table as the `phpName` of the relation. The `refPhpName` defines the name of the relation as seen from the foreign table. - -There are many more attributes and elements available to describe a datamodel. Propel's documentation provides a complete [wiki:Documentation/1.5/Schema reference of the schema syntax], together with a [source:branches/1.5/generator/resources/dtd/database.dtd DTD] and a [source:branches/1.5/generator/resources/xsd/database.xsd XSD] schema for its validation. - -== Building The Model == - -=== Setting Up Build Configuration === - -The build process is highly customizable. Whether you need the generated classes to inherit one of your classes rather than Propel's base classes, or to enable/disable some methods in the generated classes, pretty much every customization is possible. Of course, Propel provides sensible defaults, so that you actually need to define only two settings for the build process to start: the RDBMS you are going to use, and a name for your project. - -Propel expects the build configuration to be stored in a file called `build.properties`, and stored at the same level as the `schema.xml`. Here is an example for a MySQL database: - -{{{ -#!ini -# Database driver -propel.database = mysql - -# Project name -propel.project = bookstore -}}} - -Use your own database vendor driver, chosen among pgsql, mysql, sqlite, mssql, and oracle. - -You can learn more about the available build settings and their possible values in the [wiki:Documentation/1.5/BuildConfiguration build configuration reference]. - -=== Using the `propel-gen` Script To Build The Model === - -The Propel generator uses the `propel-gen` script, as seen in the previous chapter. This executable expects a command name as its argument. - -Open a terminal and browse to the `bookstore/` directory, where you saved the two previous files (`schema.xml`, and `build.properties`). Then use the `propel-gen` script to call the "Object Model generator" command using its shortcut - "om": - -{{{ -> cd /path/to/bookstore -> propel-gen om -}}} - -You should normally see a some colored lines appear in the terminal, logging all the class generation, and ending with "BUILD FINISHED". If not, look for red lines in the log and follow the directions in the error messages. - -=== Generated Object Model === - -The "om" command added a new directory in the `bookstore/` project, called `build/`. The generated model classes are located under the `classes/bookstore/` subdirectory: - -{{{ -> cd /path/to/bookstore -> cd build/classes/bookstore/ -> ls - om/ - map/ - Author.php - AuthorPeer.php - AuthorQuery.php - Book.php - BookPeer.php - BookQuery.php - Publisher.php - PublisherPeer.php - PublisherQuery.php -}}} - -For every table in the database, Propel creates 3 PHP classes: - - * a ''model'' class (e.g. `Book`), which represents a row in the database; - * a ''peer'' class (e.g. `BookPeer`), offering static constants and methods mostly for compatibility with previous Propel versions; - * a ''query'' class (e.g. `BookQuery`), used to operate on a table to retrieve and update rows - -Propel uses the `phpName` attribute of each table as the base for the PHP class names. - -All these classes are empty, but they inherit from `Base` classes that you will find under the `om/` directory: - -{{{ -#!php - cd /path/to/bookstore -> propel-gen sql -}}} - -The generated SQL definition can be found in the `build/sql/schema.sql` file. The code is optimized for the database driver defined in the `build.properties`. - -=== Using The SQL File === - -Create the database and setup the access permissions using your favorite database client. For instance, to create the `my_db_name` database with MySQL, type: - -{{{ -> mysqladmin -u root -p create my_db_name -}}} - -Now you can use the generated code directly: - -{{{ -> mysql -u root -p my_db_name < build/sql/schema.sql -}}} - -'''Tip''': The `schema.sql` file will DROP any existing table before creating them, which will effectively erase your database. - -Depending on which RDBMS you are using, it may be normal to see some errors (e.g. "unable to DROP...") when you first run this command. This is because some databases have no way of checking to see whether a database object exists before attempting to DROP it (MySQL is a notable exception). It is safe to disregard these errors, and you can always run the script a second time to make sure that the errors are no longer present. - -=== Inserting SQL With `propel-gen` === - -As an alternative to using the generated sql code directly, you can ask Propel to insert it directly into your database. Start by defining the database connection settings in the `build.properties`, as follows: - -{{{ -# Connection parameters -propel.database.url = mysql:host=localhost;dbname=my_db_name -propel.database.user = my_db_user -propel.database.password = my_db_password - -# Other examples: -# propel.database.url = sqlite:/path/to/bookstore.db -# propel.database.url = pgsql:host=localhost dbname=my_db_name user=my_db_user password=my_db_password -}}} - -The `propel.database.url` setting should be a PDO DSN (see the [http://www.php.net/pdo PDO documentation] for more information about vendor-specific DSN). The `user` and `password` are only necessary for the `mysql` and `oracle` drivers. - -Then use the `propel-gen` script with the "insert-sql" command to connect to the database and inject the generated SQL code: - -{{{ -> cd /path/to/bookstore -> propel-gen insert-sql -}}} - -== Runtime Connection Settings == - -The database and PHP classes are now ready to be used. But they don't know yet how to communicate with each other at runtime. You must add a configuration file so that the generated object model classes and the shared Propel runtime classes can connect to the database, and log the Propel activity. - -=== Writing The XML Runtime Configuration === - -Create a file called `runtime-conf.xml` at the root of the `bookstore` project, using the following content: -{{{ -#!xml - - - - - - - mysql - - mysql:host=localhost;dbname=my_db_name - my_db_user - my_db_password - - - - - -}}} - -Notice how the `id` attribute of the `` tag matches the connection name defined in the `` tag of the `schema.xml`. This is how Propel maps a database description to a connection. - -Replace the `` and the `` settings wit hthe ones of your database. - -See the [wiki:Documentation/1.5/RuntimeConfiguration runtime configuration reference] for a more detailed explanation of this file. - -'''Tip''': If you uncomment the `` section, Propel will attempt to instantiate the `Log` class (from the [http://pear.php.net/package/Log/ PEAR Log] package) with the specified parameters and use that to log queries. Propel's statement logging happens at the DEBUG level (7); errors and warnings are logged at the appropriate (non-debug) level. - -=== Building the Runtime Configuration === - -For performance reasons, Propel prefers to use a PHP version of the connection settings rather than the XML file you just defined. So you must use the `propel-gen` script one last time to build the PHP version of the `runtime-conf.xml` configuration: - -{{{ -> cd /path/to/bookstore -> propel-gen convert-conf -}}} - -The resulting file can be found under `build/conf/bookstore-conf.php`, where "bookstore" is the name of the project you defined in `build.properties`. - -'''Tip''': As you saw, a Propel project setup requires that you call three commands with the `propel-gen` script: `om`, `sql`, and `convert-conf`. This is so usual that if you call the `propel-gen` script with no parameter, it will execute these three commands in a row: - -{{{ -> cd /path/to/bookstore -> propel-gen -}}} - -== Setting Up Propel == - -This is the final step: initialize Propel in your PHP script. You may wish to do this step in an init or setup script that is included at the beginning of your PHP scripts. - -Here is a sample initialization file: - -{{{ -#!php -setFirstName('Jane'); -$author->setLastName('austen'); -$author->save(); -}}} - -The column names used in the `setXXX()` methods correspond to the `phpName` attribute of the `` tag in your schema, or to a CamelCase version of the column name if the `phpName` is not set. - -In the background, the call to `save()` results in the following SQL being executed on the database: -{{{ -#!sql -INSERT INTO author (first_name, last_name) VALUES ('Jane', 'Austen'); -}}} - -== Reading Object Properties == - -Propel maps the columns of a table into properties of the generated objects. For each property, you can use a generated getter to access it. - -{{{ -#!php -getId(); // 1 -echo $author->getFirstName(); // 'Jane' -echo $author->getLastName(); // 'austen' -}}} - -The `id` column was set automatically by the database, since the `schema.xml` defines it as an `autoIncrement` column. The value is very easy to retrieve once the object is saved: just call the getter on the column phpName. - -These calls don't issue a database query, since the `Author` object is already loaded in memory. - -== Retrieving Rows == - -Retrieving objects from the database, also referred to as ''hydrating'' objects, is essentially the process of executing a SELECT query against the database and populating a new instance of the appropriate object with the contents of each returned row. - -In Propel, you use the generated Query objects to select existing rows from the database. - -=== Retrieving by Primary Key === - -The simplest way to retrieve a row from the database, is to use the generated `findPK()` method. It simply expects the value of the primary key of the row to be retrieved. - -{{{ -#!php -findPK(1); -// now $firstBook is an Author object, or NULL if no match was found. -}}} - -This issues a simple SELECT SQL query. For instance, for MySQL: - -{{{ -#!sql -SELECT author.id, author.first_name, author.last_name -FROM `author` -WHERE author.id = 1 -LIMIT 1; -}}} - -When the primary key consists of more than one column, `findPK()` accepts multiple parameters, one for each primary key column. - -'''Tip''': Every generated Query objects offers a factory method called `create()`. This methods creates a new instance of the query, and allows you to write queries in a single line: - -{{{ -#!php -findPK(1); -}}} - -You can also select multiple objects based on their primary keys, by calling the generated `findPKs()` method. It takes an array of primary keys as a parameter: - -{{{ -#!php -findPKs(array(1,2,3,4,5,6,7)); -// $selectedAuthors is a collection of Author objects -}}} - -=== Querying the Database === - -To retrieve rows other than by the primary key, use the Query's `find()` method. - -An empty Query object carries no condition, and returns all the rows of the table -{{{ -#!php -find(); -// $authors contains a collection of Author objects -// one object for every row of the author table -foreach($authors as $author) { - echo $author->getFirstName(); -} -}}} - -To add a simple condition on a given column, use one of the generated `filterByXXX()` methods of the Query object, where `XXX` is a column phpName. Since `filterByXXX()` methods return the current query object, you can continue to add conditions or end the query with the result of the method call. For instance, to filter by first name: - -{{{ -#!php -filterByFirstName('Jane') - ->find(); -}}} - -When you pass a value to a `filterByXXX()` method, Propel uses the column type to escape this value in PDO. This protects you from SQL injection risks. - -You can also easily limit and order the results on a query. Once again, the Query methods return the current Query object, so you can easily chain them: - -{{{ -#!php -orderByLastName() - ->limit(10) - ->find(); -}}} - -`find()` always returns a collection of objects, even if there is only one result. If you know that you need a single result, use `findOne()` instead of `find()`. It will add the limit and return a single object instead of an array: - -{{{ -#!php -filterByFirstName('Jane') - ->findOne(); -}}} - -'''Tip''': Propel provides magic methods for this simple use case. So you can write the above query as: - -{{{ -#!php -findOneByFirstName('Jane'); -}}} - -The Propel Query API is very powerful. The next chapter will teach you to use it to add conditions on related objects. If you can't wait, jump to the [wiki:Documentation/1.5/ModelCriteria Query API reference]. - -=== Using Custom SQL === - -The `Query` class provides a relatively simple approach to constructing a query. Its database neutrality and logical simplicity make it a good choice for expressing many common queries. However, for a very complex query, it may prove more effective (and less painful) to simply use a custom SQL query to hydrate your Propel objects. - -As Propel uses PDO to query the underlying database, you can always write custom queries using the PDO syntax. For instance, if you have to use a sub-select: - -{{{ -#!php -prepare($sql); -$stmt->execute(array(':name' => 'Tolstoy'); -}}} - -With only a little bit more work, you can also populate `Book` objects from the resulting statement. Create a new `PropelObjectCollection` for the `Book` model, and call the `format()` method using the statement: - -{{{ -#!php -setModelName('Book'); -$books = $coll->format($stmt); -// $books contains a collection of Book objects -}}} - -There are a few important things to remember when using custom SQL to populate Propel: - * The resultset columns must be numerically indexed - * The resultset must contain all columns in the object - * The resultset must have columns ''in the same order'' as they are defined in the `schema.xml` file - -== Updating Objects == - -Updating database rows basically involves retrieving objects, modifying the contents, and then saving them. In practice, for Propel, this is a combination of what you've already seen in the previous sections: - -{{{ -#!php -findOneByFirstName('Jane'); -$author->setLastName('Austen'); -$author->save(); -}}} - -Alternatively, you can update several rows based on a Query using the query object's `update()` method: - -{{{ -#!php -filterByFirstName('Jane') - ->update(array('LastName' => 'Austen')); -}}} - -This last method is better for updating several rows at once, or if you didn't retrieve the objects before. - -== Deleting Objects == - -Deleting objects works the same as updating them. You can either delete an existing object: - -{{{ -#!php -findOneByFirstName('Jane'); -$author->delete(); -}}} - -Or use the `delete()` method in the query: - -{{{ -#!php -filterByFirstName('Jane') - ->delete(); -}}} - -'''Tip''': A deleted object still lives in the PHP code. It is marked as deleted and cannot be saved anymore, but you can still read its properties: - -{{{ -#!php -isDeleted(); // true -echo $author->getFirstName(); // 'Jane' -}}} - -== Termination Methods == - -The Query methods that don't return the current query object are called "Termination Methods". You've alread seen come of them: `find()`, `findOne()`, `update()`, `delete()`. There are two more termination methods that you should know about: - -{{{ -#!php -count(); -// You could also count the number of results from a find(), but that would be less effective, -// since it implies hydrating objects just to count them - -// paginate() returns a paginated list of results -$authorPager = AuthorQuery::create()->paginate($page = 1, $maxPerPage = 10); -// This method will compute an offset and a limit -// based on the number of the page and the max number of results per page. -// The result is a PropelModelPager object, over which you can iterate: -foreach ($authorPager as $author) { - echo $author->getFirstName(); -} -// a pager object gives more information -echo $pager->getNbResults(); // total number of results if not paginated -echo $pager->haveToPaginate(); // return true if the total number of results exceeds the maximum per page -echo $pager->getFirstIndex(); // index of the first result in the page -echo $pager->getLastIndex(); // index of the last result in the page -$links = $pager->getLinks(5); // array of page numbers around the current page; useful to display pagination controls -}}} - -== Collections And On-Demand Hydration == - -The `find()` method of generated Model Query objects returns a `PropelCollection` object. You can use this object just like an array of model objects, iterate over it using `foreach`, access the objects by key, etc. - -{{{ -#!php -limit(5) - ->find(); -foreach ($authors as $author) { - echo $authors->getFirstName(); -} -}}} - -The advantage of using a collection instead of an array is that Propel can hydrate model objects on demand. Using this feature, you'll never fall short of memory when retrieving a large number of results. Available through the `setFormatter()` method of Model Queries, on-demand hydration is very easy to trigger: - -{{{ -#!php -limit(50000) - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) // just add this line - ->find(); -foreach ($authors as $author) { - echo $author->getFirstName(); -} -}}} - -In this example, Propel will hydrate the `Author` objects row by row, after the `foreach` call, and reuse the memory between each iteration. The consequence is that the above code won't use more memory when the query returns 50,000 results than when it returns 5. - -`ModelCriteria::FORMAT_ON_DEMAND` is one of the many formatters provided by the Query objects. You can also get a collection of associative arrays instead of objects, if you don't need any of the logic stored in your model object, by using `ModelCriteria::FORMAT_ARRAY`. - -The [wiki:Documentation/1.5/ModelCriteria Query API reference] describes each formatter, and how to use it. - -== Propel Instance Pool == - -Propel keeps a list of the objects that you already retrieved in memory to avoid calling the same request twice in a PHP script. This list is called the instance pool, and is automatically populated from your past requests: - -{{{ -#!php -findPk(1); -// Issues a SELECT query -... -// second call -$author2 = AuthorQuery::create()->findPk(1); -// Skips the SQL query and returns the existing $author1 object -}}} diff --git a/airtime_mvc/library/propel/docs/guide/04-Relationships.txt b/airtime_mvc/library/propel/docs/guide/04-Relationships.txt deleted file mode 100644 index 6e5de3c68..000000000 --- a/airtime_mvc/library/propel/docs/guide/04-Relationships.txt +++ /dev/null @@ -1,386 +0,0 @@ -= Basic Relationships = - -[[PageOutline]] - -The definition of foreign keys in your schema allows Propel to add smart methods to the generated model and query objects. In practice, these generated methods mean that you will never actually have to deal with primary and foreign keys yourself. It makes the task of dealing with relations extremely straightforward. - -== Inserting A Related Row == - -Propel creates setters for related objects that simplify the foreign key handling. You don't actually have to define a foreign key value. Instead, just set a related object, as follows: - -{{{ -#!php -setFirstName("Leo"); -$author->setLastName("Tolstoy"); -$author->save(); - -$book = new Book(); -$book->setTitle("War & Peace"); -// associate the $author object with the current $book -$book->setAuthor($author); -$book->save(); -}}} - -Propel generates the `setAuthor()` method based on the `phpName` attribute of the `` element in the schema. When the attribute is not set, Propel uses the `phpName` of the related table instead. - -Internally, the call to `Book::setAuthor($author)` translates into `Book::setAuthorId($author->getId())`. But you don't actually have to save a Propel object before associating it to another. In fact, Propel automatically "cascades" INSERT statements when a new object has other related objects added to it. - -For one-to-many relationships - meaning, from the other side of a many-to-one relationship - the process is a little different. In the previous example, one `Book` has one `Author`, but one `Author` has many `Books`. From the `Author` point of view, a one-to-many relationships relates it to `Book`. So Propel doesn't generate an `Author::setBook()`, but rather an `Author::addBook()`: - -{{{ -#!php -setTitle("War & Peace"); -// associate the $author object with the current $book -$book->save(); - -$author = new Author(); -$author->setFirstName("Leo"); -$author->setLastName("Tolstoy"); -$author->addBook($book); -$author->save(); -}}} - -The result is the same in the database - the `author_id` column of the `book` row is correctly set to the `id` of the `author` row. - -== Save Cascade == - -As a matter of fact, you don't need to `save()` an object before relating it. Propel knows which objects are related to each other, and is capable of saving all the unsaved objects if they are related to each other. - -The following example shows how to create new `Author` and `Publisher` objects, which are then added to a new `Book` object; all 3 objects are saved when the `Book::save()` method is eventually invoked. - -{{{ -#!php -setFirstName("Leo"); -$author->setLastName("Tolstoy"); -// no need to save the author yet - -$publisher = new Publisher(); -$publisher->setName("Viking Press"); -// no need to the publisher yet - -$book = new Book(); -$book->setTitle("War & Peace"); -$book->setIsbn("0140444173"); -$book->setPublisher($publisher); -$book->setAuthor($author); -$book->save(); // saves all 3 objects! -}}} - -In practice, Propel '''cascades''' the `save()` action to the related objects. - -== Reading Related Object Properties == - -Just like the related object setters, Propel generates a getter for every relation: - -{{{ -#!php -findPk(1); -$author = $book->getAuthor(); -echo $author->getFirstName(); // 'Leo' -}}} - -Since a relationship can also be seen from the other end, Propel allows the foreign table to retrieve the related objects as well: - -{{{ -#!php -findPk(1); -$books = $author->getBooks(); -foreach ($books as $book) { - echo $book->getTitle(); -} -}}} - -Notice that Propel generated a `getBooks()` method returning an array of `Book` objects, rather than a `getBook()` method. This is because the definition of a foreign key defines a many-to-one relationship, seen from the other end as a one-to-many relationship. - -'''Tip''': Propel also generates a `countBooks()` methods to get the number of related objects without hydrating all the `Book` objects. for performance reasons, you should prefer this method to `count($author->getBooks())`. - -Getters for one-to-many relationship accept an optional query object. This allows you to hydrate related objects, or retrieve only a subset of the related objects, or to reorder the list of results: - -{{{ -#!php -orderByTitle() - ->joinWith('Book.Publisher'); -$books = $author->getBooks($query); -}}} - -== Using Relationships In A Query == - -=== Finding Records Related To Another One === - -If you need to find objects related to a model object that you already have, you can take advantage of the generated `filterByXXX()` methods in the query objects, where `XXX` is a relation name: - -{{{ -#!php -findPk(1); -$books = BookQuery::create() - ->filterByAuthor($author) - ->orderByTitle() - ->find(); -}}} - -You don't need to specify that the `author_id` column of the `Book` object should match the `id` column of the `Author` object. Since you already defined the foreign key mapping in your schema, Propel knows enough to figure it out. - -=== Embedding Queries === - -In SQL queries, relationships often translate to a JOIN statement. Propel abstracts this relational logic in the query objects, by allowing you to ''embed'' a related query into another. - -In practice, Propel generates one `useXXXQuery()` method for every relation in the Query objects. So the `BookQuery` class offers a `useAuthorQuery()` and a `usePublisherQuery()` method. These methods return a new Query instance of the related query class, that you can eventually merge into the main query by calling `endUse()`. - -To illustrate this, let's see how to write the following SQL query with the Propel Query API: - -{{{ -#!sql -SELECT book.* -FROM book INNER JOIN author ON book.AUTHOR_ID = author.ID -WHERE book.ISBN = '0140444173' AND author.FIRST_NAME = 'Leo' -ORDER BY book.TITLE ASC -LIMIT 10; -}}} - -That would simply give: - -{{{ -#!php -filterByISBN('0140444173') - ->useAuthorQuery() // returns a new AuthorQuery instance - ->filterByFirstName('Leo') // this is an AuthorQuery method - ->endUse() // merges the Authorquery in the main Bookquery and returns the BookQuery - ->orderByTitle() - ->limit(10) - ->find(); -}}} - -Propel knows the columns to use in the `ON` clause from the definition of foreign keys in the schema. The ability to use methods of a related Query object allows you to keep your model logic where it belongs. - -Of course, you can embed several queries to issue a query of any complexity level: - -{{{ -#!php -useBookQuery() - ->usePublisherQuery() - ->filterByName('Viking Press') - ->endUse() - ->endUse() - ->find(); -}}} - -You can see how the indentation of the method calls provide a clear explanation of the embedding logic. That's why it is a good practice to format your Propel queries with a single method call per line, and to add indentation every time a `useXXXQuery()` method is used. - -== Many-to-Many Relationships == - -Databases typically use a cross-reference table, or junction table, to materialize the relationship. For instance, if the `user` and `group` tables are related by a many-to-many relationship, this happens through the rows of a `user_group` table. To inform Propel about the many-to-many relationship, set the `isCrossRef` attribute of the cross reference table to true: - -{{{ -#!xml - - - -
- - - - -
- - - - - - - - - - -
-}}} - -Once you rebuild your model, the relationship is seen as a one-to-many relationship from both the `User` and the `Group` models. That means that you can deal with adding and reading relationships the same way as you usually do: - -{{{ -#!php -setName('John Doe'); -$group = new Group(); -$group->setName('Anonymous'); -// relate $user and $group -$user->addGroup($group); -// save the $user object, the $group object, and a new instance of the UserGroup class -$user->save(); -}}} - -The same happens for reading related objects ; Both ends see the relationship as a one-to-many relationship: - -{{{ -#!php -getUsers(); -$nbUsers = $group->countUsers(); -$groups = $user->getGroups(); -$nbGroups = $user->countGroups(); -}}} - -Just like regular related object getters, these generated methods accept an optional query object, to further filter the results. - -To facilitate queries, Propel also adds new methods to the `UserQuery` and `GroupQuery` classes: - -{{{ -#!php -filterByGroup($group) - ->find(); -$groups = GroupQuery::create() - ->filterByUser($user) - ->find(); -}}} - -== One-to-One Relationships == - -Propel supports the special case of one-to-one relationships. These relationships are defined when the primary key is also a foreign key. For example : - -{{{ -#!xml - - - -
- - - - - - - - -
-}}} - -Because the primary key of the `bookstore_employee_account` is also a foreign key to the `bookstore_employee` table, Propel interprets this as a one-to-one relationship and will generate singular methods for both sides of the relationship (`BookstoreEmployee::getBookstoreEmployeeAccount()`, and `BookstoreEmployeeAccount::getBookstoreEmployee()`). - -== On-Update and On-Delete Triggers = - -Propel also supports the ''ON UPDATE'' and ''ON DELETE'' aspect of foreign keys. These properties can be specified in the `` tag using the `onUpdate` and `onDelete` attributes. Propel supports values of `CASCADE`, `SETNULL`, and `RESTRICT` for these attributes. For databases that have native foreign key support, these trigger events will be specified at the datbase level when the foreign keys are created. For databases that do not support foreign keys, this functionality will be emulated by Propel. - -{{{ -#!xml - - - - - - - -
-}}} - -In the example above, the `review` rows will be automatically removed if the related `book` row is deleted. - -== Minimizing Queries == - -Even if you use a foreign query, Propel will issue new queries when you fetch related objects: - -{{{ -#!php -useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->findOne(); -$author = $book->getAuthor(); // Needs another database query -}}} - -Propel allows you to retrieve the main object together with related objects in a single query. You just the `with()` method to specify which objects the main object should be hydrated with. - -{{{ -#!php -useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->with('Author') - ->findOne(); -$author = $book->getAuthor(); // Same result, with no supplementary query -}}} - -Since the call to `with()` adds the columns of the related object to the SELECT part of the query, and uses these columns to populate the related object, that means that a query using `with()` is slower and consumes more memory. So use it only when you actually need the related objects afterwards. - -If you don't want to add a filter on a related object but still need to hydrate it, calling `useXXXQuery()`, `endUse()`, and then `with()` can be a little cumbersome. For this case, Propel provides a proxy method called `joinWith()`. It expects a string made of the initial query name and the foreign query name. For instance: - -{{{ -#!php -joinWith('Book.Author') - ->findOne(); -$author = $book->getAuthor(); // Same result, with no supplementary query -}}} - -`with()` and `joinWith()` are not limited to immediate relationships. As a matter of fact, just like you can nest `use()` calls, you can call `with()` several times to populate a chain of objects: - -{{{ -#!php -joinWith('Review.Book') - ->joinWith('Book.Author') - ->joinWith('Book.Publisher') - ->findOne(); -$book = $review->getBook() // No additional query needed -$author = $book->getAuthor(); // No additional query needed -$publisher = $book->getPublisher(); // No additional query needed -}}} - -So `with()` is very useful to minimize the number of database queries. As soon as you see that the number of queries necessary to perform an action is proportional to the number of results, adding a `with()` call is the trick to get down to a more reasonnable query count. - -'''Tip''': `with()` also works for left joins on one-to-many relationships, but you musn't use a `limit()` in the query in this case. This is because Propel has no way to determine the actual number of rows of the main object in such a case. - -{{{ -#!php -leftJoinWith('Author.Book') - ->find(); -// this does not work -$authors = AuthorQuery::create() - ->leftJoinWith('Author.Book') - ->limit(5) - ->find(); -}}} - -However, it is quite easy to achieve hydration of related objects with only one additional query: - -{{{ - #!php -find(); -$authors->populateRelation('Book'); -// now you can iterate over each author's book without further queries -foreach ($authors as $author) { - foreach ($authors->getBooks() as $book) { // no database query, the author already has a Books collection - // do stuff with $book and $author - } -} -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/guide/05-Validators.txt b/airtime_mvc/library/propel/docs/guide/05-Validators.txt deleted file mode 100644 index 352ea6e1d..000000000 --- a/airtime_mvc/library/propel/docs/guide/05-Validators.txt +++ /dev/null @@ -1,253 +0,0 @@ -= Validators = - -[[PageOutline]] - -Validators help you to validate an input before perstisting it to the database. In Propel, validators are rules describing what type of data a column accepts. Validators are referenced in the `schema.xml` file, using `` tags. - -Validators are applied at the PHP level, they are not created as constraints on the database itself. That means that if you also use another language to work with the database, the validator rules will not be enforced. -You can also apply multiple rule entries per validator entry in the schema.xml file. - -== Overview == - -In the following example, the `username` column is defined to have a minimum length of 4 characters: - -{{{ -#!xml - - - - - - -
-}}} - -Every column rule is represented by a `` tag. A `` is a set of `` tags bound to a column. - -At runtime, you can validate an instance of the model by calling the `validate()` method: - -{{{ -#!php -setUsername("foo"); // only 3 in length, which is too short... -if ($objUser->validate()) { - // no validation errors, so the data can be persisted - $user->save(); -} else { - // Something went wrong. - // Use the validationFailures to check what - $failures = $objUser->getValidationFailures(); - foreach($failures as $failure) { - echo $objValidationFailure->getMessage() . "
\n"; - } -} -}}} - -`validate()` returns a boolean. If the validation failed, you can access the array `ValidationFailed` objects by way of the `getValidationFailures()` method. Each `ValidationFailed` instance gives access to the column, the messagen and the validator that caused the failure. - -== Core Validators == - -Propel bundles a set of validatorts that should help you deal with the most common cases. - -=== !MatchValidator === - -The `MatchValidator` is used to run a regular expression of choice against the column. Note that this is a `preg`, not `ereg` (check [http://www.php.net/preg_match the preg_match documentation] for more information about regexps). - -{{{ -#!xml - - - - -}}} - -=== !NotMatchValidator === - -Opposite of `MatchValidator, this validator returns false if the regex returns true - -{{{ -#!xml - - - - - -}}} - -=== !MaxLengthValidator === - -When you want to limit the size of the string to be inserted in a column, use the `MaxLengthValidator`. Internally, it uses `strlen()` to get the length of the string. For instance, some database completely ignore the lentgh of `LONGVARCHAR` columns; you can enforce it using a validator: - -{{{ -#!xml - - - - -}}} - -'''Tip''': If you have specified the `size` attribute in the `` tag, you don't have to specify the `value` attribute in the validator rule again, as this is done automatically. - -=== !MinLengthValidator === - -{{{ -#!xml - - - - -}}} - -=== !MaxValueValidator === - -To limit the value of an integer column, use the `MaxValueValidator`. Note that this validator uses a non-strict comparison ('less than or equal'): - -{{{ -#!xml - - - - -}}} - -=== !MinValueValidator === - -{{{ -#!xml - - - - -}}} - -'''Tip''': You can run multiple validators against a single column. - -{{{ -#!xml - - - - - -}}} - -=== !RequiredValidator === - -This validtor checks the same rule as a `required=true` on the column at the database level. However it will not give you a clean error to work with. - -{{{ -#!xml - - - - -}}} - -=== !UniqueValidator === - -To check whether the value already exists in the table, use the `UniqueValidator`: - -{{{ -#!xml - - - - -}}} - -=== !ValidValuesValidator === - -This rule restricts the valid values to a list delimited by a pipe ('|'). - -{{{ -#!xml - - - - -}}} - -=== !TypeValidator === - -Restrict values to a certain PHP type using the `TypeValidator`: - -{{{ -#!xml - - - - -}}} - -== Adding A Custom Validator == - -You can easily add a custom validator. A validator is a class extending `BasicValidator` providing a public `isValid()` method. For instance: - -{{{ -#!php -` tag. So `$map->getValue()` returns the `value` attribute. - -'''Tip''': Make sure that `isValid()` returns a boolean, so really true or false. Propel is very strict about this. Returning a mixed value just won't do. - -To enable the new validator on a column, add a corresponding `` in your schema and use 'class' as the rule `name`. - -{{{ -#!xml - - - -}}} - -The `class` attribute of the `` tag should contain a path to the validator class accessible from the include_path, where the directory separator is replaced by a dot. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/guide/06-Transactions.txt b/airtime_mvc/library/propel/docs/guide/06-Transactions.txt deleted file mode 100644 index 55a9240cc..000000000 --- a/airtime_mvc/library/propel/docs/guide/06-Transactions.txt +++ /dev/null @@ -1,291 +0,0 @@ -= Transactions = - -[[PageOutline]] - -Database transactions are the key to assure the data integrity and the performance of database queries. Propel uses transactions internally, and provides a simple API to use them in your own code. - -'''Tip''': If the [http://en.wikipedia.org/wiki/ACID ACID] acronym doesn't ring a bell, you should probably learn some [http://en.wikipedia.org/wiki/Database_transaction fundamentals about database transactions] before reading further. - -== Wrapping Queries Inside a Transaction == - -Propel uses PDO as database abstraction layer, and therefore uses [http://www.php.net/manual/en/pdo.transactions.php PDO's built-in support for database transactions]. The syntax is the same, as you can see in the classical "money transfer" example: - -{{{ -#!php -beginTransaction(); - - try { - // remove the amount from $fromAccount - $fromAccount->setValue($fromAccount->getValue() - $amount); - $fromAccount->save($con); - // add the amount to $toAccount - $toAccount->setValue($toAccount->getValue() + $amount); - $toAccount->save($con); - - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - throw $e; - } -} -}}} - -The transaction statements are `beginTransaction()`, `commit()` and `rollback()`, which are methods of the PDO connection object. Transaction methods are typically used inside a `try/catch` block. The exception is rethrown after rolling back the transaction: That ensures that the user knows that something wrong happenned. - -In this example, if something wrong happens while saving either one of the two accounts, an `Exception` is thrown, and the whole operation is rolled back. That means that the transfer is cancelled, with an insurance that the money hasn't vanished (that's the A in ACID, which stands for "Atomicity"). If both account modifications work as expected, the whole transaction is committed, meaning that the data changes enclosed in the transaction are persisted in the database. - -Tip: In order to build a transaction, you need a connection object. The connection object for a Propel model is always available through `Propel::getConnection([ModelName]Peer::DATABASE_NAME)`. - -== Denormalization And Transactions == - -Another example of the use of transactions is for [http://en.wikipedia.org/wiki/Denormalization denormalized schemas]. - -For instance, suppose that you have an `Author` model with a one to many relationship to a `Book` model. every time you need to display the number of books written by an author, you call `countBooks()` on the author object, which issues a new query to the database: - -{{{ -#!php -
    - -
  • getName() ?> (countBooks() ?> books)
  • - -
-}}} - -If you have a large number of authors and books, this simple code snippet can be a real performance blow to your application. The usual way to optimize it is to ''denormalize'' your schema by storing the number of books by each author in a new `nb_books` column, in the `author` table. - -{{{ -#!xml - - - - -
-}}} - -You must update this new column every time you save or delete a `Book` object; this will make write queries a little slower, but read queries much faster. Fortunately, Propel model objects support pre- and post- hooks for the `save()` and `delete()` methods, so this is quite easy to implement: - -{{{ -#!php -updateNbBooks($con); - } - - public function postDelete(PropelPDO $con) - { - $this->updateNbBooks($con); - } - - public function updateNbBooks(PropelPDO $con) - { - $author = $this->getAuthor(); - $nbBooks = $author->countBooks($con); - $author->setNbBooks($nbBooks); - $author->save($con); - } -} -}}} - -The `BaseBook::save()` method wraps the actual database INSERT/UPDATE query inside a transaction, together with any other query registered in a pre- or post- save hook. That means that when you save a book, the `postSave()` code is executed in the same transaction as the actual `$book->save()` method. Everything happens as is the code was the following: - -{{{ -#!php -beginTransaction(); - - try { - // insert/update query for the current object - $this->doSave($con); - - // postSave hook - $author = $this->getAuthor(); - $nbBooks = $author->countBooks($con); - $author->setNbBooks($nbBooks); - $author->save($con); - - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - throw $e; - } - } -} -}}} - -In this example, the `nb_books` column of the `author` table will always we synchronized with the number of books. If anything happens during the transaction, the saving of the book is rolled back, as well as the `nb_books` column update. The transaction serves to preserve data consistency in a denormalized schema ("Consistency" stands for the C in ACID). - -'''Tip''': Check the [wiki:Documentation/1.5/Behaviors behaviors documentation] for details about the pre- and post- hooks in Propel model objects. - -== Nested Transactions == - -Some RDBMS offer the ability to nest transactions, to allow partial rollback of a set of transactions. PDO does not provide this ability at the PHP level; nevertheless, Propel emulates nested transactions for all supported database engines: - -{{{ -#!php -beginTransaction(); - try { - $c = new Criteria(); - $c->add(BookPeer::PRICE, null, Criteria::ISNULL); - BookPeer::doDelete($c, $con); - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - throw $e; - } -} - -function deleteAuthorsWithNoEmail(PropelPDO $con) -{ - $con->beginTransaction(); - try { - $c = new Criteria(); - $c->add(AuthorPeer::EMAIL, null, Criteria::ISNULL); - AuthorPeer::doDelete($c, $con); - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - throw $e; - } -} - -function cleanup(PropelPDO $con) -{ - $con->beginTransaction(); - try { - deleteBooksWithNoPrice($con); - deleteAuthorsWithNoEmail($con); - $con->commit(); - } catch (Exception $e) { - $con->rollback(); - throw $e; - } -} -}}} - -All three functions alter data in a transaction, ensuring data integrity for each. In addition, the `cleanup()` function actually executes two nested transactions inside one main transaction. - -Propel deals with this case by seeing only the outermost transaction, and ignoring the `beginTransaction()`, `commit()` and `rollback()` statements of nested transactions. If nothing wrong happens, then the last `commit()` call (after both `deleteBooksWithNoPrice()` and `deleteAuthorsWithNoEmail()` end) triggers the actual database commit. However, if an exception is thrown in either one of these nested transactions, it is escalated to the main `catch` statement in `cleanup()` so that the entire transaction (starting at the main `beginTransaction()`) is rolled back. - -So you can use transactions everywhere it's necessary in your code, without worrying about nesting them. Propel will always commit or rollback everything altogether, whether the RDBMS supports nested transactions or not. - -'''Tip''': This allows you to wrap all your application code inside one big transaction for a better integrity. - -== Using Transactions To Boost Performance == - -A database transaction has a cost in terms of performance. In fact, for simple data manipulation, the cost of the transaction is more important than the cost of the query itself. Take the following example: - -{{{ -#!php -setTitle($i . ': A Space Odyssey'); - $book->save($con); -} -}}} - -As explained earlier, Propel wraps every save operation inside a transaction. In terms of execution time, this is very expensive. Here is how the above code would translate to MySQL in an InnodDB table: - -{{{ -#!sql -BEGIN; -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'0: A Space Odyssey'); -COMMIT; -BEGIN; -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'1: A Space Odyssey'); -COMMIT; -BEGIN; -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'2: A Space Odyssey'); -COMMIT; -... -}}} - -You can take advantage of Propel's nested transaction capabilities to encapsulate the whole loop inside one single transaction. This will reduce the execution time drastically: - -{{{ -#!php -beginTransaction(); -for ($i=0; $i<2002; $i++) -{ - $book = new Book(); - $book->setTitle($i . ': A Space Odyssey'); - $book->save($con); -} -$con->commit(); -}}} - -The transactions inside each `save()` will become nested, and therefore not translated into actual database transactions. Only the outmost transaction will become a database transaction. So this will translate to MySQL as: - -{{{ -#!sql -BEGIN; -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'0: A Space Odyssey'); -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'1: A Space Odyssey'); -INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'2: A Space Odyssey'); -... -COMMIT; -}}} - -In practice, encapsulating a large amount of simple queries inside a single transaction significantly improves performance. - -Tip: Until the final `commit()` is called, most database engines lock updated rows, or even tables, to prevent any query outside the transaction from seeing the partially committed data (this is how transactions preserve Isolation, which is the I in ACID). That means that large transactions will queue every other queries for potentially a long time. Consequently, use large transactions only when concurrency is not a requirement. - -== Why Is The Connection Always Passed As Parameter? == - -All the code examples in this chapter show the connection object passed a a parameter to Propel methods that trigger a database query: - -{{{ -#!php -setValue($fromAccount->getValue() - $amount); -$fromAccount->save($con); -}}} - -The same code works without explicitely passing the connection object, because Propel knows how to get the right connection from a Model: - -{{{ -#!php -setValue($fromAccount->getValue() - $amount); -$fromAccount->save(); -}}} - -However, it's a good practice to pass the connection explicitely, and for three reasons: - - * Propel doesn't need to look for a connection object, and this results in a tiny boost in performance. - * You can use a specific connection, which is required in distributed (master/slave) environments, in order to distinguish read and write operations. - * Most importantly, transactions are tied to a single connection. You can't enclose two queries using different connections in a single transaction. So it's very useful to identify the connection you want to use for every query, as Propel will throw an exception if you use the wrong connection. - -== Limitations == - - * Currently there is no support for row locking (e.g. `SELECT blah FOR UPDATE`). - * You must rethrow the exception caught in the `catch` statement of nested transactions, otherwise there is a risk that the global rollback doesn't occur. - * True nested transactions, with partial rollback, are only possible in MSSQL, and can be emulated in other RDBMS through savepoints. This feature may be added to Propel in the future, but for the moment, only the outermost PHP transaction triggers a database transaction. - * If you rollback a partially executed transaction and ignore the exception thrown, there are good chances that some of your objects are out of sync with the database. The good practice is to always let a transaction exception escalate until it stops the script execution. - diff --git a/airtime_mvc/library/propel/docs/guide/07-Behaviors.txt b/airtime_mvc/library/propel/docs/guide/07-Behaviors.txt deleted file mode 100644 index fe0025ec1..000000000 --- a/airtime_mvc/library/propel/docs/guide/07-Behaviors.txt +++ /dev/null @@ -1,280 +0,0 @@ -= Behaviors = - -[[PageOutline]] - -Behaviors are a great way to package model extensions for reusability. They are the powerful, versatile, fast, and help you organize your code in a better way. - -== Pre and Post Hooks For `save()` And `delete()` Methods == - -The `save()` and `delete()` methods of your generated objects are easy to override. In fact, Propel looks for one of the following methods in your objects and executes them when needed: - -{{{ -#!php - - ... - - -}}} - -Then, you can force the update of the `created_at` column before every insertion as follows: - -{{{ -#!php -setCreatedAt(time()); - return true; - } -} -}}} - -Whenever you call `save()` on a new object, Propel now executes the `preInsert()` method on this objects and therefore update the `created_at` column: - -{{{ -#!php -setTitle('War And Peace'); -$b->save(); -echo $b->getCreatedAt(); // 2009-10-02 18:14:23 -}}} - -If you implement `preInsert()`, `preUpdate()`, `preSave()` or `preDelete()`, these methods must return a boolean value. This determines whether the action (save or delete) may proceed. - -'''Tip''': Since this feature adds a small overhead to write operations, you can deactivate it completely in your build properties by setting `propel.addHooks` to `false`. - -{{{ -#!ini -# ------------------- -# TEMPLATE VARIABLES -# ------------------- -propel.addHooks = false -}}} - -== Introducing Behaviors == - -When several of your custom model classes end up with similar methods added, it is time to refactor the common code. - -For example, you may want to add the same ability you gave to `Book` to all the other objects in your model. Let's call this the "Timestampable behavior", because then all of your rows have a timestamp marking their creation. In order to achieve this behavior, you have to repeat the same operations on every table. First, add a `created_at` column to the other tables: - -{{{ -#!xml - - ... - -
- - ... - -
-}}} - -Then, add a `preInsert()` hook to the object stub classes: - -{{{ -#!php -setCreatedAt(time()); - } -} - -class Author extends BaseAuthor -{ - public function preInsert() - { - $this->setCreatedAt(time()); - } -} -}}} - -Even if the code of this example is very simple, the repetition of code is already too much. Just imagine a more complex behavior, and you will understand that using the copy-and-paste technique soon leads to a maintenance nightmare. - -Propel offers three ways to achieve the refactoring of the common behavior. The first one is to use a custom builder during the build process. This can work if all of your models share one single behavior. The second way is to use table inheritance. The inherited methods then offer limited capabilities. And the third way is to use Propel behaviors. This is the right way to refactor common model logic. - -Behaviors are special objects that use events called during the build process to enhance the generated model classes. Behaviors can add attributes and methods to both the Peer and model classes, they can modify the course of some of the generated methods, and they can even modify the structure of a database by adding columns or tables. - -For instance, Propel bundles a behavior called `timestampable`, which does exatcly the same thing as described above. But instead of adding columns and methods by hand, all you have to do is to declare it in a `` tag in your `schema.xml`, as follows: - -{{{ -#!xml - - ... - -
- - ... - -
-}}} - -Then rebuild your model, and there you go: two columns, `created_at` and `updated_at`, were automatically added to both the `book` and `author` tables. Besides, the generated `BaseBook` and `BaseAuthor` classes already contain the code necessary to auto-set the current time on creation and on insertion. - -== Bundled Behaviors == - -Propel currently bundles several behaviors. Check the behavior documentation for details on usage: - - * [wiki:Documentation/1.5/Behaviors/aggregate_column aggregate_column] - * [wiki:Documentation/1.5/Behaviors/alternative_coding_standards alternative_coding_standards] - * [wiki:Documentation/1.5/Behaviors/auto_add_pk auto_add_pk] - * [wiki:Documentation/1.5/Behaviors/timestampable timestampable] - * [wiki:Documentation/1.5/Behaviors/sluggable sluggable] - * [wiki:Documentation/1.5/Behaviors/soft_delete soft_delete] - * [wiki:Documentation/1.5/Behaviors/sortable sortable] - * [wiki:Documentation/1.5/Behaviors/nested_set nested_set] - * [wiki:Documentation/1.5/Behaviors/query_cache query_cache] - * And [wiki:Documentation/1.5/Inheritance#ConcreteTableInheritance concrete_inheritance], documented in the Inheritance Chapter even if it's a behavior - -Behaviors bundled with Propel require no further installation and work out of the box. - -== Customizing Behaviors == - -Behaviors often offer some parameters to tweak their effect. For instance, the `timestampable` behavior allows you to customize the names of the columns added to store the creation date and the update date. The behavior customization occurs in the `schema.xml`, inside `` tags nested in the `` tag. So let's set the behavior to use `created_on` instead of `created_at` for the creation date column name (and same for the update date column): - -{{{ -#!xml - - ... - - - - -
-}}} - -If the columns already exist in your schema, a behavior is smart enough not to add them one more time. - -{{{ -#!xml - - ... - - - - - - -
-}}} - -== Using Third-Party Behaviors == - -As a Propel behavior can be packaged into a single class, behaviors are quite easy to reuse and distribute across several projects. All you need to do is to copy the behavior file into your project, and declare it in `build.properties`, as follows: - -{{{ -#!ini -# ---------------------------------- -# B E H A V I O R S E T T I N G S -# ---------------------------------- - -propel.behavior.timestampable.class = propel.engine.behavior.timestampable.TimestampableBehavior -# Add your custom behavior pathes here -propel.behavior.formidable.class = path.to.FormidableBehavior -}}} - -Propel will then find the `FormidableBehavior` class whenever you use the `formidable` behavior in your schema: - -{{{ -#!xml - - ... - - -
-}}} - -'''Tip''': If you use autoloading during the build process, and if the behavior classes benefit from the autoloading, then you don't even need to declare the path to the behavior class. - -== Applying a Behavior To All Tables == - -You can add a `` tag directly under the `` tag. That way, the behavior will be applied to all the tables of the database. - -{{{ -#!xml - - - - ... -
- - ... -
-
-}}} - -In this example, both the `book` and `author` table benefit from the `timestampable` behavior, and therefore automatically update their `created_at` and `updated_at` columns upon saving. - -Going one step further, you can even apply a behavior to all the databases of your project, provided the behavior doesn't need parameters - or can use default parameters. To add a behavior to all databases, simply declare it in the project's `build.properties` under the `propel.behavior.default` key, as follows: - -{{{ -#!ini -propel.behavior.default = soft_delete, timestampable -}}} - -== Writing a Behavior == - -Behaviors can modify their table, and even add another table, by implementing the `modifyTable` method. In this method, use `$this->getTable()` to retrieve the table buildtime model and manipulate it. - -Behaviors can add code to the generated model object by implementing one of the following methods: - -{{{ -objectAttributes() // add attributes to the object -objectMethods() // add methods to the object -preInsert() // add code to be executed before insertion of a new object -postInsert() // add code to be executed after insertion of a new object -preUpdate() // add code to be executed before update of an existing object -postUpdate() // add code to be executed after update of an existing object -preSave() // add code to be executed before saving an object (new or existing) -postSave() // add code to be executed after saving an object (new or existing) -preDelete() // add code to be executed before deleting an object -postDelete() // add code to be executed after deleting an object -objectCall() // add code to be executed inside the object's __call() -objectFilter(&$script) // do whatever you want with the generated code, passed as reference -}}} - -Behaviors can also add code to the generated query objects by implementing one of the following methods: - -{{{ -queryAttributes() // add attributes to the query class -queryMethods() // add methods to the query class -preSelectQuery() // add code to be executed before selection of a existing objects -preUpdateQuery() // add code to be executed before update of a existing objects -postUpdateQuery() // add code to be executed after update of a existing objects -preDeleteQuery() // add code to be executed before deletion of a existing objects -postDeleteQuery() // add code to be executed after deletion of a existing objects -queryFilter(&$script) // do whatever you want with the generated code, passed as reference -}}} - -Behaviors can also add code to the generated peer objects by implementing one of the following methods: - -{{{ -staticAttributes() // add static attributes to the peer class -staticMethods() // add static methods to the peer class -preSelect() // adds code before every select query -peerFilter(&$script) // do whatever you want with the generated code, passed as reference -}}} - -Check the behaviors bundled with Propel to see how to implement your own behavior. diff --git a/airtime_mvc/library/propel/docs/guide/08-Logging.txt b/airtime_mvc/library/propel/docs/guide/08-Logging.txt deleted file mode 100644 index 80445f17d..000000000 --- a/airtime_mvc/library/propel/docs/guide/08-Logging.txt +++ /dev/null @@ -1,448 +0,0 @@ -= Logging And Debugging = - -[[PageOutline]] - -Propel provides tools to monitor and debug your model. Whether you need to check the SQL code of slow queries, or to look for error messages previously thrown, Propel is your best friend for finding and fixing problems. - -== Propel Logs == - -Propel uses the logging facility configured in `runtime-conf.xml` to record errors, warnings, and debug information. - -By default Propel will attempt to use the Log framework that is distributed with PEAR. If you are not familiar with it, check its [http://www.indelible.org/php/Log/guide.html online documentation]. It is also easy to configure Propel to use your own logging framework -- or none at all. - -=== Logger Configuration === - -The Propel log handler is configured in the `` section of your project's `runtime-conf.xml` file. Here is the accepted format for this section with the default values that Propel uses: - -{{{ -#!xml - - - - file - ./propel.log - propel - 7 - - - - ... - - -}}} - -Using these parameters, Propel creates a ''file'' Log handler in the background, and keeps it for later use: - -{{{ -#!php -` nested elements may vary, depending on which log handler you are using. Refer to the [http://www.indelible.org/php/Log/guide.html#standard-log-handlers PEAR::Log] documentation for more details on log handlers configuration and options. - -Note that the `` tag needs to correspond to the integer represented by one of the `PEAR_LOG_*` constants: - -||'''Constant'''||'''Value'''||'''Description''' -||PEAR_LOG_EMERG||0||System is unusable|| -||PEAR_LOG_ALERT||1||Immediate action required|| -||PEAR_LOG_CRIT||2||Critical conditions|| -||PEAR_LOG_ERR||3||Error conditions|| -||PEAR_LOG_WARNING||4||Warning conditions|| -||PEAR_LOG_NOTICE||5||Normal but significant|| -||PEAR_LOG_INFO||6||Informational|| -||PEAR_LOG_DEBUG||7||Debug-level messages|| - -=== Logging Messages === - -Use the static `Propel::log()` method to log a message using the configured log handler: - -{{{ -#!php -setName('foo'); -Propel::log('uh-oh, something went wrong with ' . $myObj->getName(), Propel::LOG_ERROR); -}}} - -You can log your own messages from the generated model objects by using their `log()` method, inherited from `BaseObject`: - -{{{ -#!php -log('uh-oh, something went wrong', Propel::LOG_ERROR); -}}} - -The log messages will show up in the log handler defined in `runtime-conf.xml` (`propel.log` file by default) as follows: - -{{{ -Oct 04 00:00:18 [error] uh-oh, something went wrong with foo -Oct 04 00:00:18 [error] MyObj: uh-oh, something went wrong -}}} - -Tip: All serious errors coming from the Propel core do not only issue a log message, they are also thrown as `PropelException`. - -=== Using An Alternative PEAR Log Handler === - -In many cases you may wish to integrate Propel's logging facility with the rest of your web application. In `runtime-conf.xml`, you can customize a different PEAR logger. Here are a few examples: - -'''Example 1:''' Using 'display' container (for output to HTML) -{{{ -#!xml - - display - 6 - -}}} - -'''Example 2:''' Using 'syslog' container -{{{ -#!xml - - syslog - 8 - propel - 6 - -}}} - -=== Using A Custom Logger === - -If you omit the `` section of your `runtime-conf.xml`, then Propel will not setup ''any'' logging for you. In this case, you can set a custom logging facility and pass it to Propel at runtime. - -Here's an example of how you could configure your own logger and then set Propel to use it: - -{{{ -#!php -log($m, Propel::LOG_EMERG); - } - public function alert($m) - { - $this->log($m, Propel::LOG_ALERT); - } - public function crit($m) - { - $this->log($m, Propel::LOG_CRIT); - } - public function err($m) - { - $this->log($m, Propel::LOG_ERR); - } - public function warning($m) - { - $this->log($m, Propel::LOG_WARNING); - } - public function notice($m) - { - $this->log($m, Propel::LOG_NOTICE); - } - public function info($m) - { - $this->log($m, Propel::LOG_INFO); - } - public function debug($m) - { - $this->log($m, Propel::LOG_DEBUG); - } - - public function log($message, $priority) - { - $color = $this->priorityToColor($priority); - echo '

$message

'; - } - - private function priorityToColor($priority) - { - switch($priority) { - case Propel::LOG_EMERG: - case Propel::LOG_ALERT: - case Propel::LOG_CRIT: - case Propel::LOG_ERR: - return 'red'; - break; - case Propel::LOG_WARNING: - return 'orange'; - break; - case Propel::LOG_NOTICE: - return 'green'; - break; - case Propel::LOG_INFO: - return 'blue'; - break; - case Propel::LOG_DEBUG: - return 'grey'; - break; - } - } -} -}}} - -Tip: There is also a bundled `MojaviLogAdapter` class which allows you to use a Mojavi logger with Propel. - -== Debugging Database Activity == - -By default, Propel uses `PropelPDO` for database connections. This class, which extends PHP's `PDO`, offers a debug mode to keep track of all the database activity, including all the executed queries. - -=== Enabling The Debug Mode === - -The debug mode is disabled by default, but you can enable it at runtime as follows: - -{{{ -#!php -useDebug(true); -}}} - -You can also disable the debug mode at runtime, by calling `PropelPDO::useDebug(false)`. Using this method, you can choose to enable the debug mode for only one particular query, or for all queries. - -Alternatively, you can ask Propel to always enable the debug mode for a particular connection by using the `DebugPDO` class instead of the default `PropelPDO` class. This is accomplished in the `runtime-conf.xml` file, in the `` tag of a given datasource connection (see the [wiki:Documentation/1.5/RuntimeConfiguration runtime configuration reference] for more details). - -{{{ -#!xml - - - - - - sqlite - - - DebugPDO -}}} - -'''Tip''': You can use your own connection class there, but make sure that it extends `PropelPDO` and not only `PDO`. Propel requires certain fixes to PDO API that are provided by `PropelPDO`. - -=== Counting Queries === - -In debug mode, `PropelPDO` keeps track of the number of queries that are executed. Use `PropelPDO::getQueryCount()` to retrieve this number: - -{{{ -#!php -getQueryCount(); // 1 -}}} - -Tip: You cannot use persistent connections if you want the query count to work. Actually, the debug mode in general requires that you don't use persistent connections in order for it to correctly log bound values and count executed statements. - -=== Retrieving The Latest Executed Query === - -For debugging purposes, you may need the SQL code of the latest executed query. It is available at runtime in debug mode using `PropelPDO::getLastExecutedQuery()`, as follows: - -{{{ -#!php -getLastExecutedQuery(); // 'SELECT * FROM my_obj'; -}}} - -Tip: You can also get a decent SQL representation of the criteria being used in a SELECT query by using the `Criteria->toString()` method. - -Propel also keeps track of the queries executed directly on the connection object, and displays the bound values correctly. - -{{{ -#!php -prepare('SELECT * FROM my_obj WHERE name = :p1'); -$stmt->bindValue(':p1', 'foo'); -$stmt->execute(); -echo $con->getLastExecutedQuery(); // 'SELECT * FROM my_obj where name = "foo"'; -}}} - -'''Tip''': The debug mode is intended for development use only. Do not use it in production environment, it logs too much information for a production server, and adds a small overhead to the database queries. - -== Full Query Logging == - -The combination of the debug mode and a logging facility provides a powerful debugging tool named ''full query logging''. If you have properly configured a log handler, enabling the debug mode (or using `DebugPDO`) automatically logs the executed queries into Propel's default log file: - -{{{ -Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO publisher (`ID`,`NAME`) VALUES (NULL,'William Morrow') -Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO author (`ID`,`FIRST_NAME`,`LAST_NAME`) VALUES (NULL,'J.K.','Rowling') -Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO book (`ID`,`TITLE`,`ISBN`,`PRICE`,`PUBLISHER_ID`,`AUTHOR_ID`) VALUES (NULL,'Harry Potter and the Order of the Phoenix','043935806X',10.99,53,58) -Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO review (`ID`,`REVIEWED_BY`,`REVIEW_DATE`,`RECOMMENDED`,`BOOK_ID`) VALUES (NULL,'Washington Post','2009-10-04',1,52) -... -Oct 04 00:00:18 propel-bookstore [debug] SELECT bookstore_employee_account.EMPLOYEE_ID, bookstore_employee_account.LOGIN FROM `bookstore_employee_account` WHERE bookstore_employee_account.EMPLOYEE_ID=25 -}}} - -By default, Propel logs all SQL queries, together with the date of the query and the name of the connection. - -=== Setting The Data To Log === - -The full query logging feature can be configured either in the `runtime-conf.xml` configuration file, or using the runtime configuration API. - -In `runtime-conf.xml`, tweak the feature by adding a `` tag under ``: - -{{{ -#!xml - - - - ... - - - - ... - - - -
- - true - - - - true - -
-
-
-
-
-}}} - -To accomplish the same configuration as above at runtime, change the settings in your main include file, after `Propel::init()`, as follows: - -{{{ -#!php -setParameter('debugpdo.logging.details.method.enabled', true); -$config->setParameter('debugpdo.logging.details.time.enabled', true); -$config->setParameter('debugpdo.logging.details.mem.enabled', true); -}}} - -Let's see a few of the provided parameters. - -=== Logging More Connection Messages === - -`PropelPDO` can log queries, but also connection events (open and close), and transaction events (begin, commit and rollback). Since Propel can emulate nested transactions, you may need to know when an actual `COMMIT` or `ROLLBACK` is issued. - -To extend which methods of `PropelPDO` do log messages in debug mode, customize the `'debugpdo.logging.methods'` parameter, as follows: - -{{{ -#!php -setParameter('debugpdo.logging.methods', $allMethods); -}}} - -By default, only the messages coming from `PropelPDO::exec`, `PropelPDO::query`, and `DebugPDOStatement::execute` are logged. - -=== Logging Execution Time And Memory === - -In debug mode, Propel counts the time and memory necessary for each database query. This very valuable data can be added to the log messages on demand, by adding the following configuration: - -{{{ -#!php -setParameter('debugpdo.logging.details.time.enabled', true); -$config->setParameter('debugpdo.logging.details.mem.enabled', true); -}}} - -Enabling the options shown above, you get log output along the lines of: - -{{{ -Feb 23 16:41:04 Propel [debug] time: 0.000 sec | mem: 1.4 MB | SET NAMES 'utf8' -Feb 23 16:41:04 Propel [debug] time: 0.002 sec | mem: 1.6 MB | SELECT COUNT(tags.NAME) FROM tags WHERE tags.IMAGEID = 12 -Feb 23 16:41:04 Propel [debug] time: 0.012 sec | mem: 2.4 MB | SELECT tags.NAME, image.FILENAME FROM tags LEFT JOIN image ON tags.IMAGEID = image.ID WHERE image.ID = 12 -}}} - -The order in which the logging details are enabled is significant, since it determines the order in which they will appear in the log file. - -=== Complete List Of Logging Options === - -The following settings can be customized at runtime or in the configuration file: - -||'''Parameter'''||'''Default'''||'''Meaning'''|| -||`debugpdo.logging.enabled`||`true`||Should any logging take place|| -||`debugpdo.logging.innerglue`||`": "`||String to use for combining the title of a detail and its value|| -||`debugpdo.logging.outerglue`||`" | "`||String to use for combining details together on a log line|| -||`debugpdo.logging.realmemoryusage`||`false`||Parameter to [http://www.php.net/manual/en/function.memory-get-usage.php memory_get_usage()] and [http://www.php.net/manual/en/function.memory-get-peak-usage.php memory_get_peak_usage()] calls|| -||`debugpdo.logging.methods`||[http://propel.propelorm.org/browser/branches/1.5/runtime/classes/propel/util/DebugPDO.php#L151 array(...)]||An array of method names `Class::method`) to be included in method call logging|| -||`debugpdo.logging.details.slow.enabled`||`false`||Enables flagging of slow method calls|| -||`debugpdo.logging.details.slow.threshold`||`0.1`||Method calls taking more seconds than this threshold are considered slow|| -||`debugpdo.logging.details.time.enabled`||`false`||Enables logging of method execution times|| -||`debugpdo.logging.details.time.precision`||`3`||Determines the precision of the execution time logging|| -||`debugpdo.logging.details.time.pad`||`10`||How much horizontal space to reserve for the execution time on a log line|| -||`debugpdo.logging.details.mem.enabled`||`false`||Enables logging of the instantaneous PHP memory consumption|| -||`debugpdo.logging.details.mem.precision`||`1`||Determines the precision of the memory consumption logging|| -||`debugpdo.logging.details.mem.pad`||`9`||How much horizontal space to reserve for the memory consumption on a log line|| -||`debugpdo.logging.details.memdelta.enabled`||`false`||Enables logging differences in memory consumption before and after the method call|| -||`debugpdo.logging.details.memdelta.precision`||`1`||Determines the precision of the memory difference logging|| -||`debugpdo.logging.details.memdelta.pad`||`10`||How much horizontal space to reserve for the memory difference on a log line|| -||`debugpdo.logging.details.mempeak.enabled`||`false`||Enables logging the peak memory consumption thus far by the currently executing PHP script|| -||`debugpdo.logging.details.mempeak.precision`||`1`||Determines the precision of the memory peak logging|| -||`debugpdo.logging.details.mempeak.pad`||`9`||How much horizontal space to reserve for the memory peak on a log line|| -||`debugpdo.logging.details.querycount.enabled`||`false`||Enables logging of the number of queries performed by the DebugPDO instance thus far|| -||`debugpdo.logging.details.querycount.pad`||`2`||How much horizontal space to reserve for the query count on a log line|| -||`debugpdo.logging.details.method.enabled`||`false`||Enables logging of the name of the method call|| -||`debugpdo.logging.details.method.pad`||`28`||How much horizontal space to reserve for the method name on a log line|| - -=== Changing the Log Level === - -By default the connection log messages are logged at the `Propel::LOG_DEBUG` level. This can be changed by calling the `setLogLevel()` method on the connection object: - -{{{ -#!php -setLogLevel(Propel::LOG_INFO); -}}} - -Now all queries and bind param values will be logged at the INFO level. - -=== Configuring a Different Full Query Logger === - -By default the `PropelPDO` connection logs queries and binds param values using the `Propel::log()` static method. As explained above, this method uses the log storage configured by the `` tag in the `runtime-conf.xml` file. - -If you would like the queries to be logged using a different logger (e.g. to a different file, or with different ident, etc.), you can set a logger explicitly on the connection at runtime, using `Propel::setLogger()`: - -{{{ -#!php -setLogger($logger); -} -}}} - -This will not affect the general Propel logging, but only the full query logging. That way you can log the Propel error and warnings in one file, and the SQL queries in another file. diff --git a/airtime_mvc/library/propel/docs/guide/09-Inheritance.txt b/airtime_mvc/library/propel/docs/guide/09-Inheritance.txt deleted file mode 100644 index 25e03b8e1..000000000 --- a/airtime_mvc/library/propel/docs/guide/09-Inheritance.txt +++ /dev/null @@ -1,329 +0,0 @@ -= Inheritance = - -[[PageOutline]] - -Developers often need one model table to extend another model table. Inheritance being an object-oriented notion, it doesn't have a true equivalent in the database world, so this is something an ORM must emulate. Propel offers two types of table inheritance: [http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html Single Table Inheritance], which is the most efficient implementations from a SQL and query performance perspective, but is limited to a small number of inherited fields ; and [http://www.martinfowler.com/eaaCatalog/concreteTableInheritance.html Concrete Table Inheritance], which provides the most features but adds a small overhead on write queries. - -== Single Table Inheritance == - -In this implementation, one table is used for all subclasses. This has the implication that your table must have all columns needed by the main class and subclasses. Propel will create stub subclasses. - -Let's illustrate this idea with an example. Consider an object model with three classes, `Book`, `Essay`, and `Comic` - the first class being parent of the other two. With single table inheritance, the data of all three classes is stored in one table, named `book`. - -=== Schema Definition === - -A table using Single Table Inheritance requires a column to identify which class should be used to represent the ''table'' row. Classically, this column is named `class_key` - but you can choose whatever name fits your taste. The column needs the `inheritance="single"` attribute to make Propel understand that it's the class key column. Note that this 'key' column must be a real column in the table. - -{{{ -#!xml - - - - - - - - -
-}}} - -Once you rebuild your model, Propel generated all three model classes (`Book`, `Essay`, and `Comic`) and three query classes (`BookQuery`, `EssayQuery`, and `ComicQuery`). The `Essay` and `Comic` classes extend the `Book` class, the `EssayQuery` and `ComicQuery` classes extend `BookQuery`. - -'''Tip''': An inherited class can extend another inherited class. That mean that you can add a `Manga` kind of book that extends `Comic` instead of `Book`. - -=== Using Inherited Objects === - -Use inherited objects just like you use regular Propel model objects: - -{{{ -#!php -setTitle('War And Peace'); -$book->save(); -$essay = new Essay(); -$essay->setTitle('On the Duty of Civil Disobedience'); -$essay->save(); -$comic = new Comic(); -$comic->setTitle('Little Nemo In Slumberland'); -$comic->save(); -}}} - -Inherited objects share the same properties and methods by default, but you can add your own logic to each of the generated classes. - -Behind the curtain, Propel sets the `class_key` column based on the model class. So the previous code stores the following rows in the database: - -{{{ -id | title | class_key ----|-----------------------------------|---------- -1 | War And Peace | Book -2 | On the Duty of Civil Disobedience | Essay -3 | Little Nemo In Slumberland | Comic -}}} - -Incidentally, that means that you can add new classes manually, even if they are not defined as `` tags in the `schema.xml`: - -{{{ -#!php -setClassKey('Novel'); - } -} -$novel = new Novel(); -$novel->setTitle('Harry Potter'); -$novel->save(); -}}} - -=== Retrieving Inherited objects === - -In order to retrieve books, use the Query object of the main class, as you would usually do. Propel will hydrate children objects instead of the parent object when necessary: - -{{{ -#!php -find(); -foreach ($books as $book) { - echo get_class($book) . ': ' . $book->getTitle() . "\n"; -} -// Book: War And Peace -// Essay: On the Duty of Civil Disobedience -// Comic: Little Nemo In Slumberland -// Novel: Harry Potter -}}} - -If you want to retrieve only objects of a certain class, use the inherited query classes: - -{{{ -#!php -findOne(); -echo get_class($comic) . ': ' . $comic->getTitle() . "\n"; -// Comic: Little Nemo In Slumberland -}}} - -'''Tip''': You can override the base peer's `getOMClass()` to return the classname to use based on more complex logic (or query). - -=== Abstract Entities === - -If you wish to enforce using subclasses of an entity, you may declare a table "abstract" in your XML data model: - -{{{ -#!xml - - ... -}}} - -That way users will only be able to instanciate `Essay` or `Comic` books, but not `Book`. - -== Concrete Table Inheritance == - -Concrete Table Inheritance uses one table for each class in the hierarchy. Each table contains columns for the class and all its ancestors, so any fields in a superclass are duplicated across the tables of the subclasses. - -Propel implements Concrete Table Inheritance through a behavior. - -=== Schema Definition === - -Once again, this is easier to understand through an example. In a Content Management System, content types are often organized in a hierarchy, each subclass adding more fields to the superclass. So let's consider the following schema, where the `article` and `video` tables use the same fields as the main `content` tables, plus additional fields: - -{{{ -#!xml -
- - - - - - -
- - - -
- - - - - - - - -
- - - - - - - - -
-}}} - -Since the columns of the main table are copied to the child tables, this schema is a simple implementation of Concrete Table Inheritance. This is something that you can write by hand, but the repetition makes it tedious. Instead, you should let the `concrete_inheritance` behavior do it for you: - -{{{ -#!xml - - - - - - - -
- - - -
- - - - - -
- - - - - -
-}}} - -'''Tip''': The `concrete_inheritance` behavior copies columns, foreign keys, indices and validators. - -=== Using Inherited Model Classes === - -For each of the tables in the schema above, Propel generates a Model class: - -{{{ -#!php -setName('Movie'); -$cat->save(); -// create a new Article -$art = new Article(); -$art->setTitle('Avatar Makes Best Opening Weekend in the History'); -$art->setCategory($cat); -$art->setContent('With $232.2 million worldwide total, Avatar had one of the best-opening weekends in the history of cinema.'); -$art->save(); -// create a new Video -$vid = new Video(); -$vid->setTitle('Avatar Trailer'); -$vid->setCategory($cat); -$vid->setResourceLink('http://www.avatarmovie.com/index.html') -$vid->save(); -}}} - -And since the `concrete_inheritance` behavior tag defines a parent table, the `Article` and `Video` classes extend the `Content` class (same for the generated Query classes): - -{{{ -#!php -getCategory()->getName(); - } -} -echo $art->getCategoryName(); // 'Movie' -echo $vid->getCategoryName(); // 'Movie' - -// methods of the parent query are accessible to the child query -class ContentQuery extends BaseContentQuery -{ - public function filterByCategoryName($name) - { - return $this - ->useCategoryQuery() - ->filterByName($name) - ->endUse(); - } -} -$articles = ArticleQuery::create() - ->filterByCategoryName('Movie') - ->find(); -}}} - -That makes of Concrete Table Inheritance a powerful way to organize your model logic and to avoid repetition, both in the schema and in the model code. - -=== Data Replication === - -By default, every time you save an `Article` or a `Video` object, Propel saves a copy of the `title` and `category_id` columns in a `Content` object. Consequently, retrieving objects regardless of their child type becomes very easy: - -{{{ -#!php -find(); -foreach ($conts as $content) { - echo $content->getTitle() . "(". $content->getCategoryName() ")/n"; -} -// Avatar Makes Best Opening Weekend in the History (Movie) -// Avatar Trailer (Movie) -}}} - -Propel also creates a one-to-one relationship between a object and its parent copy. That's why the schema definition above doesn't define any primary key for the `article` and `video` tables: the `concrete_inheritance` behavior creates the `id` primary key which is also a foreign key to the parent `id` column. So once you have a parent object, getting the child object is just one method call away: - -{{{ -#!php -getContent(); - } -} -class Movie extends BaseMovie -{ - public function getPreview() - { - return $this->getResourceLink(); - } -} -$conts = ContentQuery::create()->find(); -foreach ($conts as $content) { - echo $content->getTitle() . "(". $content->getCategoryName() ")/n" - if ($content->hasChildObject()) { - echo ' ' . $content->getChildObject()->getPreview(), "\n"; -} -// Avatar Makes Best Opening Weekend in the History (Movie) -// With $232.2 million worldwide total, Avatar had one of the best-opening -// weekends in the history of cinema. -// Avatar Trailer (Movie) -// http://www.avatarmovie.com/index.html -}}} - -The `hasChildObject()` and `getChildObject()` methods are automatically added by the behavior to the parent class. Behind the curtain, the saved `content` row has an additional `descendant_column` field allowing it to use the right model for the job. - -'''Tip''' You can disable the data replication by setting the `copy_data_to_parent` parameter to "false". In that case, the `concrete_inheritance` behavior simply modifies the table at buildtime and does nothing at runtime. Also, with `copy_data_to_parent` disabled, any primary key copied from the parent table is not turned into a foreign key: - -{{{ -#!xml - - - - - - -
-// results in - - - - - - - - -
-}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/reference/Buildtime-Configuration.txt b/airtime_mvc/library/propel/docs/reference/Buildtime-Configuration.txt deleted file mode 100644 index 36fbe642b..000000000 --- a/airtime_mvc/library/propel/docs/reference/Buildtime-Configuration.txt +++ /dev/null @@ -1,312 +0,0 @@ -= Build Properties Reference = - -[[PageOutline]] - -Here is a list of properties that can be set to affect how Propel builds database files. For a complete list, see the {{{default.properties}}} file that is bundled with your version of Propel generator (this will be in PEAR's data directory if you are using a PEAR-installed version of Propel). - -First, some conventions: - - * Text surrounded by a '''/''' is text that you would provide and is not defined in the language. (i.e. a table name is a good example of this.) - * Items where you have an alternative choice have a '''|''' character between them (i.e. true|false) - * Alternative choices may be delimited by '''{''' and '''}''' to indicate that this is the default option, if not overridden elsewhere. - -== Where to Specify Properties == - -=== In the Project build.properties File === - -The most natural place to specify properties for a file are in the project's {{{build.properties}}} file. This file is expected to be found in the project directory. - -=== In a global build.properties file === - -You can also create a {{{global build.properties}}} file in the same directory as Propel's {{{default.properties}}} file. For users who have installed Propel using PEAR, this will be in PEAR data directory structure. - -=== On the Command Line === - -You can also specify properties on the commandline when you invoke Propel: - -{{{ -$ propel-gen /path/to/project -Dpropel.someOtherProperty=value -}}} - -''Note that there is '''no space''' between the -D and the property name.'' - -== The Properties == - -=== General Build Settings === - -{{{ -propel.project = Your-Project-Name -}}} - -The name of your project. This affects names of generated files, etc. - -{{{ -propel.targetPackage = {propel.project} -}}} - -The package to use for the generated classes. This affects the value of the @package phpdoc tag, and it also affects the directory that the classes are placed in. By default this will be the same as the project. Note that the target package (and thus the target directory for generated classes) can be overridden in each `` and `` element in the XML schema. - -{{{ -propel.packageObjectModel = true|{false} -}}} - -Whether to join schemas using the same database name into a single schema. This allows splitting schemas in packages, and referencing tables in another schema (but in the same database) in a foreign key. Beware that database behaviors will also be joined when this parameter is set to true. - -{{{ -propel.schema.validate = {true}|false -}}} - -Whether to validate the schema using the XSD file. The default XSD file is located under `generator/resources/xsd/database.xsd`, and you can use a custom XSD file by changing the `propel.schema.xsd.file` property. - -{{{ -propel.schema.transform = true|{false} -}}} - -Whether to transform the schema using the XSL file. This was used in previous Propel versions to clean up the schema, but tended to hide problems in the schema. It is disabled by default since Propel 1.5. The default XSL file is located under `generator/resources/xsd/database.xsl`, and you can use a custom XSL file by changing the `propel.schema.xsl.file` property. - -=== Database Settings === - -{{{ -propel.database = pgsql|mysql|sqlite|mssql|oracle -}}} - -The Propel platform that will be used to determine how to build the SQL DDL, etc. - - -{{{ -propel.database.url = /PDO database connection string/ -propel.database.user = -propel.database.password = -}}} - -Propel will use this information as the default to connect to your database. Note that for PDO some drivers (e.g. mysql, oracle) require that you specify the username and password separately from the DSN, which is why they are available as options. - - -{{{ -propel.database.buildUrl = /PDO database connection string, defaults to use ${propel.database.url}/ -}}} - -This property is used by Propel to connect to a database to reverse engineer or data dump. The default is to use the database connection defined by the ''propel.database.url'' property. - - -{{{ -propel.database.createUrl = /PDO database connection string, defaults to use ${propel.database.url}/ -}}} - -This property is used by Propel for creating a database. Of course, Propel is unable to create many databases because they do not provide a SQL method for creation; therefore, it is usually recommended that you actually create your database by hand. - -{{{ -propel.database.schema = /schema-name/ -}}} - -Where supported by the RDBMS, you can specify a schema name for Propel to use. - -{{{ -propel.database.encoding = -}}} -The encoding to use for the database. This can affect things such as transforming charsets when exporting to XML, etc. - -{{{ -propel.tablePrefix = {empty}|string -}}} - -Add a prefix to all the table names in the database. This does not affect the tables phpName. This setting can be overridden on a per-database basis in the schema. - -=== Reverse-Engineering Settings === - -{{{ -propel.samePhpName = true|{false} -}}} -Whether to specify PHP names that are the same as the column names. - -{{{ -propel.addVendorInfo = true|{false} -}}} -Whether to add the vendor info. This is currently only used for MySQL, but does provide additional information (such as full-text indexes) which can affect the generation of the DDL from the schema. - -{{{ -propel.addValidators = {none}|maxvalue|type|required|unique|all -}}} -Which Propel validators to add to the generated schema (based on the db constraints). - -=== Customizing Generated Object Model === - -{{{ -propel.addGenericAccessors = true|{false} -propel.addGenericMutators = true|{false} -}}} -Whether to add generic getter/setter methods -- e.g. '''getByName()''', '''setByName()'''. - -{{{ -propel.addTimeStamp = true|{false} -}}} -Whether to add a timestamp to the phpdoc header of generated OM classes. - -{{{ -propel.addValidateMethod = {true}|false -}}} -Whether to add `validate()` method to your classes. Set to false if you don't use Propel validation. - -{{{ -propel.addIncludes = {true}|false -}}} -Whether to add `require` statements on the generated stub classes. Set to false if you autoload every classe at runtime. - -{{{ -propel.addHooks = {true}|false -}}} -Whether to support pre- and post- hooks on `save()` and `delete()` methods. Set to false if you never use these hooks for a small speed boost. - -{{{ -propel.basePrefix = {Base}|/YourPrefix/ -}}} -The prefix to use for the base (super) classes that are generated. - -{{{ -propel.classPrefix = {empty}|string; -}}} -Some sort of "namespacing": All Propel classes with get the Prefix "My_ORM_Prefix_" just like "My_ORM_Prefix_BookPeer". - -{{{ -propel.disableIdentifierQuoting = true|{false} -}}} -Identifier quoting is only implemented at the DDL layer at this point. Since this may result in undesired behavior (especially in Postgres), it can be disabled by setting this property to true. - -{{{ -propel.useLeftJoinsInDoJoinMethods = {true}|false -}}} -Set whether the '''doSelectJoin*()''' methods use LEFT JOIN or INNER JOIN (see ticket:491 and ticket:588 to understand more about why this might be important). - -=== MySQL-specific Settings === - -{{{ -propel.mysqlTableType = /DefaultTableEngine/ -}}} -Default table engine - defaults to MyISAM. You can override this setting if you wish to default to another engine for all tables (for instance InnoDB, or HEAP). This setting can also be overridden on a per-table basis using the `` element in the schema (see [wiki:Documentation/1.5/Schema#AddingVendorInfo]). - -{{{ -propel.mysqlTableEngineKeyword = /EngineKeyword/ -}}} -Keyword used to specify the table engine in the CREATE SQL statement. Defaults to 'ENGINE', users of MYSQL < 5 should use 'TYPE' instead. - -=== Date/Time Settings === - -{{{ -propel.useDateTimeClass = true|{false} -}}} -This is how you enable full use of the new DateTime class in Propel. Setting this to true means that getter methods for date/time/timestamp columns will return a DateTime object ''when the default format is empty''. Note that the current default of ''false'' is only for backwards compatibility; in the future ''true'' will be the only option here. - -{{{ -propel.dateTimeClass = {DateTime}|string -}}} -Specify a custom DateTime subclass that you wish to have Propel use for temporal values. - -{{{ -propel.defaultTimeStampFormat = {Y-m-d H:i:s}|string -propel.defaultTimeFormat = {%X}|string -propel.defaultDateFormat = {%x}|string -}}} -These are the default formats that will be used when fetching values from temporal columns in Propel. You can always specify these when calling the methods directly, but for methods like getByName() it is nice to change the defaults. - -To have these methods return DateTime objects instead, you should set these to empty values, for example: -{{{ -propel.defaultTimeStampFormat = -}}} - -=== Directories === - -{{{ -propel.project.dir = default-depends-on-installation-type -}}} - -''This is not necessarily a property you can change.'' The project directory is the directory where you project files (build.properties, schema.xml, runtime-conf.xml, etc.) are located. For example, if you use the {{{propel-gen}}} script, this value will get overridden to the path you pass to {{{propel-gen}}}. - -{{{ -propel.output.dir = ${propel.project.dir}/build -}}} -The default top-level directory for output of classes, sql, config, etc. - -{{{ -propel.schema.dir = ${propel.project.dir} -}}} -The directory where Propel expects to find your schema.xml file. - -{{{ -propel.conf.dir = ${propel.project.dir} -}}} -The directory where Propel expects to find your {{{runtime-conf.xml}}} file. - -{{{ -propel.php.dir = ${propel.output.dir}/classes -}}} -The directory where Propel will create generated object model classes. - -{{{ -propel.phpconf.dir = ${propel.output.dir}/conf -}}} -The directory where Propel will place the php-ified version of your {{{runtime-conf.xml}}}. - -{{{ -propel.sql.dir = ${propel.output.dir}/sql -}}} -The directory where Propel will place generated DDL (or data insert statements, etc.) - - -=== Overriding Builder Classes === - -{{{ -# Object Model builders -propel.builder.peer.class = propel.engine.builder.om.php5.PHP5ComplexPeerBuilder -propel.builder.object.class = propel.engine.builder.om.php5.PHP5ComplexObjectBuilder -propel.builder.objectstub.class = propel.engine.builder.om.php5.PHP5ExtensionObjectBuilder -propel.builder.peerstub.class = propel.engine.builder.om.php5.PHP5ExtensionPeerBuilder - -propel.builder.objectmultiextend.class = propel.engine.builder.om.php5.PHP5MultiExtendObjectBuilder - -propel.builder.tablemap.class = propel.engine.builder.om.php5.PHP5TableMapBuilder - -propel.builder.interface.class = propel.engine.builder.om.php5.PHP5InterfaceBuilder - -propel.builder.node.class = propel.engine.builder.om.php5.PHP5NodeBuilder -propel.builder.nodepeer.class = propel.engine.builder.om.php5.PHP5NodePeerBuilder -propel.builder.nodestub.class = propel.engine.builder.om.php5.PHP5ExtensionNodeBuilder -propel.builder.nodepeerstub.class = propel.engine.builder.om.php5.PHP5ExtensionNodePeerBuilder - -propel.builder.nestedset.class = propel.engine.builder.om.php5.PHP5NestedSetBuilder -propel.builder.nestedsetpeer.class = propel.engine.builder.om.php5.PHP5NestedSetPeerBuilder - -# SQL builders - -propel.builder.ddl.class = propel.engine.builder.sql.${propel.database}.${propel.database}DDLBuilder -propel.builder.datasql.class = propel.engine.builder.sql.${propel.database}.${propel.database}DataSQLBuilder - -# Platform classes - -propel.platform.class = propel.engine.platform.${propel.database}Platform - -# Pluralizer class (used to generate plural forms) - -propel.builder.pluralizer.class = propel.engine.builder.util.DefaultEnglishPluralizer -}}} - -As you can see, you can specify your own builder and platform classes if you want to extend & override behavior in the default classes - -=== Adding Behaviors === - -{{{ -propel.behavior.timestampable.class = propel.engine.behavior.TimestampableBehavior -}}} - -Define the path to the class to be used for the `timestampable` behavior. This behavior is bundled wit hPropel, but if you want to override it, you can specify a different path. - -If you want to add more behaviors, write their path following the same model: - -{{{ -propel.behavior.my_behavior.class = my.custom.path.to.MyBehaviorClass -}}} - -Behaviors are enabled on a per-table basis in the `schema.xml`. However, you can add behaviors for all your schemas, provided that you define them in the `propel.behavior.default` setting: - -{{{ -propel.behavior.default = soft_delete,my_behavior -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/reference/ModelCriteria.txt b/airtime_mvc/library/propel/docs/reference/ModelCriteria.txt deleted file mode 100644 index d5c4042d3..000000000 --- a/airtime_mvc/library/propel/docs/reference/ModelCriteria.txt +++ /dev/null @@ -1,1025 +0,0 @@ -= Propel Query Reference = - -[[PageOutline]] - -Propel's Query classes make it easy to write queries of any level of complexity in a simple and reusable way. - -== Overview == - -Propel proposes an object-oriented API for writing database queries. That means that you don't need to write any SQL code to interact with the database. Object orientation also facilitates code reuse and readability. Here is how to query the database for records in the `book` table ordered by the `title` column and published in the last month: - -{{{ -#!php -filterByPublishedAt(array('min' => time() - 30 * 24 * 60 * 60)) - ->orderByTitle() - ->find(); -}}} - -The first thing to notice here is the fluid interface. Propel queries are made of method calls that return the current query object - `filterByPublishedAt()` and `orderByTitle()` return the current query augmented with conditions. `find()`, on the other hand, is a ''termination method'' that doesn't return the query, but its result - in this case, a collection of `Book` objects. - -Propel generates one `filterByXXX()` method for every column in the table. The column name used in the PHP method is not the actual column name in the database ('`published_at`'), but rather a CamelCase version of it ('`PublishedAt`'), called the column ''phpName''. Remember to always use the phpName in the PHP code ; the actual SQL name only appears in the SQL code. - -When a termination method like `find()` is called, Propel builds the SQL code and executes it. The previous example generates the following code when `find()` is called: - -{{{ -#!php -= :p1 -ORDER BY book.TITLE ASC'; -}}} - -Propel uses the column name in conjunction with the schema to determine the column type. In this case, `published_at` is defined in the schema as a `TIMESTAMP`. Then, Propel ''binds'' the value to the condition using the column type. This prevents SQL injection attacks that often plague web applications. Behind the curtain, Propel uses PDO to achieve this binding: - -{{{ -#!php -prepare($query); -$stmt->bind(':p1', time() - 30 * 24 * 60 * 60, PDO::PARAM_INT); -$res = $stmt->execute(); -}}} - -The final `find()` doesn't just execute the SQL query above, it also instanciates `Book` objects and populates them with the results of the query. Eventually, it returns a `PropelCollection` object with these `Book` objects inside. For the sake of clarity, you can consider this collection object as an array. In fact, you can use it as if it were a true PHP array and iterate over the result list the usual way: - -{{{ -#!php -getTitle(); -} -}}} - -So Propel queries are a very powerful tool to write your queries in an object-oriented fashion. They are also very natural - if you know how to write an SQL query, chances are that you will write Propel queries in minutes. - -== Generated Query Methods == - -For each object, Propel creates a few methods in the generated query object. - -=== Column Filter Methods === - -`filterByXXX()`, generated for each column, provides a different feature and a different functionality depending on the column type: - - * For all columns, `filterByXXX()` translates to a simple SQL `WHERE` condition by default: - -{{{ -#!php -filterByTitle('War And Peace') - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from `book` -WHERE book.TITLE = :p1'; // :p1 => 'War And Peace' -}}} - - * For string columns, `filterByXXX()` translates to a SQL `WHERE ... LIKE` if the value contains wildcards: - -{{{ -#!php -filterByTitle('War%') - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from `book` -WHERE book.TITLE LIKE :p1'; // :p1 => 'War%' -}}} - - * For integer columns, `filterByXXX()` translates into a SQL `WHERE ... IN` if the value is an array: - -{{{ -#!php -filterByAuthorId(array(123, 456)) - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from `book` -WHERE book.AUTHOR_ID IN (:p1, :p2)'; // :p1 => 123, :p2 => 456 -}}} - - * For Boolean columns, `filterByXXX()` translates the value to a boolean using smart casting: - -{{{ -#!php -filterByIsPublished('yes') - ->filterByIsSoldOut('no') - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from `book` -WHERE book.IS_PUBLISHED = :p1 - AND book.IS_SOLD_OUT = :p2'; // :p1 => true, :p2 => false -}}} - -=== Relation Filter Methods === - -Propel also generates a `filterByXXX()` method for every foreign key. The filter expects an object of the related class as parameter: - -{{{ -#!php -findPk(123); -$books = BookQuery::create() - ->filterByAuthor($author) - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from `book` -WHERE book.AUTHOR_ID = :p1'; // :p1 => 123 -}}} - -Check the generated BaseQuery classes for a complete view of the generated query methods. Every generated method comes with a detailed phpDoc comment, making code completion very easy on supported IDEs. - -=== Embedding a Related Query === - -In order to add conditions on related tables, a propel query can ''embed'' the query of the related table. The generated `useXXXQuery()` serve that purpose. For instance, here is how to query the database for books written by 'Leo Tolstoi': - -{{{ -#!php -useAuthorQuery() - ->filterByName('Leo Tolstoi') - ->endUse() - ->find(); -}}} - -`useAuthorQuery()` returns a new instance of `AuthorQuery` already joined with the current `BookQuery` instance. The next method is therefore called on a different object - that's why the `filterByName()` call is further indented in the code example. Finally, `endUse()` merges the conditions applied on the `AuthorQuery` to the `BookQuery`, and returns the original `BookQuery` object. - -Propel knows how to join the `Book` model to the `Author` model, since you already defined a foreign key between the two tables in the `schema.xml`. Propel takes advantage of this knowledge of your model relationships to help you write faster queries and omit the most obvious data. - -{{{ -#!php - 'Leo Tolstoi' -}}} - -You can customize the related table alias and the join type by passing arguments to the `useXXXQuery()` method: - -{{{ -#!php -useAuthorQuery('a', 'left join') - ->filterByName('Leo Tolstoi') - ->endUse() - ->find(); -// example Query generated for a MySQL database -$query = 'SELECT book.* from book -LEFT JOIN author a ON book.AUTHOR_ID = a.ID -WHERE a.NAME = :p1'; // :p1 => 'Leo Tolstoi' -}}} - -The `useXXXQuery()` methods allow for very complex queries. You can mix them, nest them, and reopen them to add more conditions. - -== Inherited Methods == - -The generated Query classes extend a core Propel class named `ModelCriteria`, which provides even more methods for building your queries. - -=== Finding An Object From Its Primary Key === - -{{{ -#!php -findPk(123); -// Finding the books having primary keys 123 and 456 -$books = BookQuery::create()->findPks(array(123, 456)); -// Also works for objects with composite primary keys -$bookOpinion = BookOpinionQuery::create()->findPk(array($bookId, $userId)); -}}} - -=== Finding Objects === - -{{{ -#!php -find(); -// Finding 3 Books -$articles = BookQuery::create() - ->limit(3) - ->find(); -// Finding a single Book -$article = BookQuery::create() - ->findOne(); -}}} - -=== Using Magic Query Methods === - -{{{ -#!php -findOneByTitle('War And Peace'); -// same as -$book = BookQuery::create() - ->filterByTitle('War And Peace') - ->findOne(); - -$books = BookQuery::create()->findByTitle('War And Peace'); -// same as -$books = BookQuery::create() - ->filterByTitle('War And Peace') - ->find(); - -// You can even combine several column conditions in a method name, if you separate them with 'And' -$book = BookQuery::create()->findOneByTitleAndAuthorId('War And Peace', 123); -// same as -$book = BookQuery::create() - ->filterByTitle('War And Peace') - ->filterById(123) - ->findOne(); -}}} - -=== Ordering Results === - -{{{ -#!php -orderByPublishedAt() - ->find(); -// Finding all Books ordered by published_at desc -$books = BookQuery::create() - ->orderByPublishedAt('desc') - ->find(); -}}} - -=== Specifying A Connection === - -{{{ -#!php -findOne($con); -}}} - -'''Tip''': In debug mode, the connection object provides a way to check the latest executed query, by calling `$con->getLastExecutedQuery()`. See the [wiki:Documentation/1.5/07-Logging Logging documentation] for more details. - -=== Counting Objects === - -{{{ -#!php -count($con); -// This is much faster than counting the results of a find() -// since count() doesn't populate Model objects -}}} - -=== Deleting Objects === - -{{{ -#!php -deleteAll($con); -// Deleting a selection of Books -$nbDeletedBooks = BookQuery::create() - ->filterByTitle('Pride And Prejudice') - ->delete($con); -}}} - -=== Updating Objects === - -{{{ -#!php -setName('Jane Austen'); -$author1->save(); -$author2 = new Author(); -$author2->setName('Leo Tolstoy'); -$author2->save(); - -// update() issues an UPDATE ... SET query based on an associative array column => value -$nbUpdatedRows = AuthorQuery::create() - ->filterByName('Leo Tolstoy') - ->update(array('Name' => 'Leo Tolstoi'), $con); - -// update() returns the number of modified columns -echo $nbUpdatedRows; // 1 - -// Beware that update() updates all records found in a single row -// And bypasses any behavior registered on the save() hooks -// You can force a one-by-one update by setting the third parameter of update() to true -$nbUpdatedRows = AuthorQuery::create() - ->filterByName('Leo Tolstoy') - ->update(array('Name' => 'Leo Tolstoi'), $con, true); -// Beware that it may take a long time -}}} - -=== Creating An Object Based on a Query === - -You may often create a new object based on values used in conditions if a query returns no result. This happens a lot when dealing with cross-reference tables in many-to-many relationships. To avoid repeating yourself, use `findOneOrCreate()` instead of `findOne()` in such cases: - -{{{ -#!php -filterByBook($book) - ->filterByTag('crime') - ->findOne(); -if (!$bookTag) { - $bookTag = new BookTag(); - $bookTag->setBook($book); - $bookTag->setTag('crime'); -} -// The short way -$bookTag = BookTagQuery::create() - ->filterByBook($book) - ->filterByTag('crime') - ->findOneOrCreate(); -}}} - -=== Reusing A Query === - -By default, termination methods like `findOne()`, `find()`, `count()`, `paginate()`, or `delete()` alter the original query. That means that if you need to reuse a query after a termination method, you must call the `keepQuery()` method first: - -{{{ -#!php -filterByIsPublished(true); -$book = $q->findOneByTitle('War And Peace'); -// findOneByXXX() adds a limit() to the query -// so further reuses of the query may show side effects -echo $q->count(); // 1 - -// to allos query reuse, call keepQuery() before the termination method -$q = BookQuery::create()->filterByIsPublished(true)->keepQuery(); -$book = $q->findOneByTitle('War And Peace'); -echo $q->count(); // 34 -}}} - -== Relational API == - -For more complex queries, you can use an alternative set of methods, closer to the relational logic of SQL, to make sure that Propel issues exactly the SQL query you need. - -This alternative API uses methods like `where()`, `join()` and `orderBy()` that translate directly to their SQL equivalent - `WHERE`, `JOIN`, etc. Here is an example: - -{{{ -#!php -join('Book.Author') - ->where('Author.Name = ?', 'Leo Tolstoi') - ->orderBy('Book.Title', 'asc') - ->find(); - -}}} - -The names passed as parameters in these methods, like 'Book.Author', 'Author.Name', and 'Book.Title', are ''explicit column names''. These names are composed of the phpName of the model, and the phpName of the column, separated by a dot (e.g. 'Author.Name'). Manipulating object model names allows you to be detached from the actual data storage, and alter the database names without necessarily updating the PHP code. It also makes the use of table aliases much easier - more on that matter later. - -Propel knows how to map the explicit column names to database column names in order to translate the Propel query into an actual database query: - -{{{ -#!php -where('Book.Title = ?', 'War And Peace') - ->find(); -// Finding all Books where title is like 'War%' -$books = BookQuery::create() - ->where('Book.Title LIKE ?', 'War%') - ->find(); -// Finding all Books published after $date -$books = BookQuery::create() - ->where('Book.PublishedAt > ?', $date) - ->find(); -// Finding all Books with no author -$books = BookQuery::create() - ->where('Book.AuthorId IS NULL') - ->find(); -// Finding all books from a list of authors -$books = BookQuery::create() - ->where('Book.AuthorId IN ?', array(123, 542, 563)) - ->find(); -// You can even use SQL functions inside conditions -$books = BookQuery::create() - ->where('UPPER(Book.Title) = ?', 'WAR AND PEACE') - ->find(); -}}} - -=== Combining Several Conditions === - -For speed reasons, `where()` only accepts simple conditions, with a single interrogation point for the value replacement. When you need to apply more than one condition, and combine them with a logical operator, you have to call `where()` multiple times. - -{{{ -#!php -where('Book.Title = ?', 'War And Peace') - ->where('Book.PublishedAt > ?', $date) - ->find(); -// For conditions chained with OR, use orWhere() instead of where() -$books = BookQuery::create() - ->where('Book.Title = ?', 'War And Peace') - ->orWhere('Book.Title LIKE ?', 'War%') - ->find(); -}}} - -The use of `where()` and `orWhere()` doesn't allow logically complex conditions, that you would write in SQL with parenthesis. For such cases, create named conditions with `condition()`, and then combine them in an array that you can pass to `where()` instead of a single condition, as follows: - -{{{ -#!php -condition('cond1', 'Book.Title = ?', 'War And Peace') // create a condition named 'cond1' - ->condition('cond2', 'Book.Title LIKE ?', 'War%') // create a condition named 'cond2' - ->where(array('cond1', 'cond2'), 'or')-> // combine 'cond1' and 'cond2' with a logical OR - ->find(); - // SELECT book.* from book WHERE (book.TITLE = 'War And Peace' OR book.TITLE LIKE 'War%'); - -// You can create a named condition from the combination of other named conditions by using `combine()` -// That allows for any level of complexity -$books = BookQuery::create() - ->condition('cond1', 'Book.Title = ?', 'War And Peace') // create a condition named 'cond1' - ->condition('cond2', 'Book.Title LIKE ?', 'War%') // create a condition named 'cond2' - ->combine(array('cond1', 'cond2'), 'or', 'cond12') // create a condition named 'cond12' from 'cond1' and 'cond2' - ->condition('cond3', 'Book.PublishedAt <= ?', $end) // create a condition named 'cond3' - ->condition('cond4', 'Book.PublishedAt >= ?', $begin) // create a condition named 'cond4' - ->combine(array('cond3', 'cond4'), 'and', 'cond34') // create a condition named 'cond34' from 'cond3' and 'cond4' - ->where(array('cond12', 'cond34'), 'and') // combine the two conditions in a where - ->find(); - // SELECT book.* FROM book WHERE ( - // (book.TITLE = 'War And Peace' OR book.TITLE LIKE 'War%') - // AND - // (book.PUBLISHED_AT <= $end AND book.PUBLISHED_AT >= $begin) - // ); -}}} - -=== Joining Tables === - -{{{ -#!php -setName('Jane Austen'); -$author1->save(); -$book1 = new Book(); -$book1->setTitle('Pride And Prejudice'); -$book1->setAuthor($author1); -$book1->save(); - -// Add a join statement -// No need to tell the query which columns to use for the join, just the related Class -// After all, the columns of the FK are already defined in the schema. -$book = BookQuery::create() - ->join('Book.Author') - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); - // SELECT book.* FROM book - // INNER JOIN author ON book.AUTHOR_ID = author.ID - // WHERE author.NAME = 'Jane Austin' - // LIMIT 1; - -// The default join() call results in a SQL INNER JOIN clause -// For LEFT JOIN or RIGHT JOIN clauses, use leftJoin() or rightJoin() instead of join() -$book = BookQuery::create() - ->leftJoin('Book.Author') - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); - -// You can chain joins if you want to make more complex queries -$review = new Review(); -$review->setBook($book1); -$review->setRecommended(true); -$review->save(); - -$author = BookQuery::create() - ->join('Author.Book') - ->join('Book.Review') - ->where('Review.Recommended = ?', true) - ->findOne(); - -// Alternatively, you can use the generated joinXXX() methods -// Which are a bit faster than join(), but limited to the current model's relationships -$book = BookQuery::create() - ->joinAuthor() - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); -// The join type depends on the required attribute of the foreign key column -// If the column is required, then the default join type is an INNER JOIN -// Otherwise, the default join type is a LEFT JOIN -// You can override the default join type for a given relationship -// By setting the joinType attribute of the foreign key element in the schema.xml -}}} - -=== Table Aliases === - -{{{ -#!php -where('b.Title = ?', 'Pride And Prejudice') - ->find(); - -// join(), leftJoin() and rightJoin() also allow table aliases -$author = AuthorQuery::create('a') - ->join('a.Book b') - ->join('b.Review r') - ->where('r.Recommended = ?', true) - ->findOne(); - -// Table aliases can be used in all query methods (where, groupBy, orderBy, etc.) -$books = BookQuery::create('b') - ->where('b.Title = ?', 'Pride And Prejudice') - ->orderBy('b.Title') - ->find(); - -// Table aliases are mostly useful to join the current table, -// or to handle multiple foreign keys on the same column -$employee = EmployeeQuery::create('e') - ->innerJoin('e.Supervisor s') - ->where('s.Name = ?', 'John') - ->find(); -}}} - -=== Minimizing Queries === - -Even if you do a join, Propel will issue new queries when you fetch related objects: - -{{{ -#!php -join('Book.Author') - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); -$author = $book->getAuthor(); // Needs another database query -}}} - -Propel allows you to retrieve the main object together with related objects in a single query. You just have to call the `with()` method to specify which objects the main object should be hydrated with. - -{{{ -#!php -join('Book.Author') - ->with('Author') - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); -$author = $book->getAuthor(); // Same result, with no supplementary query -}}} - -`with()` expects a relation name, as declared previously by `join()`. In practice, that means that `with()` and `join()` should always come one after the other. To avoid repetition, use `joinWith()` to both add a `join()` and a `with()` on a relation. So the shorter way to write the previous query is: - -{{{ -#!php -joinWith('Book.Author') - ->where('Author.Name = ?', 'Jane Austen') - ->findOne(); -$author = $book->getAuthor(); // Same result, with no supplementary query -}}} - -Since the call to `with()` adds the columns of the related object to the SELECT part of the query, and uses these columns to populate the related object, that means that `joinWith()` is slower and consumes more memory that `join()`. So use it only when you actually need the related objects afterwards. - -`with()` and `joinWith()` are not limited to immediate relationships. As a matter of fact, just like you can chain `join()` calls, you can chain `joinWith()` calls to populate a chain of objects: - -{{{ -#!php -joinWith('Review.Book') - ->joinWith('Book.Author') - ->joinWith('Book.Publisher') - ->findOne(); -$book = $review->getBook() // No additional query needed -$author = $book->getAuthor(); // No additional query needed -$publisher = $book->getPublisher(); // No additional query needed -}}} - -So `joinWith()` is very useful to minimize the number of database queries. As soon as you see that the number of queries necessary to perform an action is proportional to the number of results, adding `With` after `join()` calls is the trick to get down to a more reasonnable query count. - -=== Adding Columns === - -Sometimes you don't need to hydrate a full object in addition to the main object. If you only need one additional column, the `withColumn()` method is a good alternative to `joinWith()`, and it speeds up the query: - -{{{ -#!php -join('Book.Author') - ->withColumn('Author.Name', 'AuthorName') - ->findOne(); -$authorName = $book->getAuthorName(); -}}} - -Propel adds the 'with' column to the SELECT clause of the query, and uses the second argument of the `withColumn()` call as a column alias. This additional column is later available as a 'virtual' column, i.e. using a getter that does not correspond to a real column. You don't actually need to write the `getAuthorName()` method ; Propel uses the magic `__call()` method of the generated `Book` class to catch the call to a virtual column. - -`withColumn()` is also of great use to add calculated columns: - -{{{ -#!php -join('Author.Book') - ->withColumn('COUNT(Book.Id)', 'NbBooks') - ->groupBy('Author.Id') - ->find(); -foreach ($authors as $author) { - echo $author->getName() . ': ' . $author->getNbBooks() . " books\n"; -} -}}} - -With a single SQL query, you can have both a list of objects and an additional column for each object. That makes of `withColumn()` a great query saver. - -'''Tip''': You can call `withColumn()` multiple times to add more than one virtual column to the resulting objects. - -=== Adding A Comment === - -{{{ -#!php -setComment('Author Deletion') - ->filterByName('Leo Tolstoy') - ->delete($con); -// The comment ends up in the generated SQL query -// DELETE /* Author Deletion */ FROM `author` WHERE author.NAME = 'Leo Tolstoy' -}}} - -=== Using Methods From Another Query Class === - -After writing custom methods to query objects, developers often meet the need to use the method from another query. For instance, in order to select the authors of the most recent books, you may want to write: - -{{{ -#!php -join('Author.Book') - ->recent() - ->find(); -}}} - -The problem is that `recent()` is a method of `BookQuery`, not of the `AuthorQuery` class that the `create()` factory returns. - -Does that mean that you must repeat the `BookQuery::recent()` code into a new `AuthorQuery::recentBooks()` method? That would imply repeating the same code in two classes, which is not a good practice. Instead, use the `useQuery()` and `endUse()` combination to use the methods of `BookQuery` inside `AuthorQuery`: - -{{{ -#!php -join('Author.Book') - ->useQuery('Book') - ->recent() - ->endUse() - ->find(); -}}} - -This is excatly whath the generated `useBookQuery()` does, except that you have more control over the join type and alias when you use the relational API. Behind the scene, `useQuery('Book')` creates a `BookQuery` instance and returns it. So the `recent()` call is actually called on `BookQuery`, not on `ArticleQuery`. Upon calling `endUse()`, the `BookQuery` merges into the original `ArticleQuery` and returns it. So the final `find()` is indeed called on the `AuthorQuery` instance. - -You can nest queries in as many levels as you like, in order to avoid the repetition of code in your model. - -'''Tip''': If you define an alias for the relation in `join()`, you must pass this alias instead of the model name in `useQuery()`. - -{{{ -#!php -join('a.Book b') - ->useQuery('b') - ->recent() - ->endUse() - ->find(); -}}} - -=== Fluid Conditions === - -Thanks to the query factories and the fluid interface, developers can query the database without creating a variable for the Query object. This helps a lot to reduce the amount of code necessary to write a query, and it also makes the code more readable. - -But when you need to call a method on a Query object only if a certain condition is satisfied, it becomes compulsory to use a variable for the Query object: - -{{{ -#!php -isEditor()) { - $query->where('Book.IsPublished = ?', true); -} -$books = $query - ->orderByTitle() - ->find(); -}}} - -The `ModelCriteria` class offers a neat way to keep your code to a minimum in such occasions. It provides `_if()` and `_endif()` methods allowing for inline conditions. Using thses methods, the previous query can be written as follows: - -{{{ -#!php -_if(!$user->isEditor()) - ->where('Book.IsPublished = ?', true) - ->_endif() - ->orderByTitle() - ->find(); -}}} - -The method calls enclosed between `_if($cond)` and `_endif()` will only be executed if the condition is true. To complete the list of tools available for fluid conditions, you can also use `_else()` and `_elseif($cond)`. - -=== More Complex Queries === - -The Propel Query objects have even more methods that allow you to write queries of any level of complexity. Check the API documentation for the `ModelCriteria` class to see all methods. - -{{{ -#!php -find(); // $books behaves like an array -?> -There are books: -
    - -
  • - getTitle() ?> -
  • - -
- -find(); // $books is an object -?> - -isEmpty()): ?> -There are no books. - -There are count() ?> books: -
    - -
  • - getTitle() ?> -
  • - isLast()): ?> -
  • Do you want more books?
  • - - -
- -}}} - -Here is the list of methods you can call on a PropelCollection: - -{{{ -#!php -setFormatter('PropelArrayFormatter') - ->findOne(); -print_r($book); - => array('Id' => 123, 'Title' => 'War And Peace', 'ISBN' => '3245234535', 'AuthorId' => 456, 'PublisherId' => 567) -}}} - -Of course, the formatters take the calls to `with()` into account, so you can end up with a precise array representation of a model object: - -{{{ -#!php -setFormatter('PropelArrayFormatter') - ->with('Book.Author') - ->with('Book.Publisher') - ->findOne(); -print_r($book); - => array( - 'Id' => 123, - 'Title' => 'War And Peace', - 'ISBN' => '3245234535', - 'AuthorId' => 456, - 'PublisherId' => 567 - 'Author' => array( - 'Id' => 456, - 'FirstName' => 'Leo', - 'LastName' => 'Tolstoi' - ), - 'Publisher' => array( - 'Id' => 567, - 'Name' => 'Penguin' - ) - ) -}}} - -Propel provides four formatters: - * `PropelObjectFormatter`: The default formatter, returning a model object for `findOne()`, and a `PropelObjectCollection` of model objects for `find()` - * `PropelOnDemandFormatter`: To save memory for large resultsets, prefer this formatter ; it hydrates rows one by one as they are iterated on, and doesn't create a new Propel Model object at each row. Note that this formatter doesn't use the Instance Pool. - * `PropelArrayFormatter`: The array formatter, returning an associative array for `findOne()`, and a `PropelArrayCollection` of arrays for `find()` - * `PropelStatementFormatter`: The 'raw' formatter, returning a `PDOStatement` in any case. - -You can easily write your own formatter to format the resultas the way you want. A formatter is basically a subclass of `PropelFormatter` providing a `format()` and a `formatOne()` method expecting a PDO statement. - -== Writing Your Own business Logic Into A Query == - -=== Custom Filters === - -You can add custom methods to the query objects to make your queries smarter, more reusable, and more readable. Don't forget to return the current object (`$this`) in the new methods. - -{{{ -#!php -filterByPublishedAt(array('min' => time() - $nbDays * 24 * 60 * 60)); - } - - public function mostRecentFirst() - { - return $this->orderByPublishedAt('desc'); - } -} - -// You can now use your custom query and its methods together with the usual ones -$books = BookQuery::create() - ->recent() - ->mostRecentFirst() - ->find(); -}}} - -=== Custom Hooks === - -The query objects also allow you to add code to be executed before each query, by implementing one of the following methods: `preSelect()`, `preUpdate()`, and `preDelete()`. It makes the implementation of a 'soft delete' behavior very straightforward: - -{{{ -#!php -filterByDeletedAt(null); - } - - public function preDelete($con) - { - // mark the records as deleted instead of deleting them - return $this->update(array('DeletedAt' => time())); - } -} -}}} - -'''Tip''': You can create several custom queries for a given model, in order to separate the methods into logical classes. - -{{{ -#!php -where($this->getModelAliasOrName() . '.PublishedAt IS NOT NULL'); - } -} -// Use 'frontendBook' instead of 'Book' in the frontend to retrieve only published articles -$q = new frontendBookQuery(); -$books = $q->find(); -}}} - -'''Tip''': Due to late static binding issues in PHP 5.2, you cannot use the `create()` factory on an inherited query - unless you override it yoursel in the descendant class. Alternatively, Propel offers a global query factory named `PropelQuery`: - -{{{ -#!php -find(); -}}} \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/reference/Runtime-Configuration.txt b/airtime_mvc/library/propel/docs/reference/Runtime-Configuration.txt deleted file mode 100644 index 256c0a45e..000000000 --- a/airtime_mvc/library/propel/docs/reference/Runtime-Configuration.txt +++ /dev/null @@ -1,318 +0,0 @@ -= Runtime Configuration File = - -[[PageOutline]] - -== Example {{{runtime-conf.xml}}} File == - -Here is a the sample runtime configuration file. - -{{{ -#!xml - - - - propel-bookstore - console - 7 - - - - - sqlite - - DebugPDO - mysql:host=localhost;dbname=bookstore - testuser - password - - - - - - - - utf8 - - set search_path myschema, public - INSERT INTO BAR ('hey', 'there') - - - - - - mysql:host=slave-server1; dbname=bookstore - - - mysql:host=slave-server2; dbname=bookstore - - - - - - -
- - true - - - - true - 1 - -
-
-
-
-
-}}} - -== Explanation of Configuration Sections == - -Below you will find an explanation of the primary elements in the configuration. - -=== === - -If the '''''' element is present, Propel will use the specified information to instantiate a [http://pear.php.net/Log PEAR Log] logger. - -{{{ -#!xml - - - file - /path/to/logger.log - my-app - 7 - -}}} - -The nested elements correspond to the configuration options for the logger (options that would otherwise be passed to '''Log::factory()''' method). - -||'''Element'''||'''Default'''||'''Description'''|| -||''''''||file||The logger type.|| -||''''''||./propel.log||Name of log, meaning is dependent on type specified. (For ''file'' type this is the filename).|| -||''''''||propel||The identifier tag for the log.|| -||''''''||7 (PEAR_LOG_DEBUG)||The logging level.|| - -This log configuring API is designed to provide a simple way to get log output from Propel; however, if your application already has a logging mechanism, we recommend instead that you use your existing logger (writing a simple log adapter, if you are using an unsupported logger). See the [wiki:Documentation/1.5/07-Logging Logging documentation] for more info. - -=== === - -This is the top-level tag for Propel datasources configuration. - -{{{ -#!xml - - - -}}} - -=== === - -{{{ -#!xml - - - - -}}} -A specific datasource being configured. - * The @id must match the @name attribute from your {{{schema.xml}}}. - -=== === - -The adapter to use for Propel. Currently supported adapters: sqlite, pgsql, mysql, oracle, mssql. Note that it is possible that your adapter could be different from your connection driver (e.g. if using ODBC to connect to MSSQL database, you would use an ODBC PDO driver, but MSSQL Propel adapter). - -{{{ -#!xml - - - - - sqlite -}}} - -=== === - -The PDO database connection for the specified datasource. - -Nested elements define the DSN, connection options, other PDO attributes, and finally some Propel-specific initialization settings. - -{{{ -#!xml - - - - - -}}} - -==== ==== - -A custom PDO class (must be a PropelPDO subclass) that you would like to use for the PDO connection. - -{{{ -#!xml - - - - - - DebugPDO -}}} - -This can be used to specify the alternative '''DebugPDO''' class bundled with Propel, or your own subclass. ''Your class must extend PropelPDO, because Propel requires the ability to nest transactions (without having exceptions being thrown by PDO).'' - -==== ==== - -The PDO DSN that Propel will use to connect to the database for this datasource. - -{{{ -#!xml - - - - - - mysql:host=localhost;dbname=bookstore -}}} - -See the PHP documentation for specific format: - * [http://www.php.net/manual/en/ref.pdo-mysql.connection.php MySQL DSN] - * [http://www.php.net/manual/en/ref.pdo-pgsql.connection.php PostgreSQL DSN] - * [http://www.php.net/manual/en/ref.pdo-sqlite.connection.php SQLite DSN] - * [http://www.php.net/manual/en/ref.pdo-oci.connection.php Oracle DSN] - * [http://www.php.net/manual/en/ref.pdo-dblib.connection.php MSSQL DSN] - -Note that some database (e.g. PostgreSQL) specify username and password as part of the DSN while the others specify user and password separately. - -==== and ==== - -Specifies credentials for databases that specify username and password separately (e.g. MySQL, Oracle). - -{{{ -#!xml - - - - - - mysql:host=localhost;dbname=bookstore - test - testpass -}}} - -==== ==== - -Specify any options which ''must'' be specified when the PDO connection is created. For example, the ATTR_PERSISTENT option must be specified at object creation time. - -See the [http://www.php.net/pdo PDO documentation] for more details. - -{{{ -#!xml - - - - - - - - - -}}} - -==== ==== - -`` are similar to ``; the difference is that options specified in `` are set after the PDO object has been created. These are set using the [http://us.php.net/PDO-setAttribute PDO->setAttribute()] method. - -In addition to the standard attributes that can be set on the PDO object, there are also the following Propel-specific attributes that change the behavior of the PropelPDO connection: - -|| '''Attribute constant''' || '''Valid Values (Default)''' || '''Description''' || -|| PropelPDO::PROPEL_ATTR_CACHE_PREPARES || true/false (false) || Whether to have the PropelPDO connection cache the PDOStatement prepared statements. This will improve performance if you are executing the same query multiple times by your script (within a single request / script run). || - -''Note that attributes in the XML can be specified with or without the PDO:: (or PropelPDO::) constant prefix.'' - -{{{ -#!xml - - - - - - - - - - - -}}} - -'''Tip''': If you are using MySQL and get the following error : "SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active", you can try adding the following attribute: - -{{{ - -}}} - -==== ==== - -Settings are Propel-specific options used to further configure the connection -- or perform other user-defined initialization tasks. - -Currently supported settings are: - * charset - * queries - -===== charset ===== - -Specifies the character set to use. Currently you must specify the charset in the way that is understood by your RDBMS. Also note that not all database systems support specifying charset (e.g. SQLite must be compiled with specific charset support). Specifying this option will likely result in an exception if your database doesn't support the specified charset. - -{{{ -#!xml - - - - - - - - utf8 - -}}} - -===== queries ===== - -Specifies any SQL statements to run when the database connection is initialized. This can be used for any environment setup or db initialization you would like to perform. These statements will be executed with every Propel initialization (e.g. every PHP script load). - -{{{ -#!xml - - - - - - - - - set search_path myschema, public - INSERT INTO BAR ('hey', 'there') - - -}}} - -=== === - -{{{ -#!xml - - - - - -}}} - -The `` tag groups slave `` elements which provide support for configuring slave db servers -- when using Propel in a master-slave replication environment. See the [wiki:Documentation/1.5/Master-Slave Master-Slave documentation] for more information. The nested `` elements are configured the same way as the top-level `` element is configured. - -=== === - -The optional `` element may be provided to pass additional logging configuration options to DebugPDO. Note that these settings have no effect unless DebugPDO has been selected in [1.5/RuntimeConfiguration#debugpdo `runtime-conf.xml`] as the PDO connection class. See the [wiki:Documentation/1.5/07-Logging Logging documentation] for more information on configuring DebugPDO. \ No newline at end of file diff --git a/airtime_mvc/library/propel/docs/reference/Schema.txt b/airtime_mvc/library/propel/docs/reference/Schema.txt deleted file mode 100644 index b130c03fb..000000000 --- a/airtime_mvc/library/propel/docs/reference/Schema.txt +++ /dev/null @@ -1,398 +0,0 @@ -= Database Schema = - -[[PageOutline]] - -The schema for `schema.xml` contains a small number of elements with required and optional attributes. The Propel generator contains a [source:branches/1.5/generator/resources/dtd/database.dtd DTD] that can be used to validate your `schema.xml` document. Also, when you build your SQL and OM, the Propel generator will automatically validate your `schema.xml` file using a highly-detailed [source:branches/1.5/generator/resources/xsd/database.xsd XSD]. - -== At-a-Glance == - -The hierarchical tree relationship for the elements is: - -{{{ -#!xml - - -
- - - - - - - - - - - - - -
-
-}}} - -**Tip**: If you use an IDE supporting autocompletion in XML documents, you can take advantage of the XSD describing the `schema.xml` syntax to suggest elements and attributes as you type. To enable it, add a `xmlns:xsi` and a `xsi:noNamespaceSchemaLocation` attribute to the leading `` tag: - -{{{ -#!xml - -}}} - -== Detailed Reference == - -This page provides an alternate rendering of the Appendix B - Schema Reference from the user's guide. -It spells out in specific detail, just where each attribute or element belongs. - -First, some conventions: - - * Text surrounded by a '''/''' is text that you would provide and is not defined in the language. (i.e. a table name is a good example of this.) - * Optional items are surrounded by '''[''' and ''']''' characters. - * Items where you have an alternative choice have a '''|''' character between them (i.e. true|false) - * Alternative choices may be delimited by '''{''' and '''}''' to indicate that this is the default option, if not overridden elsewhere. - * '''...''' means repeat the previous item. - -=== element === - -Starting with the {{{}}} element. The ''attributes'' and ''elements'' available are: - -{{{ -#!xml - - - - ... - -}}} - -The `package`, `baseClass`, `basePeer`, `defaultPhpNamingMethod`, and `heavyIndexing` attributes are generally optional. -A Database element may include an `` element, or multiple `
` elements. - - * `defaultIdMethod` sets the default id method to use for auto-increment columns. - * `package` specifies the "package" for the generated classes. Classes are created in subdirectories according to the `package` value. - * `namespace` specifies the default namespace that generated model classes will use (PHP 5.3 only). This attribute can be completed or overridden at the table level. - * `baseClass` allows you to specify a default base class that all generated Propel objects should extend (in place of `propel.om.BaseObject`). - * `basePeer` instructs Propel to use a different SQL-generating `BasePeer` class (or sub-class of `BasePeer`) for all generated objects. - * `defaultPhpNamingMethod` the default naming method to use for tables of this database. Defaults to `underscore`, which transforms table names into CamelCase phpNames. - * `heavyIndexing` adds indexes for each component of the primary key (when using composite primary keys). - * `tablePrefix` adds a prefix to all the SQL table names. - -=== element === - -The `` element is pretty simple. It just includes a schema file from somewhere on the file systems. The format is: - -{{{ -#!xml - -}}} - -===
element === - -The `
` element is the most complicated of the usable elements. Its definition looks like this: - -{{{ -#!xml -
- - - ... - - ... - - ... - - ... - - ... -
-}}} - -According to the schema, `name` is the only required attribute. Also, the `idMethod`, `package`, `namespace`, `phpNamingMethod`, `baseClass`, `basePeer`, and `heavyIndexing` attributes all default to what is specified by the `` element. - -==== Description of Attributes ==== - - * `idMethod` sets the id method to use for auto-increment columns. - * `phpName` specifies object model class name. By default, Propel uses a CamelCase version of the table name as phpName. - * `package` specifies the "package" (or subdirectory) in which model classes get generated. - * `namespace` specifies the namespace that the generated model classes will use (PHP 5.3 only). If the table namespace starts with a `\`, it overrides the namespace defined in the `` tag; otherwise, the actual table namespace is the concatenation of the database namespace and the table namespace. - * `skipSql` instructs Propel not to generate DDL SQL for the specified table. This can be used together with `readOnly` for supperting VIEWS in Propel. - * `abstract` Whether the generated ''stub'' class will be abstract (e.g. if you're using inheritance) - * `phpNamingMethod` the naming method to use. Defaults to `underscore`, which transforms the table name into a CamelCase phpName. - * `baseClass` allows you to specify a class that the generated Propel objects should extend ({{{in place of propel.om.BaseObject}}}). - * `basePeer` instructs Propel to use a different SQL-generating `BasePeer` class (or sub-class of `BasePeer`). - * `heavyIndexing` adds indexes for each component of the primary key (when using composite primary keys). - * `readOnly` suppresses the mutator/setter methods, save() and delete() methods. - * `treeMode` is used to indicate that this table is part of a node tree. Currently the only supported values are "!NestedSet" (see [wiki:Documentation/1.5/Behaviors/nested_set]) and "!MaterializedPath" (deprecated). - * `reloadOnInsert` is used to indicate that the object should be reloaded from the database when an INSERT is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on INSERT. - * `reloadOnUpdate` is used to indicate that the object should be reloaded from the database when an UPDATE is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on UPDATE. - * `allowPkInsert` can be used if you want to define the primary key of a new object being inserted. By default if idMethod is "native", Propel would throw an exception. However, in some cases this feature is useful, for example if you do some replication of data in an master-master environment. It defaults to false. - -=== element === - -{{{ -#!xml - - [] - -}}} - -==== Description of Attributes ==== - - * {{{defaultValue}}} The default value that the object will have for this column in the PHP instance after creating a "new Object". This value is always interpreted as a string. - * {{{defaultExpr}}} The default value for this column as expressed in SQL. This value is used solely for the "sql" target which builds your database from the schema.xml file. The defaultExpr is the SQL expression used as the "default" for the column. - * {{{primaryString}}} A column defined as primary string serves as default value for a `__toString()` method in the generated Propel object. - -=== element === - -To link a column to another table use the following syntax: - -{{{ -#!xml - - - -}}} - -==== Description of Attributes ==== - - * {{{defaultJoin}}} This affects the default join type used in the generated `joinXXX()` methods in the model query class. Propel uses an INNER JOIN for foreign keys attached to a required column, and a LEFT JOIN for foreign keys attached to a non-required column, but you can override this in the foreign key element. - -=== element === - -To create an index on one or more columns, use the following syntax: - -{{{ -#!xml - - - ... - -}}} - -In some cases your RDBMS may require you to specify an index size. - -=== element === - -To create a unique index on one or more columns, use the following syntax: - -{{{ -#!xml - - - ... - -}}} - -In some cases your RDBMS may require you to specify an index size for unique indexes. - -=== element === - -If you are using a database that uses sequences for auto-increment columns (e.g. PostgreSQL or Oracle), you can customize the name of the sequence using the tag: - -{{{ -#!xml - -}}} - -== Column Types == - -Here are the Propel column types with some example mappings to native database and PHP types. There are also several ways to customize the mapping between these types. - -=== Text Types === - -||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''|| -||CHAR||Fixed-lenght character data||CHAR||string|| -||VARCHAR||Variable-lenght character data||VARCHAR||string|| -||LONGVARCHAR||Long variable-length character data||TEXT||string|| -||CLOB||Character LOB (locator object)||LONGTEXT||string|| - -=== Numeric Types === - -||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''|| -||NUMERIC||Numeric data||DECIMAL||string (PHP int is limited)|| -||DECIMAL||Decimal data||DECIMAL||string (PHP int is limited)|| -||TINYINT||Tiny integer ||TINYINT||int|| -||SMALLINT||Small integer ||SMALLINT||int|| -||INTEGER||Integer||INTEGER||int|| -||BIGINT||Large integer||BIGINT||string (PHP int is limited)|| -||REAL||Real number||REAL||double|| -||FLOAT||Floating point number||FLOAT||double|| -||DOUBLE||Floating point number||DOUBLE||double|| - -=== Binary Types === - -||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''|| -||BINARY||Fixed-length binary data||BLOB||double|| -||VARBINARY||Variable-length binary data||MEDIUMBLOB||double|| -||LONGVARBINARY||Long variable-length binary data||LONGBLOB||double|| -||BLOB||Binary LOB (locator object)||LONGBLOB||string|| - -=== Temporal (Date/Time) Types === - - -||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''|| -||DATE||Date (e.g. YYYY-MM-DD)||DATE||DateTime object|| -||TIME||Time (e.g. HH:MM:SS)||TIME||DateTime object|| -||TIMESTAMP||Date + time (e.g. YYYY-MM-DD HH:MM:SS)||TIMESTAMP||DateTime object|| - -==== Legacy Temporal Types ==== - -The following Propel 1.2 types are still supported, but are no longer needed with Propel 1.3. - -||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''|| -||BU_DATE||Pre-/post-epoch date (e.g. 1201-03-02)||DATE||DateTime object|| -||BU_TIMESTAMP||Pre-/post-epoch Date + time (e.g. 1201-03-02 12:33:00)||TIMESTAMP||DateTime object|| - -== Customizing Mappings == - -=== Specify Column Attributes === - -You can change the way that Propel maps its own types to native SQL types or to PHP types by overriding the values for a specific column. - -For example: - -(Overriding PHP type) -{{{ -#!xml - -}}} - -(Overriding SQL type) -{{{ -#!xml - -}}} - -=== Adding Vendor Info === - -Propel supports database-specific elements in the schema (currently only for MySQL). This "vendor" parameters affect the generated SQL. To add vendor data, add a `` tag with a `type` attribute specifying the target database vendor. In the `` tag, add `` tags with a `name` and a `value` attribue. For instance: - -{{{ -#!xml - - - - - -
-}}} - -This will change the generated SQL table creation to look like: - -{{{ -#!sql -CREATE TABLE book - () - ENGINE = InnoDB - DEFAULT CHARACTER SET utf8; -}}} - -Propel supports the following vendor parameters for MySQL: - -{{{ -Name | Example values ------------------|--------------- -// in element -Engine | MYISAM (default), BDB, HEAP, ISAM, InnoDB, MERGE, MRG_MYISAM -Charset | utf8, latin1, etc. -Collate | utf8_unicode_ci, latin1_german1_ci, etc. -Checksum | 0, 1 -Pack_Keys | 0, 1, DEFAULT -Delay_key_write | 0, 1 -// in element -Charset | utf8, latin1, etc. -Collate | utf8_unicode_ci, latin1_german1_ci, etc. -// in element -Index_type | FULLTEXT -}}} - -=== Using Custom Platform === - -For overriding the mapping between Propel types and native SQL types, you can create your own Platform class and override the mapping. - -For example: - -{{{ -#!php -setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, "DECIMAL")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "MEDIUMBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "LONGTEXT")); - } -} -}}} - -You must then specify that mapping in the {{{build.properties}}} for your project: - -{{{ -propel.platform.class = propel.engine.platform.${propel.database}Platform -}}} diff --git a/airtime_mvc/library/propel/generator/bin/propel-gen b/airtime_mvc/library/propel/generator/bin/propel-gen deleted file mode 100755 index ea10819b5..000000000 --- a/airtime_mvc/library/propel/generator/bin/propel-gen +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/sh -# Shell wrapper for Propel generator -# $Id$ -# -# This script will do the following: -# - check for PHING_COMMAND env, if found, use it. -# - if not found assume php is on the path -# - check for PROPEL_GEN_HOME env, if found use it -# - if not look for it - -if [ -z "$PROPEL_GEN_HOME" ] ; then - - # try to find Propel - if [ -d /opt/propel/generator ] ; then - PROPEL_GEN_HOME=/opt/propel/generator - fi - - if [ -d "${HOME}/opt/propel/generator" ] ; then - PROPEL_GEN_HOME="${HOME}/opt/propel/generator" - fi - - if [ -d "/usr/local/propel/generator" ] ; then - PROPEL_GEN_HOME="/usr/local/propel/generator" - fi - - if [ -d "${HOME}/usr/propel/generator" ] ; then - PROPEL_GEN_HOME="${HOME}/usr/propel/generator" - fi - - ## resolve links - the script name may be a link to phing's home - PRG="$0" - progname=`basename "$0"` - saveddir=`pwd` - - # need this for relative symlinks - dirname_prg=`dirname "$PRG"` - cd "$dirname_prg" - - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi - done - - cd "$saveddir" - - PROPEL_GEN_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - PROPEL_GEN_HOME=`cd "$PROPEL_GEN_HOME" && pwd` - - # make it available in PHP via getenv("PROPEL_GEN_HOME") - export PROPEL_GEN_HOME - -fi - -if [ -z "$PHING_COMMAND" ] ; then - # echo "WARNING: PHING_COMMAND environment not set. (Assuming phing on PATH)" - export PHING_COMMAND="phing" -fi - -if [ $# = 1 ] ; then - $PHING_COMMAND -f $PROPEL_GEN_HOME/build.xml -Dusing.propel-gen=true -Dproject.dir=$saveddir $* -else - $PHING_COMMAND -f $PROPEL_GEN_HOME/build.xml -Dusing.propel-gen=true -Dproject.dir=$* -fi diff --git a/airtime_mvc/library/propel/generator/build-propel.xml b/airtime_mvc/library/propel/generator/build-propel.xml deleted file mode 100644 index 036544248..000000000 --- a/airtime_mvc/library/propel/generator/build-propel.xml +++ /dev/null @@ -1,513 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ATTENTION: It appears you are using PostgreSQL and you have identifier-quoting turned on. - It is suggested that you disable identifier quoting when using PostgreSQL -- especially if you - have case-sensitive columns in your database. - - To disable identifier quoting, add the following property to your build.properties (or specify - it using -D on commandline): - - propel.disableIdentifierQuoting=true - - You can ignore this warning if you understand the issues related to case-sensitivity and Propel's - DDL-only implementation of identifier quoting. - - - - - - - - - - - - ATTENTION: It appears you are using the mysqli driver. - - This driver is no longer supported by Propel because Propel now uses PDO for database connections. - Please use mysqli driver instead. - Use 'mysql' instead of 'mysqli' for your propel.database property. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Output file: ${propel.runtime.phpconf.file} - XMLFile: ${propel.conf.dir}/${propel.runtime.conf.file} - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/build.properties-sample b/airtime_mvc/library/propel/generator/build.properties-sample deleted file mode 100644 index e94312a21..000000000 --- a/airtime_mvc/library/propel/generator/build.properties-sample +++ /dev/null @@ -1,192 +0,0 @@ -# ------------------------------------------------------------------- -# -# P R O P E L C O N F I G U R A T I O N F I L E -# -# ------------------------------------------------------------------- -# This file contains some example properties. Ideally properties -# should be specified in the project-specific build.properties file; -# however, this file can be used to specify non-default properties -# that you would like to use accross all of your Propel projects. -# ------------------------------------------------------------------- -# - -propel.home = . - -# ------------------------------------------------------------------- -# -# P R O J E C T -# -# ------------------------------------------------------------------- -# This is the name of your Propel project. The name of your Propel -# project is used (by default) to determine where the generator will -# find needed configuration files and will place resuilting build -# files. E.g. if your project is named 'killerapp', Propel will -# look here for schema.xml and runtime-conf.xml files: -# -# projects/killerapp/ -# -# ------------------------------------------------------------------- - -# You can set this here, but it's preferrable to set this in a -# project-specific build.properties file. -# -# propel.project = bookstore - -# ------------------------------------------------------------------- -# -# T A R G E T D A T A B A S E -# -# ------------------------------------------------------------------- -# This is the target database, only considered when generating -# the SQL for your Propel project. Your possible choices are: -# -# mssql, mysql, oracle, pgsql, sqlite -# ------------------------------------------------------------------- - -# You can set this here, but it's preferrable to set this in a -# project-specific build.properties file. -# -# propel.database = mysql - -# ------------------------------------------------------------------- -# -# O B J E C T M O D E L I N F O R M A T I O N -# -# ------------------------------------------------------------------- -# These settings will allow you to customize the way your -# Peer-based object model is created. -# ------------------------------------------------------------------- -# addGenericAccessors -# If true, Propel adds methods to get database fields by name/position. -# -# addGenericMutators -# If true, Propel adds methods to set database fields by name/position. -# -# addSaveMethod -# If true, Propel adds tracking code to determine how to save objects. -# -# addTimeStamp -# If true, Propel true puts time stamps in phpdoc of generated om files. -# -# basePrefix -# A string to pre-pend to the file names of base data and peer objects. -# -# complexObjectModel -# If true, Propel generates data objects with collection support and -# methods to easily retreive foreign key relationships. -# -# targetPackage -# Sets the PHP "package" the om files will generated to, e.g. -# "com.company.project.om". -# -# targetPlatform -# Sets whether Propel is building classes for php5 (default) -# or php4 (experimental). -# -# packageObjectModel -# Sets whether Propel is packaging ObjectModel fro several -# [package].schema.xml files. The -# attribute has to be set then. (warning: this is experimental!) -# -# ------------------------------------------------------------------- - -# classes will be put in (and included from) this directory -# e.g. if package is "bookstore" then om will expect include('bookstore/Book.php'); to work. -# use dot-path notation -- e.g. my.bookstore -> my/bookstore. -# -propel.targetPackage = ${propel.project} - -propel.addGenericAccessors = false -propel.addGenericMutators = false -propel.addSaveMethod = true -propel.addTimeStamp = true -propel.basePrefix = Base -propel.complexObjectModel = true -propel.targetPlatform = php5 -propel.packageObjectModel = false - -# ------------------------------------------------------------------- -# -# D B C O N N E C T I O N S E T T I N G S -# -# ------------------------------------------------------------------- -# PDO connection settings. These connection settings are used by -# build tagets that perform database operations (e.g. 'insert-sql', -# 'reverse'). -# -# You can set them here, but it's preferrable to set these properties -# in a project-specific build.properties file. -# - -# If you want to use a custom driver, specify it below, otherwise -# leave it blank or comment it out to use Creole stock driver. -# -# propel.database.driver = creole.drivers.sqlite.SQLiteConnection - -# Note that if you do not wish to specify the database (e.g. if you -# are using multiple databses) you can use the @DB@ token which -# will be replaced with a database at runtime. -# -# propel.database.url = mysql:host=$host;dbname=$database - -# For MySQL or Oracle, you also need to specify username & password -# propel.database.user = [db username] -# propel.database.password = [db password] - -# Use the URL below to specify a DSN to used to create the database. -# Note that this URL should not contain the database name, as you will -# get an error if the database does not exist. -# (This does not apply to SQLite since the databse is automatically created -# when the connection is made -- if it does not already exist.) -# -# propel.database.createUrl = mysql:host=$host;dbname=$database - - -# ------------------------------------------------------------------- -# -# D A T A B A S E TO X M L -# -# ------------------------------------------------------------------- -# -# samePhpName -# If true, the reverse task will set the phpName attribute for the -# tables and columns to be the same as SQL name. -# -# addVendorInfo -# If true, the reverse task will add vendor specific information -# to the database schema -# -# addValidators -# Bitfield like option to turn on/off addition of Validator and -# Rule tags to the schema. Uses a boolean syntax like in php.ini. -# Allowed tokens are: -# none add no validators) -# all add all validators) -# maxlength add maxlengths for string type columns) -# maxvalue add maxvalue for numeric columns) -# type add notmatch validators for numeric columns) -# required add required validators for required columns) -# unique add unique validators for unique indexes) -# Allowed operators are: -# & bitwise AND -# | bitwise OR -# ~ bitwise NOT -# -# ------------------------------------------------------------------- - -# propel.samePhpName = false -# propel.addVendorInfo=true -# propel.addValidators=none - - -# ------------------------------------------------------------------- -# -# D A T A B A S E B U I L D C O N F I G -# -# ------------------------------------------------------------------- -# Some databases provide some configuration options that can be set -# in this script. -# -# === MySQL -# propel.mysql.tableType -# Use this property to set the table type of generated tables (e.g. InnoDB, MyISAM). diff --git a/airtime_mvc/library/propel/generator/build.xml b/airtime_mvc/library/propel/generator/build.xml deleted file mode 100644 index 5005dae11..000000000 --- a/airtime_mvc/library/propel/generator/build.xml +++ /dev/null @@ -1,184 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Project name - - - - - No project.dir was specified, using default path: ./projects/${project} - - - - - - - - Processing additional properties file: ${additional.properties} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/generator/build.xml-local b/airtime_mvc/library/propel/generator/build.xml-local deleted file mode 100644 index ff57c3b2b..000000000 --- a/airtime_mvc/library/propel/generator/build.xml-local +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/generator/default.properties b/airtime_mvc/library/propel/generator/default.properties deleted file mode 100644 index 3d914e514..000000000 --- a/airtime_mvc/library/propel/generator/default.properties +++ /dev/null @@ -1,267 +0,0 @@ -# ------------------------------------------------------------------- -# -# D E F A U L T P R O P E R T I E S -# -# ------------------------------------------------------------------- -# This file sets default properties. You can override any of these -# by specifying your new value in the build.properties file for your -# project or a top-level build.properties file. Either way, you -# should not need to edit this file. -# ------------------------------------------------------------------- - - -# ------------------------------------------------------------------- -# -# B A S I C P R O P E R T I E S -# -# ------------------------------------------------------------------- - -propel.version = 1.5.2 - -propel.home = . - -propel.project = -propel.database = -propel.targetPackage = ${propel.project} -propel.runOnlyOnSchemaChange = false - -# Default behavior settings -# -propel.targetPlatform = php5 -propel.packageObjectModel = false -propel.useDateTimeClass = true -propel.dateTimeClass = DateTime - -propel.schema.validate = true -propel.schema.transform = false - -# controls what type of joins will be used in the doSelectJoin*() peer methods, -# if set to true, LEFT JOINS will be used, INNER JOINS otherwise -# see ticket #491, #588 -propel.useLeftJoinsInDoJoinMethods = true - -# ------------------------------------------------------------------- -# -# D A T A B A S E S E T T I N G S -# -# ------------------------------------------------------------------- - -propel.database.url = -propel.database.buildUrl = ${propel.database.url} -propel.database.createUrl = ${propel.database.buildUrl} - -propel.database.driver = - -propel.database.schema = -propel.database.encoding = -propel.database.manualCreation = false - -# if these arent blank then when we try to connect with insert-sql to a database -# that doesnt require them and it isnt in the build.properties it sends -# the ${blah} for the username and password -propel.database.user = -propel.database.password = - -# ------------------------------------------------------------------- -# -# D A T A B A S E T O X M L S E T T I N G S -# -# ------------------------------------------------------------------- - -propel.samePhpName = false -propel.addVendorInfo = false -propel.addValidators = none - -# ------------------------------------------------------------------- -# -# T E M P L A T E V A R I A B L E S -# -# ------------------------------------------------------------------- - -propel.addGenericAccessors = true -propel.addGenericMutators = true -propel.addSaveMethod = true -propel.addTimeStamp = false -propel.addValidateMethod = true -propel.addIncludes = false -propel.addHooks = true -propel.basePrefix = Base -propel.saveException = PropelException -propel.emulateForeignKeyConstraints = false - -# Identifier quoting is only implemented at the DDL layer at this point. -# Since this may result in undesired behavior (especially in Postgres), -# it can be disabled by setting this property to true in your build.properties file. -propel.disableIdentifierQuoting = false - -# These are the default formats that will be used when fetching values -# from temporal columns in Propel. You can always specify these when -# calling the methods directly, but for methods like getByName() -# it is nice to change the defaults. - -propel.defaultTimeStampFormat = Y-m-d H:i:s -propel.defaultTimeFormat = %X -propel.defaultDateFormat = %x - -propel.namespace.om = om -propel.namespace.map = map -propel.namespace.autoPackage = false - -propel.omtar.src.base = false -propel.omtar.src.extension = false -propel.omtar.bin.base = false -propel.omtar.bin.extension = false -propel.omtar.deleteFiles = false - -# ------------------------------------------------------------------- -# -# D I R E C T O R I E S -# -# ------------------------------------------------------------------- - -propel.project.dir = ${propel.home}/projects/${propel.project} - -propel.output.dir = ${propel.project.dir}/build -propel.schema.dir = ${propel.project.dir} -propel.templatePath = ${propel.home}/templates -propel.conf.dir = ${propel.project.dir} - -propel.doc.dir = ${propel.output.dir}/doc -propel.php.dir = ${propel.output.dir}/classes -propel.phpconf.dir = ${propel.output.dir}/conf -propel.phpdoc.dir = ${propel.output.dir}/phpdoc -propel.sql.dir = ${propel.output.dir}/sql -propel.graph.dir = ${propel.output.dir}/graph -propel.omtar.dir = ${propel.output.dir} - -# ------------------------------------------------------------------- -# -# D E F A U L T F I L E N A M ES -# -# ------------------------------------------------------------------- - -# propel.sqlfile - -propel.runtime.conf.file = runtime-conf.xml -propel.runtime.phpconf.file = ${propel.project}-conf.php -propel.runtime.phpconf-classmap.file = ${propel.project}-classmap.php -propel.default.schema.basename = schema - -# Can't use because of inconsistencies in where the files -# are named (some from build-propel.xml, but some from within templates) -# propel.default.data.basename = ${propel.project}-data - -propel.schema.xsd.file = ${propel.home}/resources/xsd/database.xsd -propel.schema.xsl.file = ${propel.home}/resources/xsl/database.xsl - -# ------------------------------------------------------------------- -# -# I N C L U D E A N D E X C L U D E S E T T I N G S -# -# ------------------------------------------------------------------- - -propel.schema.sql.includes = *schema.xml -propel.schema.sql.excludes = -propel.schema.doc.includes = *schema.xml -propel.schema.doc.excludes = -propel.schema.create-db.includes = *schema.xml -propel.schema.create-db.excludes = -propel.schema.init-sql.includes = *schema.xml -propel.schema.init-sql.excludes = id-table-schema.xml -propel.schema.om.includes = *schema.xml -propel.schema.om.excludes = id-table-schema.xml -propel.schema.datadtd.includes = *schema.xml -propel.schema.datadtd.excludes = id-table-schema.xml - -# ------------------------------------------------------------------- -# -# M A P P E R S E T T I N G S -# -# ------------------------------------------------------------------- - -# (note: data xml files are selected based on datadbmap file) -propel.datasql.mapper.from = *.xml -propel.datasql.mapper.to = *.sql - -propel.datadump.mapper.from = *schema.xml -propel.datadump.mapper.to = *data.xml - -propel.datadtd.mapper.from = *.xml -propel.datadtd.mapper.to = *.dtd - -propel.sql.mapper.from = *.xml -propel.sql.mapper.to = *.sql - - -# ------------------------------------------------------------------- -# -# B U I L D E R S E T T I N G S -# -# ------------------------------------------------------------------- - -# Object Model builders -propel.builder.peer.class = builder.om.PHP5PeerBuilder -propel.builder.object.class = builder.om.PHP5ObjectBuilder -propel.builder.objectstub.class = builder.om.PHP5ExtensionObjectBuilder -propel.builder.peerstub.class = builder.om.PHP5ExtensionPeerBuilder - -propel.builder.objectmultiextend.class = builder.om.PHP5MultiExtendObjectBuilder - -propel.builder.tablemap.class = builder.om.PHP5TableMapBuilder -propel.builder.query.class = builder.om.QueryBuilder -propel.builder.querystub.class = builder.om.ExtensionQueryBuilder -propel.builder.queryinheritance.class = builder.om.QueryInheritanceBuilder -propel.builder.queryinheritancestub.class = builder.om.ExtensionQueryInheritanceBuilder - -propel.builder.interface.class = builder.om.PHP5InterfaceBuilder - -propel.builder.node.class = builder.om.PHP5NodeBuilder -propel.builder.nodepeer.class = builder.om.PHP5NodePeerBuilder -propel.builder.nodestub.class = builder.om.PHP5ExtensionNodeBuilder -propel.builder.nodepeerstub.class = builder.om.PHP5ExtensionNodePeerBuilder - -propel.builder.nestedset.class = builder.om.PHP5NestedSetBuilder -propel.builder.nestedsetpeer.class = builder.om.PHP5NestedSetPeerBuilder - -propel.builder.pluralizer.class = builder.util.DefaultEnglishPluralizer - -# SQL builders - -propel.builder.ddl.class = builder.sql.${propel.database}.${propel.database}DDLBuilder -propel.builder.datasql.class = builder.sql.${propel.database}.${propel.database}DataSQLBuilder - -# Platform classes - -propel.platform.class = platform.${propel.database}Platform - -# Schema Parser (reverse-engineering) classes - -propel.reverse.parser.class = reverse.${propel.database}.${propel.database}SchemaParser - -# ------------------------------------------------------------------- -# -# M Y S Q L S P E C I F I C S E T T I N G S -# -# ------------------------------------------------------------------- - -# Default table type -propel.mysqlTableType = MyISAM -# Keyword used to specify table type. MYSQL < 5 should use TYPE instead -propel.mysqlTableEngineKeyword = ENGINE - -# ------------------------------------------------------------------- -# -# B E H A V I O R S E T T I N G S -# -# ------------------------------------------------------------------- - -propel.behavior.timestampable.class = behavior.TimestampableBehavior -propel.behavior.alternative_coding_standards.class = behavior.AlternativeCodingStandardsBehavior -propel.behavior.soft_delete.class = behavior.SoftDeleteBehavior -propel.behavior.auto_add_pk.class = behavior.AutoAddPkBehavior -propel.behavior.nested_set.class = behavior.nestedset.NestedSetBehavior -propel.behavior.sortable.class = behavior.sortable.SortableBehavior -propel.behavior.sluggable.class = behavior.sluggable.SluggableBehavior -propel.behavior.concrete_inheritance.class = behavior.concrete_inheritance.ConcreteInheritanceBehavior -propel.behavior.query_cache.class = behavior.query_cache.QueryCacheBehavior -propel.behavior.aggregate_column.class = behavior.aggregate_column.AggregateColumnBehavior \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/AlternativeCodingStandardsBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/AlternativeCodingStandardsBehavior.php deleted file mode 100644 index d9a9de6e2..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/AlternativeCodingStandardsBehavior.php +++ /dev/null @@ -1,133 +0,0 @@ - 'true', - 'remove_closing_comments' => 'true', - 'use_whitespace' => 'true', - 'tab_size' => 2, - 'strip_comments' => 'false' - ); - - public function objectFilter(&$script) - { - return $this->filter($script); - } - - public function extensionObjectFilter(&$script) - { - return $this->filter($script); - } - - public function queryFilter(&$script) - { - return $this->filter($script); - } - - public function extensionQueryFilter(&$script) - { - return $this->filter($script); - } - - public function peerFilter(&$script) - { - return $this->filter($script); - } - - public function extensionPeerFilter(&$script) - { - return $this->filter($script); - } - - public function tableMapFilter(&$script) - { - return $this->filter($script); - } - - /** - * Transform the coding standards of a PHP sourcecode string - * - * @param string $script A script string to be filtered, passed as reference - */ - protected function filter(&$script) - { - $filter = array(); - if($this->getParameter('brackets_newline') == 'true') { - $filter['#^(\t*)\}\h(else|elseif|catch)(.*)\h\{$#m'] = "$1} -$1$2$3 -$1{"; - $filter['#^(\t*)(\w.*)\h\{$#m'] = "$1$2 -$1{"; - } - if ($this->getParameter('remove_closing_comments') == 'true') { - $filter['#^(\t*)} //.*$#m'] = "$1}"; - } - if ($this->getParameter('use_whitespace') == 'true') { - $filter['#\t#'] = str_repeat(' ', $this->getParameter('tab_size')); - } - - $script = preg_replace(array_keys($filter), array_values($filter), $script); - - if ($this->getParameter('strip_comments') == 'true') { - $script = self::stripComments($script); - } - } - - /** - * Remove inline and codeblock comments from a PHP code string - * @param string $code The input code - * @return string The input code, without comments - */ - public static function stripComments($code) - { - $output = ''; - $commentTokens = array(T_COMMENT, T_DOC_COMMENT); - foreach (token_get_all($code) as $token) { - if (is_array($token)) { - if (in_array($token[0], $commentTokens)) continue; - $token = $token[1]; - } - $output .= $token; - } - - return $output; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/AutoAddPkBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/AutoAddPkBehavior.php deleted file mode 100644 index 10b8f4edb..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/AutoAddPkBehavior.php +++ /dev/null @@ -1,54 +0,0 @@ - 'id', - 'autoIncrement' => 'true', - 'type' => 'INTEGER' - ); - - /** - * Copy the behavior to the database tables - * Only for tables that have no Pk - */ - public function modifyDatabase() - { - foreach ($this->getDatabase()->getTables() as $table) { - if(!$table->hasPrimaryKey()) { - $b = clone $this; - $table->addBehavior($b); - } - } - } - - /** - * Add the primary key to the current table - */ - public function modifyTable() - { - $table = $this->getTable(); - if (!$table->hasPrimaryKey() && !$table->hasBehavior('concrete_inheritance')) { - $columnAttributes = array_merge(array('primaryKey' => 'true'), $this->getParameters()); - $this->getTable()->addColumn($columnAttributes); - } - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/SoftDeleteBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/SoftDeleteBehavior.php deleted file mode 100644 index f87bec0bb..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/SoftDeleteBehavior.php +++ /dev/null @@ -1,467 +0,0 @@ - 'deleted_at', - ); - - /** - * Add the deleted_column to the current table - */ - public function modifyTable() - { - if(!$this->getTable()->containsColumn($this->getParameter('deleted_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('deleted_column'), - 'type' => 'TIMESTAMP' - )); - } - } - - protected function getColumnSetter() - { - return 'set' . $this->getColumnForParameter('deleted_column')->getPhpName(); - } - - public function objectMethods($builder) - { - $script = ''; - $this->addObjectForceDelete($script); - $this->addObjectUndelete($script); - return $script; - } - - public function addObjectForceDelete(&$script) - { - $script .= " -/** - * Bypass the soft_delete behavior and force a hard delete of the current object - */ -public function forceDelete(PropelPDO \$con = null) -{ - {$this->getTable()->getPhpName()}Peer::disableSoftDelete(); - \$this->delete(\$con); -} -"; - } - - public function addObjectUndelete(&$script) - { - $script .= " -/** - * Undelete a row that was soft_deleted - * - * @return int The number of rows affected by this update and any referring fk objects' save() operations. - */ -public function unDelete(PropelPDO \$con = null) -{ - \$this->{$this->getColumnSetter()}(null); - return \$this->save(\$con); -} -"; - } - - public function preDelete($builder) - { - return <<getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled()) { - \$this->{$this->getColumnSetter()}(time()); - \$this->save(\$con); - \$con->commit(); - {$builder->getStubPeerBuilder()->getClassname()}::removeInstanceFromPool(\$this); - return; -} -EOT; - } - - public function queryAttributes() - { - return "protected static \$softDelete = true; -protected \$localSoftDelete = true; -"; - } - - public function queryMethods($builder) - { - $this->builder = $builder; - $script = ''; - $this->addQueryIncludeDeleted($script); - $this->addQuerySoftDelete($script); - $this->addQueryForceDelete($script); - $this->addQueryForceDeleteAll($script); - $this->addQueryUnDelete($script); - $this->addQueryEnableSoftDelete($script); - $this->addQueryDisableSoftDelete($script); - $this->addQueryIsSoftDeleteEnabled($script); - - return $script; - } - - public function addQueryIncludeDeleted(&$script) - { - $script .= " -/** - * Temporarily disable the filter on deleted rows - * Valid only for the current query - * - * @see {$this->builder->getStubQueryBuilder()->getClassname()}::disableSoftDelete() to disable the filter for more than one query - * - * @return {$this->builder->getStubQueryBuilder()->getClassname()} The current query, for fuid interface - */ -public function includeDeleted() -{ - \$this->localSoftDelete = false; - return \$this; -} -"; - } - - public function addQuerySoftDelete(&$script) - { - $script .= " -/** - * Soft delete the selected rows - * - * @param PropelPDO \$con an optional connection object - * - * @return int Number of updated rows - */ -public function softDelete(PropelPDO \$con = null) -{ - return \$this->update(array('{$this->getColumnForParameter('deleted_column')->getPhpName()}' => time()), \$con); -} -"; - } - - public function addQueryForceDelete(&$script) - { - $script .= " -/** - * Bypass the soft_delete behavior and force a hard delete of the selected rows - * - * @param PropelPDO \$con an optional connection object - * - * @return int Number of deleted rows - */ -public function forceDelete(PropelPDO \$con = null) -{ - return {$this->builder->getPeerClassname()}::doForceDelete(\$this, \$con); -} -"; - } - - public function addQueryForceDeleteAll(&$script) - { - $script .= " -/** - * Bypass the soft_delete behavior and force a hard delete of all the rows - * - * @param PropelPDO \$con an optional connection object - * - * @return int Number of deleted rows - */ -public function forceDeleteAll(PropelPDO \$con = null) -{ - return {$this->builder->getPeerClassname()}::doForceDeleteAll(\$con);} -"; - } - - public function addQueryUnDelete(&$script) - { - $script .= " -/** - * Undelete selected rows - * - * @param PropelPDO \$con an optional connection object - * - * @return int The number of rows affected by this update and any referring fk objects' save() operations. - */ -public function unDelete(PropelPDO \$con = null) -{ - return \$this->update(array('{$this->getColumnForParameter('deleted_column')->getPhpName()}' => null), \$con); -} -"; - } - - public function addQueryEnableSoftDelete(&$script) - { - $script .= " -/** - * Enable the soft_delete behavior for this model - */ -public static function enableSoftDelete() -{ - self::\$softDelete = true; -} -"; - } - - public function addQueryDisableSoftDelete(&$script) - { - $script .= " -/** - * Disable the soft_delete behavior for this model - */ -public static function disableSoftDelete() -{ - self::\$softDelete = false; -} -"; - } - - public function addQueryIsSoftDeleteEnabled(&$script) - { - $script .= " -/** - * Check the soft_delete behavior for this model - * - * @return boolean true if the soft_delete behavior is enabled - */ -public static function isSoftDeleteEnabled() -{ - return self::\$softDelete; -} -"; - } - - public function preSelectQuery($builder) - { - return <<getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled() && \$this->localSoftDelete) { - \$this->addUsingAlias({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL); -} else { - {$this->getTable()->getPhpName()}Peer::enableSoftDelete(); -} -EOT; - } - - public function preDeleteQuery($builder) - { - return <<getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled() && \$this->localSoftDelete) { - return \$this->softDelete(\$con); -} else { - return \$this->hasWhereClause() ? \$this->forceDelete(\$con) : \$this->forceDeleteAll(\$con); -} -EOT; - } - - public function staticMethods($builder) - { - $builder->declareClassFromBuilder($builder->getStubQueryBuilder()); - $this->builder = $builder; - $script = ''; - $this->addPeerEnableSoftDelete($script); - $this->addPeerDisableSoftDelete($script); - $this->addPeerIsSoftDeleteEnabled($script); - $this->addPeerDoSoftDelete($script); - $this->addPeerDoDelete2($script); - $this->addPeerDoSoftDeleteAll($script); - $this->addPeerDoDeleteAll2($script); - - return $script; - } - - public function addPeerEnableSoftDelete(&$script) - { - $script .= " -/** - * Enable the soft_delete behavior for this model - */ -public static function enableSoftDelete() -{ - {$this->builder->getStubQueryBuilder()->getClassname()}::enableSoftDelete(); - // some soft_deleted objects may be in the instance pool - {$this->builder->getStubPeerBuilder()->getClassname()}::clearInstancePool(); -} -"; - } - - public function addPeerDisableSoftDelete(&$script) - { - $script .= " -/** - * Disable the soft_delete behavior for this model - */ -public static function disableSoftDelete() -{ - {$this->builder->getStubQueryBuilder()->getClassname()}::disableSoftDelete(); -} -"; - } - - public function addPeerIsSoftDeleteEnabled(&$script) - { - $script .= " -/** - * Check the soft_delete behavior for this model - * @return boolean true if the soft_delete behavior is enabled - */ -public static function isSoftDeleteEnabled() -{ - return {$this->builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled(); -} -"; - } - - public function addPeerDoSoftDelete(&$script) - { - $script .= " -/** - * Soft delete records, given a {$this->getTable()->getPhpName()} or Criteria object OR a primary key value. - * - * @param mixed \$values Criteria or {$this->getTable()->getPhpName()} object or primary key or array of primary keys - * which is used to create the DELETE statement - * @param PropelPDO \$con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ -public static function doSoftDelete(\$values, PropelPDO \$con = null) -{ - if (\$values instanceof Criteria) { - // rename for clarity - \$criteria = clone \$values; - } elseif (\$values instanceof {$this->getTable()->getPhpName()}) { - // create criteria based on pk values - \$criteria = \$values->buildPkeyCriteria(); - } else { - // it must be the primary key - \$criteria = new Criteria(self::DATABASE_NAME);"; - $pks = $this->getTable()->getPrimaryKey(); - if (count($pks)>1) { - $i = 0; - foreach ($pks as $col) { - $script .= " - \$criteria->add({$col->getConstantName()}, \$values[$i], Criteria::EQUAL);"; - $i++; - } - } else { - $col = $pks[0]; - $script .= " - \$criteria->add({$col->getConstantName()}, (array) \$values, Criteria::IN);"; - } - $script .= " - } - \$criteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, time()); - return {$this->getTable()->getPhpName()}Peer::doUpdate(\$criteria, \$con); -} -"; - } - - public function addPeerDoDelete2(&$script) - { - $script .= " -/** - * Delete or soft delete records, depending on {$this->getTable()->getPhpName()}Peer::\$softDelete - * - * @param mixed \$values Criteria or {$this->getTable()->getPhpName()} object or primary key or array of primary keys - * which is used to create the DELETE statement - * @param PropelPDO \$con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ -public static function doDelete2(\$values, PropelPDO \$con = null) -{ - if ({$this->getTable()->getPhpName()}Peer::isSoftDeleteEnabled()) { - return {$this->getTable()->getPhpName()}Peer::doSoftDelete(\$values, \$con); - } else { - return {$this->getTable()->getPhpName()}Peer::doForceDelete(\$values, \$con); - } -}"; - } - - public function addPeerDoSoftDeleteAll(&$script) - { - $script .= " -/** - * Method to soft delete all rows from the {$this->getTable()->getName()} table. - * - * @param PropelPDO \$con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ -public static function doSoftDeleteAll(PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection({$this->getTable()->getPhpName()}Peer::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - \$selectCriteria = new Criteria(); - \$selectCriteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL); - \$selectCriteria->setDbName({$this->getTable()->getPhpName()}Peer::DATABASE_NAME); - \$modifyCriteria = new Criteria(); - \$modifyCriteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, time()); - return BasePeer::doUpdate(\$selectCriteria, \$modifyCriteria, \$con); -} -"; - } - - public function addPeerDoDeleteAll2(&$script) - { - $script .= " -/** - * Delete or soft delete all records, depending on {$this->getTable()->getPhpName()}Peer::\$softDelete - * - * @param PropelPDO \$con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ -public static function doDeleteAll2(PropelPDO \$con = null) -{ - if ({$this->getTable()->getPhpName()}Peer::isSoftDeleteEnabled()) { - return {$this->getTable()->getPhpName()}Peer::doSoftDeleteAll(\$con); - } else { - return {$this->getTable()->getPhpName()}Peer::doForceDeleteAll(\$con); - } -} -"; - } - - public function preSelect($builder) - { - return <<getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled()) { - \$criteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL); -} else { - {$this->getTable()->getPhpName()}Peer::enableSoftDelete(); -} -EOT; - } - - public function peerFilter(&$script) - { - $script = str_replace(array( - 'public static function doDelete(', - 'public static function doDelete2(', - 'public static function doDeleteAll(', - 'public static function doDeleteAll2(' - ), array( - 'public static function doForceDelete(', - 'public static function doDelete(', - 'public static function doForceDeleteAll(', - 'public static function doDeleteAll(' - ), $script); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/TimestampableBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/TimestampableBehavior.php deleted file mode 100644 index bf73b7669..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/TimestampableBehavior.php +++ /dev/null @@ -1,171 +0,0 @@ - 'created_at', - 'update_column' => 'updated_at' - ); - - /** - * Add the create_column and update_columns to the current table - */ - public function modifyTable() - { - if(!$this->getTable()->containsColumn($this->getParameter('create_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('create_column'), - 'type' => 'TIMESTAMP' - )); - } - if(!$this->getTable()->containsColumn($this->getParameter('update_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('update_column'), - 'type' => 'TIMESTAMP' - )); - } - } - - /** - * Get the setter of one of the columns of the behavior - * - * @param string $column One of the behavior colums, 'create_column' or 'update_column' - * @return string The related setter, 'setCreatedOn' or 'setUpdatedOn' - */ - protected function getColumnSetter($column) - { - return 'set' . $this->getColumnForParameter($column)->getPhpName(); - } - - /** - * Add code in ObjectBuilder::preUpdate - * - * @return string The code to put at the hook - */ - public function preUpdate() - { - return "if (\$this->isModified() && !\$this->isColumnModified(" . $this->getColumnForParameter('update_column')->getConstantName() . ")) { - \$this->" . $this->getColumnSetter('update_column') . "(time()); -}"; - } - - /** - * Add code in ObjectBuilder::preInsert - * - * @return string The code to put at the hook - */ - public function preInsert() - { - return "if (!\$this->isColumnModified(" . $this->getColumnForParameter('create_column')->getConstantName() . ")) { - \$this->" . $this->getColumnSetter('create_column') . "(time()); -} -if (!\$this->isColumnModified(" . $this->getColumnForParameter('update_column')->getConstantName() . ")) { - \$this->" . $this->getColumnSetter('update_column') . "(time()); -}"; - } - - public function objectMethods($builder) - { - return " -/** - * Mark the current object so that the update date doesn't get updated during next save - * - * @return " . $builder->getStubObjectBuilder()->getClassname() . " The current object (for fluent API support) - */ -public function keepUpdateDateUnchanged() -{ - \$this->modifiedColumns[] = " . $this->getColumnForParameter('update_column')->getConstantName() . "; - return \$this; -} -"; - } - - public function queryMethods($builder) - { - $queryClassName = $builder->getStubQueryBuilder()->getClassname(); - $updateColumnConstant = $this->getColumnForParameter('update_column')->getConstantName(); - $createColumnConstant = $this->getColumnForParameter('create_column')->getConstantName(); - return " -/** - * Filter by the latest updated - * - * @param int \$nbDays Maximum age of the latest update in days - * - * @return $queryClassName The current query, for fuid interface - */ -public function recentlyUpdated(\$nbDays = 7) -{ - return \$this->addUsingAlias($updateColumnConstant, time() - \$nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); -} - -/** - * Filter by the latest created - * - * @param int \$nbDays Maximum age of in days - * - * @return $queryClassName The current query, for fuid interface - */ -public function recentlyCreated(\$nbDays = 7) -{ - return \$this->addUsingAlias($createColumnConstant, time() - \$nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); -} - -/** - * Order by update date desc - * - * @return $queryClassName The current query, for fuid interface - */ -public function lastUpdatedFirst() -{ - return \$this->addDescendingOrderByColumn($updateColumnConstant); -} - -/** - * Order by update date asc - * - * @return $queryClassName The current query, for fuid interface - */ -public function firstUpdatedFirst() -{ - return \$this->addAscendingOrderByColumn($updateColumnConstant); -} - -/** - * Order by create date desc - * - * @return $queryClassName The current query, for fuid interface - */ -public function lastCreatedFirst() -{ - return \$this->addDescendingOrderByColumn($createColumnConstant); -} - -/** - * Order by create date asc - * - * @return $queryClassName The current query, for fuid interface - */ -public function firstCreatedFirst() -{ - return \$this->addAscendingOrderByColumn($createColumnConstant); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnBehavior.php deleted file mode 100644 index 16a996466..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnBehavior.php +++ /dev/null @@ -1,122 +0,0 @@ - null, - 'expression' => null, - 'foreign_table' => null, - ); - - /** - * Add the aggregate key to the current table - */ - public function modifyTable() - { - $table = $this->getTable(); - if (!$columnName = $this->getParameter('name')) { - throw new InvalidArgumentException(sprintf('You must define a \'name\' parameter for the \'aggregate_column\' behavior in the \'%s\' table', $table->getName())); - } - - // add the aggregate column if not present - if(!$this->getTable()->containsColumn($columnName)) { - $column = $this->getTable()->addColumn(array( - 'name' => $columnName, - 'type' => 'INTEGER', - )); - } - - // add a behavior in the foreign table to autoupdate the aggregate column - $foreignTable = $this->getForeignTable(); - if (!$foreignTable->hasBehavior('concrete_inheritance_parent')) { - $relationBehavior = new AggregateColumnRelationBehavior(); - $relationBehavior->setName('aggregate_column_relation'); - $foreignKey = $this->getForeignKey(); - $relationBehavior->addParameter(array('name' => 'foreign_table', 'value' => $table->getName())); - $relationBehavior->addParameter(array('name' => 'update_method', 'value' => 'update' . $this->getColumn()->getPhpName())); - $foreignTable->addBehavior($relationBehavior); - } - } - - public function objectMethods($builder) - { - if (!$foreignTableName = $this->getParameter('foreign_table')) { - throw new InvalidArgumentException(sprintf('You must define a \'foreign_table\' parameter for the \'aggregate_column\' behavior in the \'%s\' table', $this->getTable()->getName())); - } - $script = ''; - $script .= $this->addObjectCompute(); - $script .= $this->addObjectUpdate(); - - return $script; - } - - protected function addObjectCompute() - { - $conditions = array(); - $bindings = array(); - foreach ($this->getForeignKey()->getColumnObjectsMapping() as $index => $columnReference) { - $conditions[] = $columnReference['local']->getFullyQualifiedName() . ' = :p' . ($index + 1); - $bindings[$index + 1] = $columnReference['foreign']->getPhpName(); - } - $sql = sprintf('SELECT %s FROM %s WHERE %s', - $this->getParameter('expression'), - $this->getTable()->getDatabase()->getPlatform()->quoteIdentifier($this->getParameter('foreign_table')), - implode(' AND ', $conditions) - ); - - return $this->renderTemplate('objectCompute', array( - 'column' => $this->getColumn(), - 'sql' => $sql, - 'bindings' => $bindings, - )); - } - - protected function addObjectUpdate() - { - return $this->renderTemplate('objectUpdate', array( - 'column' => $this->getColumn(), - )); - } - - protected function getForeignTable() - { - return $this->getTable()->getDatabase()->getTable($this->getParameter('foreign_table')); - } - - protected function getForeignKey() - { - $foreignTable = $this->getForeignTable(); - // let's infer the relation from the foreign table - $fks = $foreignTable->getForeignKeysReferencingTable($this->getTable()->getName()); - if (!$fks) { - throw new InvalidArgumentException(sprintf('You must define a foreign key to the \'%s\' table in the \'%s\' table to enable the \'aggregate_column\' behavior', $this->getTable()->getName(), $foreignTable->getName())); - } - // FIXME doesn't work when more than one fk to the same table - return array_shift($fks); - } - - protected function getColumn() - { - return $this->getTable()->getColumn($this->getParameter('name')); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnRelationBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnRelationBehavior.php deleted file mode 100644 index 1fce170a1..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/AggregateColumnRelationBehavior.php +++ /dev/null @@ -1,164 +0,0 @@ - '', - 'update_method' => '', - ); - - public function postSave($builder) - { - $relationName = $this->getRelationName($builder); - return "\$this->updateRelated{$relationName}(\$con);"; - } - - // no need for a postDelete() hook, since delete() uses Query::delete(), - // which already has a hook - - public function objectAttributes($builder) - { - $relationName = $this->getRelationName($builder); - return "protected \$old{$relationName}; -"; - } - - public function objectMethods($builder) - { - return $this->addObjectUpdateRelated($builder); - } - - protected function addObjectUpdateRelated($builder) - { - $relationName = $this->getRelationName($builder); - $updateMethodName = $this->getParameter('update_method'); - return $this->renderTemplate('objectUpdateRelated', array( - 'relationName' => $relationName, - 'variableName' => self::lcfirst($relationName), - 'updateMethodName' => $this->getParameter('update_method'), - )); - } - - public function objectFilter(&$script, $builder) - { - $relationName = $this->getRelationName($builder); - $relatedClass = $this->getForeignTable()->getPhpName(); - $search = " public function set{$relationName}({$relatedClass} \$v = null) - {"; - $replace = $search . " - // aggregate_column_relation behavior - if (null !== \$this->a{$relationName} && \$v !== \$this->a{$relationName}) { - \$this->old{$relationName} = \$this->a{$relationName}; - }"; - $script = str_replace($search, $replace, $script); - } - - public function preUpdateQuery($builder) - { - return $this->getFindRelated($builder); - } - - public function preDeleteQuery($builder) - { - return $this->getFindRelated($builder); - } - - protected function getFindRelated($builder) - { - $relationName = $this->getRelationName($builder); - return "\$this->findRelated{$relationName}s(\$con);"; - } - - public function postUpdateQuery($builder) - { - return $this->getUpdateRelated($builder); - } - - public function postDeleteQuery($builder) - { - return $this->getUpdateRelated($builder); - } - - protected function getUpdateRelated($builder) - { - $relationName = $this->getRelationName($builder); - return "\$this->updateRelated{$relationName}s(\$con);"; - } - - public function queryMethods($builder) - { - $script = ''; - $script .= $this->addQueryFindRelated($builder); - $script .= $this->addQueryUpdateRelated($builder); - - return $script; - } - - protected function addQueryFindRelated($builder) - { - $foreignKey = $this->getForeignKey(); - $relationName = $this->getRelationName($builder); - return $this->renderTemplate('queryFindRelated', array( - 'foreignTable' => $this->getForeignTable(), - 'relationName' => $relationName, - 'variableName' => self::lcfirst($relationName), - 'foreignQueryName' => $foreignKey->getForeignTable()->getPhpName() . 'Query', - 'refRelationName' => $builder->getRefFKPhpNameAffix($foreignKey), - )); - } - - protected function addQueryUpdateRelated($builder) - { - $relationName = $this->getRelationName($builder); - return $this->renderTemplate('queryUpdateRelated', array( - 'relationName' => $relationName, - 'variableName' => self::lcfirst($relationName), - 'updateMethodName' => $this->getParameter('update_method'), - )); - } - - protected function getForeignTable() - { - return $this->getTable()->getDatabase()->getTable($this->getParameter('foreign_table')); - } - - protected function getForeignKey() - { - $foreignTable = $this->getForeignTable(); - // let's infer the relation from the foreign table - $fks = $this->getTable()->getForeignKeysReferencingTable($foreignTable->getName()); - // FIXME doesn't work when more than one fk to the same table - return array_shift($fks); - } - - protected function getRelationName($builder) - { - return $builder->getFKPhpNameAffix($this->getForeignKey()); - } - - protected static function lcfirst($input) - { - // no lcfirst in php<5.3... - $input[0] = strtolower($input[0]); - return $input; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectCompute.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectCompute.php deleted file mode 100644 index 00e183872..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectCompute.php +++ /dev/null @@ -1,17 +0,0 @@ - -/** - * Computes the value of the aggregate column getName() ?> - * - * @param PropelPDO $con A connection object - * - * @return mixed The scalar result from the aggregate query - */ -public function computegetPhpName() ?>(PropelPDO $con) -{ - $stmt = $con->prepare(''); - $binding): ?> - $stmt->bindValue(':p', $this->get()); - - $stmt->execute(); - return $stmt->fetchColumn(); -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdate.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdate.php deleted file mode 100644 index 9236bad3e..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdate.php +++ /dev/null @@ -1,11 +0,0 @@ - -/** - * Updates the aggregate column getName() ?> - * - * @param PropelPDO $con A connection object - */ -public function updategetPhpName() ?>(PropelPDO $con) -{ - $this->setgetPhpName() ?>($this->computegetPhpName() ?>($con)); - $this->save($con); -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdateRelated.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdateRelated.php deleted file mode 100644 index d5892b0f2..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/objectUpdateRelated.php +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Update the aggregate column in the related object - * - * @param PropelPDO $con A connection object - */ -protected function updateRelated(PropelPDO $con) -{ - if ($ = $this->get()) { - $->($con); - } - if ($this->old) { - $this->old->($con); - $this->old = null; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryFindRelated.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryFindRelated.php deleted file mode 100644 index 252adf195..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryFindRelated.php +++ /dev/null @@ -1,20 +0,0 @@ - -/** - * Finds the related getPhpName() ?> objects and keep them for later - * - * @param PropelPDO $con A connection object - */ -protected function findRelateds($con) -{ - $criteria = clone $this; - if ($this->useAliasInSQL) { - $alias = $this->getModelAlias(); - $criteria->removeAlias($alias); - } else { - $alias = ''; - } - $this->s = ::create() - ->join($alias) - ->mergeWith($criteria) - ->find($con); -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryUpdateRelated.php b/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryUpdateRelated.php deleted file mode 100644 index 056264c55..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/aggregate_column/templates/queryUpdateRelated.php +++ /dev/null @@ -1,8 +0,0 @@ - -protected function updateRelateds($con) -{ - foreach ($this->s as $) { - $->($con); - } - $this->s = array(); -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceBehavior.php deleted file mode 100644 index 8d5011a94..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceBehavior.php +++ /dev/null @@ -1,235 +0,0 @@ - '', - 'descendant_column' => 'descendant_class', - 'copy_data_to_parent' => 'true' - ); - - public function modifyTable() - { - $table = $this->getTable(); - $parentTable = $this->getParentTable(); - - if ($this->isCopyData()) { - // tell the parent table that it has a descendant - if (!$parentTable->hasBehavior('concrete_inheritance_parent')) { - $parentBehavior = new ConcreteInheritanceParentBehavior(); - $parentBehavior->setName('concrete_inheritance_parent'); - $parentBehavior->addParameter(array('name' => 'descendant_column', 'value' => $this->getParameter('descendant_column'))); - $parentTable->addBehavior($parentBehavior); - // The parent table's behavior modifyTable() must be executed before this one - $parentBehavior->getTableModifier()->modifyTable(); - $parentBehavior->setTableModified(true); - } - } - - // Add the columns of the parent table - foreach ($parentTable->getColumns() as $column) { - if ($column->getName() == $this->getParameter('descendant_column')) { - continue; - } - if ($table->containsColumn($column->getName())) { - continue; - } - $copiedColumn = clone $column; - if ($column->isAutoIncrement() && $this->isCopyData()) { - $copiedColumn->setAutoIncrement(false); - } - $table->addColumn($copiedColumn); - if ($column->isPrimaryKey() && $this->isCopyData()) { - $fk = new ForeignKey(); - $fk->setForeignTableName($column->getTable()->getName()); - $fk->setOnDelete('CASCADE'); - $fk->setOnUpdate(null); - $fk->addReference($copiedColumn, $column); - $fk->isParentChild = true; - $table->addForeignKey($fk); - } - } - - // add the foreign keys of the parent table - foreach ($parentTable->getForeignKeys() as $fk) { - $copiedFk = clone $fk; - $copiedFk->setName(''); - $copiedFk->setRefPhpName(''); - $this->getTable()->addForeignKey($copiedFk); - } - - // add the validators of the parent table - foreach ($parentTable->getValidators() as $validator) { - $copiedValidator = clone $validator; - $this->getTable()->addValidator($copiedValidator); - } - - // add the indices of the parent table - foreach ($parentTable->getIndices() as $index) { - $copiedIndex = clone $index; - $copiedIndex->setName(''); - $this->getTable()->addIndex($copiedIndex); - } - - // add the unique indices of the parent table - foreach ($parentTable->getUnices() as $unique) { - $copiedUnique = clone $unique; - $copiedUnique->setName(''); - $this->getTable()->addUnique($copiedUnique); - } - - // give name to newly added foreign keys and indices - // (this is already done for other elements of the current table) - $table->doNaming(); - - // add the Behaviors of the parent table - foreach ($parentTable->getBehaviors() as $behavior) { - if ($behavior->getName() == 'concrete_inheritance_parent' || $behavior->getName() == 'concrete_inheritance') { - continue; - } - $copiedBehavior = clone $behavior; - $this->getTable()->addBehavior($copiedBehavior); - } - - } - - protected function getParentTable() - { - return $this->getTable()->getDatabase()->getTable($this->getParameter('extends')); - } - - protected function isCopyData() - { - return $this->getParameter('copy_data_to_parent') == 'true'; - } - - public function parentClass($builder) - { - switch (get_class($builder)) { - case 'PHP5ObjectBuilder': - return $builder->getNewStubObjectBuilder($this->getParentTable())->getClassname(); - break; - case 'QueryBuilder': - return $builder->getNewStubQueryBuilder($this->getParentTable())->getClassname(); - break; - default: - return null; - break; - } - } - - public function preSave($script) - { - if ($this->isCopyData()) { - return "\$parent = \$this->getSyncParent(\$con); -\$parent->save(\$con); -\$this->setPrimaryKey(\$parent->getPrimaryKey()); -"; - } - } - - public function postDelete($script) - { - if ($this->isCopyData()) { - return "\$this->getParentOrCreate(\$con)->delete(\$con); -"; - } - } - - public function objectMethods($builder) - { - if (!$this->isCopyData()) { - return; - } - $this->builder = $builder; - $script .= ''; - $this->addObjectGetParentOrCreate($script); - $this->addObjectGetSyncParent($script); - - return $script; - } - - protected function addObjectGetParentOrCreate(&$script) - { - $parentTable = $this->getParentTable(); - $parentClass = $this->builder->getNewStubObjectBuilder($parentTable)->getClassname(); - $script .= " -/** - * Get or Create the parent " . $parentClass . " object of the current object - * - * @return " . $parentClass . " The parent object - */ -public function getParentOrCreate(\$con = null) -{ - if (\$this->isNew()) { - \$parent = new " . $parentClass . "(); - \$parent->set" . $this->getParentTable()->getColumn($this->getParameter('descendant_column'))->getPhpName() . "('" . $this->builder->getStubObjectBuilder()->getClassname() . "'); - return \$parent; - } else { - return " . $this->builder->getNewStubQueryBuilder($parentTable)->getClassname() . "::create()->findPk(\$this->getPrimaryKey(), \$con); - } -} -"; - } - - protected function addObjectGetSyncParent(&$script) - { - $parentTable = $this->getParentTable(); - $pkeys = $parentTable->getPrimaryKey(); - $cptype = $pkeys[0]->getPhpType(); - $script .= " -/** - * Create or Update the parent " . $parentTable->getPhpName() . " object - * And return its primary key - * - * @return " . $cptype . " The primary key of the parent object - */ -public function getSyncParent(\$con = null) -{ - \$parent = \$this->getParentOrCreate(\$con);"; - foreach ($parentTable->getColumns() as $column) { - if ($column->isPrimaryKey() || $column->getName() == $this->getParameter('descendant_column')) { - continue; - } - $phpName = $column->getPhpName(); - $script .= " - \$parent->set{$phpName}(\$this->get{$phpName}());"; - } - foreach ($parentTable->getForeignKeys() as $fk) { - if (isset($fk->isParentChild) && $fk->isParentChild) { - continue; - } - $refPhpName = $this->builder->getFKPhpNameAffix($fk, $plural = false); - $script .= " - if (\$this->get" . $refPhpName . "() && \$this->get" . $refPhpName . "()->isNew()) { - \$parent->set" . $refPhpName . "(\$this->get" . $refPhpName . "()); - }"; - } - $script .= " - - return \$parent; -} -"; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceParentBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceParentBehavior.php deleted file mode 100644 index e2cdb2fc6..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/concrete_inheritance/ConcreteInheritanceParentBehavior.php +++ /dev/null @@ -1,89 +0,0 @@ - 'descendant_class' - ); - - public function modifyTable() - { - $table = $this->getTable(); - if (!$table->containsColumn($this->getParameter('descendant_column'))) { - $table->addColumn(array( - 'name' => $this->getParameter('descendant_column'), - 'type' => 'VARCHAR', - 'size' => 100 - )); - } - } - - protected function getColumnGetter() - { - return 'get' . $this->getColumnForParameter('descendant_column')->getPhpName(); - } - - public function objectMethods($builder) - { - $this->builder = $builder; - $script .= ''; - $this->addHasChildObject($script); - $this->addGetChildObject($script); - - return $script; - } - - protected function addHasChildObject(&$script) - { - $script .= " -/** - * Whether or not this object is the parent of a child object - * - * @return bool - */ -public function hasChildObject() -{ - return \$this->" . $this->getColumnGetter() . "() !== null; -} -"; - } - - protected function addGetChildObject(&$script) - { - $script .= " -/** - * Get the child object of this object - * - * @return mixed - */ -public function getChildObject() -{ - if (!\$this->hasChildObject()) { - return null; - } - \$childObjectClass = \$this->" . $this->getColumnGetter() . "(); - \$childObject = PropelQuery::from(\$childObjectClass)->findPk(\$this->getPrimaryKey()); - return \$childObject->hasChildObject() ? \$childObject->getChildObject() : \$childObject; -} -"; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehavior.php deleted file mode 100644 index 5e8996352..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehavior.php +++ /dev/null @@ -1,99 +0,0 @@ - 'tree_left', - 'right_column' => 'tree_right', - 'level_column' => 'tree_level', - 'use_scope' => 'false', - 'scope_column' => 'tree_scope', - 'method_proxies' => 'false' - ); - - protected $objectBuilderModifier, $queryBuilderModifier, $peerBuilderModifier; - - /** - * Add the left, right and scope to the current table - */ - public function modifyTable() - { - if(!$this->getTable()->containsColumn($this->getParameter('left_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('left_column'), - 'type' => 'INTEGER' - )); - } - if(!$this->getTable()->containsColumn($this->getParameter('right_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('right_column'), - 'type' => 'INTEGER' - )); - } - if(!$this->getTable()->containsColumn($this->getParameter('level_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('level_column'), - 'type' => 'INTEGER' - )); - } - if ($this->getParameter('use_scope') == 'true' && - !$this->getTable()->containsColumn($this->getParameter('scope_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('scope_column'), - 'type' => 'INTEGER' - )); - } - } - - public function getObjectBuilderModifier() - { - if (is_null($this->objectBuilderModifier)) - { - $this->objectBuilderModifier = new NestedSetBehaviorObjectBuilderModifier($this); - } - return $this->objectBuilderModifier; - } - - public function getQueryBuilderModifier() - { - if (is_null($this->queryBuilderModifier)) - { - $this->queryBuilderModifier = new NestedSetBehaviorQueryBuilderModifier($this); - } - return $this->queryBuilderModifier; - } - - public function getPeerBuilderModifier() - { - if (is_null($this->peerBuilderModifier)) - { - $this->peerBuilderModifier = new NestedSetBehaviorPeerBuilderModifier($this); - } - return $this->peerBuilderModifier; - } - - public function useScope() - { - return $this->getParameter('use_scope') == 'true'; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php deleted file mode 100644 index 3b99c2c87..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php +++ /dev/null @@ -1,1540 +0,0 @@ - - * @package propel.generator.behavior.nestedset - */ -class NestedSetBehaviorObjectBuilderModifier -{ - protected $behavior, $table, $builder, $objectClassname, $peerClassname; - - public function __construct($behavior) - { - $this->behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumnAttribute($name) - { - return strtolower($this->behavior->getColumnForParameter($name)->getName()); - } - - protected function getColumnPhpName($name) - { - return $this->behavior->getColumnForParameter($name)->getPhpName(); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->queryClassname = $builder->getStubQueryBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - /* - public function objectFilter(&$script, $builder) - { - $script = str_replace('implements Persistent', 'implements Persistent, NodeObject', $script); - } - */ - - public function objectAttributes($builder) - { - $objectClassname = $builder->getStubObjectBuilder()->getClassname(); - return " -/** - * Queries to be executed in the save transaction - * @var array - */ -protected \$nestedSetQueries = array(); - -/** - * Internal cache for children nodes - * @var null|PropelObjectCollection - */ -protected \$collNestedSetChildren = null; - -/** - * Internal cache for parent node - * @var null|$objectClassname - */ -protected \$aNestedSetParent = null; - -"; - } - - public function preSave($builder) - { - return "\$this->processNestedSetQueries(\$con);"; - } - - public function preDelete($builder) - { - $peerClassname = $builder->getStubPeerBuilder()->getClassname(); - return "if (\$this->isRoot()) { - throw new PropelException('Deletion of a root node is disabled for nested sets. Use $peerClassname::deleteTree(" . ($this->behavior->useScope() ? '$scope' : '') . ") instead to delete an entire tree'); -} -\$this->deleteDescendants(\$con); -"; - } - - public function postDelete($builder) - { - $peerClassname = $builder->getStubPeerBuilder()->getClassname(); - return "// fill up the room that was used by the node -$peerClassname::shiftRLValues(-2, \$this->getRightValue() + 1, null" . ($this->behavior->useScope() ? ", \$this->getScopeValue()" : "") . ", \$con); -"; - } - - public function objectClearReferences($builder) - { - return "\$this->collNestedSetChildren = null; -\$this->aNestedSetParent = null;"; - } - - public function objectMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - - $this->addProcessNestedSetQueries($script); - - $this->addGetLeft($script); - $this->addGetRight($script); - $this->addGetLevel($script); - if ($this->getParameter('use_scope') == 'true') - { - $this->addGetScope($script); - } - - $this->addSetLeft($script); - $this->addSetRight($script); - $this->addSetLevel($script); - if ($this->getParameter('use_scope') == 'true') - { - $this->addSetScope($script); - } - - $this->addMakeRoot($script); - - $this->addIsInTree($script); - $this->addIsRoot($script); - $this->addIsLeaf($script); - $this->addIsDescendantOf($script); - $this->addIsAncestorOf($script); - - $this->addHasParent($script); - $this->addSetParent($script); - $this->addGetParent($script); - - $this->addHasPrevSibling($script); - $this->addGetPrevSibling($script); - - $this->addHasNextSibling($script); - $this->addGetNextSibling($script); - - $this->addNestedSetChildrenClear($script); - $this->addNestedSetChildrenInit($script); - $this->addNestedSetChildAdd($script); - $this->addHasChildren($script); - $this->addGetChildren($script); - $this->addCountChildren($script); - - $this->addGetFirstChild($script); - $this->addGetLastChild($script); - $this->addGetSiblings($script); - $this->addGetDescendants($script); - $this->addCountDescendants($script); - $this->addGetBranch($script); - $this->addGetAncestors($script); - - $this->addAddChild($script); - $this->addInsertAsFirstChildOf($script); - $this->addInsertAsLastChildOf($script); - $this->addInsertAsPrevSiblingOf($script); - $this->addInsertAsNextSiblingOf($script); - - $this->addMoveToFirstChildOf($script); - $this->addMoveToLastChildOf($script); - $this->addMoveToPrevSiblingOf($script); - $this->addMoveToNextSiblingOf($script); - $this->addMoveSubtreeTo($script); - - $this->addDeleteDescendants($script); - - $this->addGetIterator($script); - - if ($this->getParameter('method_proxies') == 'true') - { - $this->addCompatibilityProxies($script); - } - - return $script; - } - - protected function addProcessNestedSetQueries(&$script) - { - $script .= " -/** - * Execute queries that were saved to be run inside the save transaction - */ -protected function processNestedSetQueries(\$con) -{ - foreach (\$this->nestedSetQueries as \$query) { - \$query['arguments'][]= \$con; - call_user_func_array(\$query['callable'], \$query['arguments']); - } - \$this->nestedSetQueries = array(); -} -"; - } - protected function addGetLeft(&$script) - { - $script .= " -/** - * Wraps the getter for the nested set left value - * - * @return int - */ -public function getLeftValue() -{ - return \$this->{$this->getColumnAttribute('left_column')}; -} -"; - } - - protected function addGetRight(&$script) - { - $script .= " -/** - * Wraps the getter for the nested set right value - * - * @return int - */ -public function getRightValue() -{ - return \$this->{$this->getColumnAttribute('right_column')}; -} -"; - } - - protected function addGetLevel(&$script) - { - $script .= " -/** - * Wraps the getter for the nested set level - * - * @return int - */ -public function getLevel() -{ - return \$this->{$this->getColumnAttribute('level_column')}; -} -"; - } - - protected function addGetScope(&$script) - { - $script .= " -/** - * Wraps the getter for the scope value - * - * @return int or null if scope is disabled - */ -public function getScopeValue() -{ - return \$this->{$this->getColumnAttribute('scope_column')}; -} -"; - } - - protected function addSetLeft(&$script) - { - $script .= " -/** - * Set the value left column - * - * @param int \$v new value - * @return {$this->objectClassname} The current object (for fluent API support) - */ -public function setLeftValue(\$v) -{ - return \$this->set{$this->getColumnPhpName('left_column')}(\$v); -} -"; - } - - protected function addSetRight(&$script) - { - $script .= " -/** - * Set the value of right column - * - * @param int \$v new value - * @return {$this->objectClassname} The current object (for fluent API support) - */ -public function setRightValue(\$v) -{ - return \$this->set{$this->getColumnPhpName('right_column')}(\$v); -} -"; - } - - protected function addSetLevel(&$script) - { - $script .= " -/** - * Set the value of level column - * - * @param int \$v new value - * @return {$this->objectClassname} The current object (for fluent API support) - */ -public function setLevel(\$v) -{ - return \$this->set{$this->getColumnPhpName('level_column')}(\$v); -} -"; - } - - protected function addSetScope(&$script) - { - $script .= " -/** - * Set the value of scope column - * - * @param int \$v new value - * @return {$this->objectClassname} The current object (for fluent API support) - */ -public function setScopeValue(\$v) -{ - return \$this->set{$this->getColumnPhpName('scope_column')}(\$v); -} -"; - } - - protected function addMakeRoot(&$script) - { - $script .= " -/** - * Creates the supplied node as the root node. - * - * @return {$this->objectClassname} The current object (for fluent API support) - * @throws PropelException - */ -public function makeRoot() -{ - if (\$this->getLeftValue() || \$this->getRightValue()) { - throw new PropelException('Cannot turn an existing node into a root node.'); - } - - \$this->setLeftValue(1); - \$this->setRightValue(2); - \$this->setLevel(0); - return \$this; -} -"; - } - - protected function addIsInTree(&$script) - { - $script .= " -/** - * Tests if onbject is a node, i.e. if it is inserted in the tree - * - * @return bool - */ -public function isInTree() -{ - return \$this->getLeftValue() > 0 && \$this->getRightValue() > \$this->getLeftValue(); -} -"; - } - - protected function addIsRoot(&$script) - { - $script .= " -/** - * Tests if node is a root - * - * @return bool - */ -public function isRoot() -{ - return \$this->isInTree() && \$this->getLeftValue() == 1; -} -"; - } - - protected function addIsLeaf(&$script) - { - $script .= " -/** - * Tests if node is a leaf - * - * @return bool - */ -public function isLeaf() -{ - return \$this->isInTree() && (\$this->getRightValue() - \$this->getLeftValue()) == 1; -} -"; - } - - protected function addIsDescendantOf(&$script) - { - $objectClassname = $this->objectClassname; - $script .= " -/** - * Tests if node is a descendant of another node - * - * @param $objectClassname \$node Propel node object - * @return bool - */ -public function isDescendantOf(\$parent) -{"; - if ($this->behavior->useScope()) { - $script .= " - if (\$this->getScopeValue() !== \$parent->getScopeValue()) { - throw new PropelException('Comparing two nodes of different trees'); - }"; - } - $script .= " - return \$this->isInTree() && \$this->getLeftValue() > \$parent->getLeftValue() && \$this->getRightValue() < \$parent->getRightValue(); -} -"; - } - - protected function addIsAncestorOf(&$script) - { - $objectClassname = $this->objectClassname; - $script .= " -/** - * Tests if node is a ancestor of another node - * - * @param $objectClassname \$node Propel node object - * @return bool - */ -public function isAncestorOf(\$child) -{ - return \$child->isDescendantOf(\$this); -} -"; - } - - protected function addHasParent(&$script) - { - $script .= " -/** - * Tests if object has an ancestor - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ -public function hasParent(PropelPDO \$con = null) -{ - return \$this->getLevel() > 0; -} -"; - } - - protected function addSetParent(&$script) - { - $objectClassname = $this->objectClassname; - $script .= " -/** - * Sets the cache for parent node of the current object. - * Warning: this does not move the current object in the tree. - * Use moveTofirstChildOf() or moveToLastChildOf() for that purpose - * - * @param $objectClassname \$parent - * @return $objectClassname The current object, for fluid interface - */ -public function setParent(\$parent = null) -{ - \$this->aNestedSetParent = \$parent; - return \$this; -} -"; - } - - - protected function addGetParent(&$script) - { - $script .= " -/** - * Gets parent node for the current object if it exists - * The result is cached so further calls to the same method don't issue any queries - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ -public function getParent(PropelPDO \$con = null) -{ - if (\$this->aNestedSetParent === null && \$this->hasParent()) { - \$this->aNestedSetParent = {$this->queryClassname}::create() - ->ancestorsOf(\$this) - ->orderByLevel(true) - ->findOne(\$con); - } - return \$this->aNestedSetParent; -} -"; - } - - protected function addHasPrevSibling(&$script) - { - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Determines if the node has previous sibling - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ -public function hasPrevSibling(PropelPDO \$con = null) -{ - if (!{$this->peerClassname}::isValid(\$this)) { - return false; - } - return $queryClassname::create() - ->filterBy" . $this->getColumnPhpName('right_column') . "(\$this->getLeftValue() - 1)"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree(\$this->getScopeValue())"; - } - $script .= " - ->count(\$con) > 0; -} -"; - } - - protected function addGetPrevSibling(&$script) - { - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets previous sibling for the given node if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ -public function getPrevSibling(PropelPDO \$con = null) -{ - return $queryClassname::create() - ->filterBy" . $this->getColumnPhpName('right_column') . "(\$this->getLeftValue() - 1)"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree(\$this->getScopeValue())"; - } - $script .= " - ->findOne(\$con); -} -"; - } - - protected function addHasNextSibling(&$script) - { - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Determines if the node has next sibling - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ -public function hasNextSibling(PropelPDO \$con = null) -{ - if (!{$this->peerClassname}::isValid(\$this)) { - return false; - } - return $queryClassname::create() - ->filterBy" . $this->getColumnPhpName('left_column') . "(\$this->getRightValue() + 1)"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree(\$this->getScopeValue())"; - } - $script .= " - ->count(\$con) > 0; -} -"; - } - - protected function addGetNextSibling(&$script) - { - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets next sibling for the given node if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ -public function getNextSibling(PropelPDO \$con = null) -{ - return $queryClassname::create() - ->filterBy" . $this->getColumnPhpName('left_column') . "(\$this->getRightValue() + 1)"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree(\$this->getScopeValue())"; - } - $script .= " - ->findOne(\$con); -} -"; - } - - protected function addNestedSetChildrenClear(&$script) - { - $script .= " -/** - * Clears out the \$collNestedSetChildren collection - * - * This does not modify the database; however, it will remove any associated objects, causing - * them to be refetched by subsequent calls to accessor method. - * - * @return void - */ -public function clearNestedSetChildren() -{ - \$this->collNestedSetChildren = null; -} -"; - } - - protected function addNestedSetChildrenInit(&$script) - { - $script .= " -/** - * Initializes the \$collNestedSetChildren collection. - * - * @return void - */ -public function initNestedSetChildren() -{ - \$this->collNestedSetChildren = new PropelObjectCollection(); - \$this->collNestedSetChildren->setModel('" . $this->builder->getNewStubObjectBuilder($this->table)->getClassname() . "'); -} -"; - } - - protected function addNestedSetChildAdd(&$script) - { - $objectClassname = $this->objectClassname; - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Adds an element to the internal \$collNestedSetChildren collection. - * Beware that this doesn't insert a node in the tree. - * This method is only used to facilitate children hydration. - * - * @param $objectClassname $objectName - * - * @return void - */ -public function addNestedSetChild($objectName) -{ - if (\$this->collNestedSetChildren === null) { - \$this->initNestedSetChildren(); - } - if (!\$this->collNestedSetChildren->contains($objectName)) { // only add it if the **same** object is not already associated - \$this->collNestedSetChildren[]= $objectName; - {$objectName}->setParent(\$this); - } -} -"; - } - - protected function addHasChildren(&$script) - { - $script .= " -/** - * Tests if node has children - * - * @return bool - */ -public function hasChildren() -{ - return (\$this->getRightValue() - \$this->getLeftValue()) > 1; -} -"; - } - - protected function addGetChildren(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets the children of the given node - * - * @param Criteria \$criteria Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getChildren(\$criteria = null, PropelPDO \$con = null) -{ - if(null === \$this->collNestedSetChildren || null !== \$criteria) { - if (\$this->isLeaf() || (\$this->isNew() && null === \$this->collNestedSetChildren)) { - // return empty collection - \$this->initNestedSetChildren(); - } else { - \$collNestedSetChildren = $queryClassname::create(null, \$criteria) - ->childrenOf(\$this) - ->orderByBranch() - ->find(\$con); - if (null !== \$criteria) { - return \$collNestedSetChildren; - } - \$this->collNestedSetChildren = \$collNestedSetChildren; - } - } - return \$this->collNestedSetChildren; -} -"; - } - - protected function addCountChildren(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets number of children for the given node - * - * @param Criteria \$criteria Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return int Number of children - */ -public function countChildren(\$criteria = null, PropelPDO \$con = null) -{ - if(null === \$this->collNestedSetChildren || null !== \$criteria) { - if (\$this->isLeaf() || (\$this->isNew() && null === \$this->collNestedSetChildren)) { - return 0; - } else { - return $queryClassname::create(null, \$criteria) - ->childrenOf(\$this) - ->count(\$con); - } - } else { - return count(\$this->collNestedSetChildren); - } -} -"; - } - - protected function addGetFirstChild(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets the first child of the given node - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getFirstChild(\$query = null, PropelPDO \$con = null) -{ - if(\$this->isLeaf()) { - return array(); - } else { - return $queryClassname::create(null, \$query) - ->childrenOf(\$this) - ->orderByBranch() - ->findOne(\$con); - } -} -"; - } - - protected function addGetLastChild(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets the last child of the given node - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getLastChild(\$query = null, PropelPDO \$con = null) -{ - if(\$this->isLeaf()) { - return array(); - } else { - return $queryClassname::create(null, \$query) - ->childrenOf(\$this) - ->orderByBranch(true) - ->findOne(\$con); - } -} -"; - } - - protected function addGetSiblings(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets the siblings of the given node - * - * @param bool \$includeNode Whether to include the current node or not - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * - * @return array List of $objectClassname objects - */ -public function getSiblings(\$includeNode = false, \$query = null, PropelPDO \$con = null) -{ - if(\$this->isRoot()) { - return array(); - } else { - \$query = $queryClassname::create(null, \$query) - ->childrenOf(\$this->getParent(\$con)) - ->orderByBranch(true); - if (!\$includeNode) { - \$query->prune(\$this); - } - return \$query->find(\$con); - } -} -"; - } - - protected function addGetDescendants(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets descendants for the given node - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getDescendants(\$query = null, PropelPDO \$con = null) -{ - if(\$this->isLeaf()) { - return array(); - } else { - return $queryClassname::create(null, \$query) - ->descendantsOf(\$this) - ->orderByBranch() - ->find(\$con); - } -} -"; - } - - protected function addCountDescendants(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets number of descendants for the given node - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return int Number of descendants - */ -public function countDescendants(\$query = null, PropelPDO \$con = null) -{ - if(\$this->isLeaf()) { - // save one query - return 0; - } else { - return $queryClassname::create(null, \$query) - ->descendantsOf(\$this) - ->count(\$con); - } -} -"; - } - - protected function addGetBranch(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets descendants for the given node, plus the current node - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getBranch(\$query = null, PropelPDO \$con = null) -{ - return $queryClassname::create(null, \$query) - ->branchOf(\$this) - ->orderByBranch() - ->find(\$con); -} -"; - } - - protected function addGetAncestors(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $script .= " -/** - * Gets ancestors for the given node, starting with the root node - * Use it for breadcrumb paths for instance - * - * @param Criteria \$query Criteria to filter results. - * @param PropelPDO \$con Connection to use. - * @return array List of $objectClassname objects - */ -public function getAncestors(\$query = null, PropelPDO \$con = null) -{ - if(\$this->isRoot()) { - // save one query - return array(); - } else { - return $queryClassname::create(null, \$query) - ->ancestorsOf(\$this) - ->orderByBranch() - ->find(\$con); - } -} -"; - } - - protected function addAddChild(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Inserts the given \$child node as first child of current - * The modifications in the current object and the tree - * are not persisted until the child object is saved. - * - * @param $objectClassname \$child Propel object for child node - * - * @return $objectClassname The current Propel object - */ -public function addChild($objectClassname \$child) -{ - if (\$this->isNew()) { - throw new PropelException('A $objectClassname object must not be new to accept children.'); - } - \$child->insertAsFirstChildOf(\$this); - return \$this; -} -"; - } - - protected function addInsertAsFirstChildOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Inserts the current node as first child of given \$parent node - * The modifications in the current object and the tree - * are not persisted until the current object is saved. - * - * @param $objectClassname \$parent Propel object for parent node - * - * @return $objectClassname The current Propel object - */ -public function insertAsFirstChildOf(\$parent) -{ - if (\$this->isInTree()) { - throw new PropelException('A $objectClassname object must not already be in the tree to be inserted. Use the moveToFirstChildOf() instead.'); - } - \$left = \$parent->getLeftValue() + 1; - // Update node properties - \$this->setLeftValue(\$left); - \$this->setRightValue(\$left + 1); - \$this->setLevel(\$parent->getLevel() + 1);"; - if ($useScope) - { - $script .= " - \$scope = \$parent->getScopeValue(); - \$this->setScopeValue(\$scope);"; - } - $script .= " - // update the children collection of the parent - \$parent->addNestedSetChild(\$this); - - // Keep the tree modification query for the save() transaction - \$this->nestedSetQueries []= array( - 'callable' => array('$peerClassname', 'makeRoomForLeaf'), - 'arguments' => array(\$left" . ($useScope ? ", \$scope" : "") . ") - ); - return \$this; -} -"; - } - - protected function addInsertAsLastChildOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Inserts the current node as last child of given \$parent node - * The modifications in the current object and the tree - * are not persisted until the current object is saved. - * - * @param $objectClassname \$parent Propel object for parent node - * - * @return $objectClassname The current Propel object - */ -public function insertAsLastChildOf(\$parent) -{ - if (\$this->isInTree()) { - throw new PropelException('A $objectClassname object must not already be in the tree to be inserted. Use the moveToLastChildOf() instead.'); - } - \$left = \$parent->getRightValue(); - // Update node properties - \$this->setLeftValue(\$left); - \$this->setRightValue(\$left + 1); - \$this->setLevel(\$parent->getLevel() + 1);"; - if ($useScope) - { - $script .= " - \$scope = \$parent->getScopeValue(); - \$this->setScopeValue(\$scope);"; - } - $script .= " - // update the children collection of the parent - \$parent->addNestedSetChild(\$this); - - // Keep the tree modification query for the save() transaction - \$this->nestedSetQueries []= array( - 'callable' => array('$peerClassname', 'makeRoomForLeaf'), - 'arguments' => array(\$left" . ($useScope ? ", \$scope" : "") . ") - ); - return \$this; -} -"; - } - - protected function addInsertAsPrevSiblingOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Inserts the current node as prev sibling given \$sibling node - * The modifications in the current object and the tree - * are not persisted until the current object is saved. - * - * @param $objectClassname \$sibling Propel object for parent node - * - * @return $objectClassname The current Propel object - */ -public function insertAsPrevSiblingOf(\$sibling) -{ - if (\$this->isInTree()) { - throw new PropelException('A $objectClassname object must not already be in the tree to be inserted. Use the moveToPrevSiblingOf() instead.'); - } - \$left = \$sibling->getLeftValue(); - // Update node properties - \$this->setLeftValue(\$left); - \$this->setRightValue(\$left + 1); - \$this->setLevel(\$sibling->getLevel());"; - if ($useScope) - { - $script .= " - \$scope = \$sibling->getScopeValue(); - \$this->setScopeValue(\$scope);"; - } - $script .= " - // Keep the tree modification query for the save() transaction - \$this->nestedSetQueries []= array( - 'callable' => array('$peerClassname', 'makeRoomForLeaf'), - 'arguments' => array(\$left" . ($useScope ? ", \$scope" : "") . ") - ); - return \$this; -} -"; - } - - protected function addInsertAsNextSiblingOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Inserts the current node as next sibling given \$sibling node - * The modifications in the current object and the tree - * are not persisted until the current object is saved. - * - * @param $objectClassname \$sibling Propel object for parent node - * - * @return $objectClassname The current Propel object - */ -public function insertAsNextSiblingOf(\$sibling) -{ - if (\$this->isInTree()) { - throw new PropelException('A $objectClassname object must not already be in the tree to be inserted. Use the moveToNextSiblingOf() instead.'); - } - \$left = \$sibling->getRightValue() + 1; - // Update node properties - \$this->setLeftValue(\$left); - \$this->setRightValue(\$left + 1); - \$this->setLevel(\$sibling->getLevel());"; - if ($useScope) - { - $script .= " - \$scope = \$sibling->getScopeValue(); - \$this->setScopeValue(\$scope);"; - } - $script .= " - // Keep the tree modification query for the save() transaction - \$this->nestedSetQueries []= array( - 'callable' => array('$peerClassname', 'makeRoomForLeaf'), - 'arguments' => array(\$left" . ($useScope ? ", \$scope" : "") . ") - ); - return \$this; -} -"; - } - - protected function addMoveToFirstChildOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $script .= " -/** - * Moves current node and its subtree to be the first child of \$parent - * The modifications in the current object and the tree are immediate - * - * @param $objectClassname \$parent Propel object for parent node - * @param PropelPDO \$con Connection to use. - * - * @return $objectClassname The current Propel object - */ -public function moveToFirstChildOf(\$parent, PropelPDO \$con = null) -{ - if (!\$this->isInTree()) { - throw new PropelException('A $objectClassname object must be already in the tree to be moved. Use the insertAsFirstChildOf() instead.'); - }"; - if ($this->behavior->useScope()) { - $script .= " - if (\$parent->getScopeValue() != \$this->getScopeValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - }"; - } - $script .= " - if (\$parent->isDescendantOf(\$this)) { - throw new PropelException('Cannot move a node as child of one of its subtree nodes.'); - } - - \$this->moveSubtreeTo(\$parent->getLeftValue() + 1, \$parent->getLevel() - \$this->getLevel() + 1, \$con); - - return \$this; -} -"; - } - - protected function addMoveToLastChildOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $script .= " -/** - * Moves current node and its subtree to be the last child of \$parent - * The modifications in the current object and the tree are immediate - * - * @param $objectClassname \$parent Propel object for parent node - * @param PropelPDO \$con Connection to use. - * - * @return $objectClassname The current Propel object - */ -public function moveToLastChildOf(\$parent, PropelPDO \$con = null) -{ - if (!\$this->isInTree()) { - throw new PropelException('A $objectClassname object must be already in the tree to be moved. Use the insertAsLastChildOf() instead.'); - }"; - if ($this->behavior->useScope()) { - $script .= " - if (\$parent->getScopeValue() != \$this->getScopeValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - }"; - } - $script .= " - if (\$parent->isDescendantOf(\$this)) { - throw new PropelException('Cannot move a node as child of one of its subtree nodes.'); - } - - \$this->moveSubtreeTo(\$parent->getRightValue(), \$parent->getLevel() - \$this->getLevel() + 1, \$con); - - return \$this; -} -"; - } - - protected function addMoveToPrevSiblingOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $script .= " -/** - * Moves current node and its subtree to be the previous sibling of \$sibling - * The modifications in the current object and the tree are immediate - * - * @param $objectClassname \$sibling Propel object for sibling node - * @param PropelPDO \$con Connection to use. - * - * @return $objectClassname The current Propel object - */ -public function moveToPrevSiblingOf(\$sibling, PropelPDO \$con = null) -{ - if (!\$this->isInTree()) { - throw new PropelException('A $objectClassname object must be already in the tree to be moved. Use the insertAsPrevSiblingOf() instead.'); - } - if (\$sibling->isRoot()) { - throw new PropelException('Cannot move to previous sibling of a root node.'); - }"; - if ($this->behavior->useScope()) { - $script .= " - if (\$sibling->getScopeValue() != \$this->getScopeValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - }"; - } - $script .= " - if (\$sibling->isDescendantOf(\$this)) { - throw new PropelException('Cannot move a node as sibling of one of its subtree nodes.'); - } - - \$this->moveSubtreeTo(\$sibling->getLeftValue(), \$sibling->getLevel() - \$this->getLevel(), \$con); - - return \$this; -} -"; - } - - protected function addMoveToNextSiblingOf(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $script .= " -/** - * Moves current node and its subtree to be the next sibling of \$sibling - * The modifications in the current object and the tree are immediate - * - * @param $objectClassname \$sibling Propel object for sibling node - * @param PropelPDO \$con Connection to use. - * - * @return $objectClassname The current Propel object - */ -public function moveToNextSiblingOf(\$sibling, PropelPDO \$con = null) -{ - if (!\$this->isInTree()) { - throw new PropelException('A $objectClassname object must be already in the tree to be moved. Use the insertAsNextSiblingOf() instead.'); - } - if (\$sibling->isRoot()) { - throw new PropelException('Cannot move to next sibling of a root node.'); - }"; - if ($this->behavior->useScope()) { - $script .= " - if (\$sibling->getScopeValue() != \$this->getScopeValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - }"; - } - $script .= " - if (\$sibling->isDescendantOf(\$this)) { - throw new PropelException('Cannot move a node as sibling of one of its subtree nodes.'); - } - - \$this->moveSubtreeTo(\$sibling->getRightValue() + 1, \$sibling->getLevel() - \$this->getLevel(), \$con); - - return \$this; -} -"; - } - - protected function addMoveSubtreeTo(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Move current node and its children to location \$destLeft and updates rest of tree - * - * @param int \$destLeft Destination left value - * @param int \$levelDelta Delta to add to the levels - * @param PropelPDO \$con Connection to use. - */ -protected function moveSubtreeTo(\$destLeft, \$levelDelta, PropelPDO \$con = null) -{ - \$left = \$this->getLeftValue(); - \$right = \$this->getRightValue();"; - if ($useScope) { - $script .= " - \$scope = \$this->getScopeValue();"; - } - $script .= " - - \$treeSize = \$right - \$left +1; - - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$con->beginTransaction(); - try { - // make room next to the target for the subtree - $peerClassname::shiftRLValues(\$treeSize, \$destLeft, null" . ($useScope ? ", \$scope" : "") . ", \$con); - - if (\$left >= \$destLeft) { // src was shifted too? - \$left += \$treeSize; - \$right += \$treeSize; - } - - if (\$levelDelta) { - // update the levels of the subtree - $peerClassname::shiftLevel(\$levelDelta, \$left, \$right" . ($useScope ? ", \$scope" : "") . ", \$con); - } - - // move the subtree to the target - $peerClassname::shiftRLValues(\$destLeft - \$left, \$left, \$right" . ($useScope ? ", \$scope" : "") . ", \$con); - - // remove the empty room at the previous location of the subtree - $peerClassname::shiftRLValues(-\$treeSize, \$right + 1, null" . ($useScope ? ", \$scope" : "") . ", \$con); - - // update all loaded nodes - $peerClassname::updateLoadedNodes(\$con); - - \$con->commit(); - } catch (PropelException \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addDeleteDescendants(&$script) - { - $objectClassname = $this->objectClassname; - $peerClassname = $this->peerClassname; - $queryClassname = $this->queryClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Deletes all descendants for the given node - * Instance pooling is wiped out by this command, - * so existing $objectClassname instances are probably invalid (except for the current one) - * - * @param PropelPDO \$con Connection to use. - * - * @return int number of deleted nodes - */ -public function deleteDescendants(PropelPDO \$con = null) -{ - if(\$this->isLeaf()) { - // save one query - return; - } - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_READ); - } - \$left = \$this->getLeftValue(); - \$right = \$this->getRightValue();"; - if ($useScope) { - $script .= " - \$scope = \$this->getScopeValue();"; - } - $script .= " - \$con->beginTransaction(); - try { - // delete descendant nodes (will empty the instance pool) - \$ret = $queryClassname::create() - ->descendantsOf(\$this) - ->delete(\$con); - - // fill up the room that was used by descendants - $peerClassname::shiftRLValues(\$left - \$right + 1, \$right, null" . ($useScope ? ", \$scope" : "") . ", \$con); - - // fix the right value for the current node, which is now a leaf - \$this->setRightValue(\$left + 1); - - \$con->commit(); - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } - - return \$ret; -} -"; - } - - protected function addGetIterator(&$script) - { - $script .= " -/** - * Returns a pre-order iterator for this node and its children. - * - * @return RecursiveIterator - */ -public function getIterator() -{ - return new NestedSetRecursiveIterator(\$this); -} -"; - } - - protected function addCompatibilityProxies(&$script) - { - $objectClassname = $this->objectClassname; - $script .= " -/** - * Alias for makeRoot(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see makeRoot - */ -public function createRoot() -{ - return \$this->makeRoot(); -} - -/** - * Alias for getParent(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getParent - */ -public function retrieveParent(PropelPDO \$con = null) -{ - return \$this->getParent(\$con); -} - -/** - * Alias for setParent(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see setParent - */ -public function setParentNode(\$parent = null) -{ - return \$this->setParent(\$parent); -} - -/** - * Alias for countDecendants(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see setParent - */ -public function getNumberOfDescendants(PropelPDO \$con = null) -{ - return \$this->countDescendants(null, \$con); -} - -/** - * Alias for countChildren(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see setParent - */ -public function getNumberOfChildren(PropelPDO \$con = null) -{ - return \$this->countChildren(null, \$con); -} - -/** - * Alias for getPrevSibling(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getParent - */ -public function retrievePrevSibling(PropelPDO \$con = null) -{ - return \$this->getPrevSibling(\$con); -} - -/** - * Alias for getNextSibling(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getParent - */ -public function retrieveNextSibling(PropelPDO \$con = null) -{ - return \$this->getNextSibling(\$con); -} - -/** - * Alias for getFirstChild(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getParent - */ -public function retrieveFirstChild(PropelPDO \$con = null) -{ - return \$this->getFirstChild(null, \$con); -} - -/** - * Alias for getLastChild(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getParent - */ -public function retrieveLastChild(PropelPDO \$con = null) -{ - return \$this->getLastChild(null, \$con); -} - -/** - * Alias for getAncestors(), for BC with Propel 1.4 nested sets - * - * @deprecated since 1.5 - * @see getAncestors - */ -public function getPath(PropelPDO \$con = null) -{ - return \$this->getAncestors(null, \$con); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorPeerBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorPeerBuilderModifier.php deleted file mode 100644 index 17bbb9630..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorPeerBuilderModifier.php +++ /dev/null @@ -1,555 +0,0 @@ - - * @package propel.generator.behavior.nestedset - */ -class NestedSetBehaviorPeerBuilderModifier -{ - protected $behavior, $table, $builder, $objectClassname, $peerClassname; - - public function __construct($behavior) - { - $this->behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumn($name) - { - return $this->behavior->getColumnForParameter($name); - } - - protected function getColumnAttribute($name) - { - return strtolower($this->getColumn($name)->getName()); - } - - protected function getColumnConstant($name) - { - return strtoupper($this->getColumn($name)->getName()); - } - - protected function getColumnPhpName($name) - { - return $this->getColumn($name)->getPhpName(); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - public function staticAttributes($builder) - { - $tableName = $this->table->getName(); - - $script = " -/** - * Left column for the set - */ -const LEFT_COL = '" . $tableName . '.' . $this->getColumnConstant('left_column') . "'; - -/** - * Right column for the set - */ -const RIGHT_COL = '" . $tableName . '.' . $this->getColumnConstant('right_column') . "'; - -/** - * Level column for the set - */ -const LEVEL_COL = '" . $tableName . '.' . $this->getColumnConstant('level_column') . "'; -"; - - if ($this->behavior->useScope()) { - $script .= " -/** - * Scope column for the set - */ -const SCOPE_COL = '" . $tableName . '.' . $this->getColumnConstant('scope_column') . "'; -"; - } - - return $script; - } - - public function staticMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - - if ($this->getParameter('use_scope') == 'true') - { - $this->addRetrieveRoots($script); - } - $this->addRetrieveRoot($script); - $this->addRetrieveTree($script); - $this->addIsValid($script); - $this->addDeleteTree($script); - $this->addShiftRLValues($script); - $this->addShiftLevel($script); - $this->addUpdateLoadedNodes($script); - $this->addMakeRoomForLeaf($script); - $this->addFixLevels($script); - - return $script; - } - - protected function addRetrieveRoots(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Returns the root nodes for the tree - * - * @param PropelPDO \$con Connection to use. - * @return {$this->objectClassname} Propel object for root node - */ -public static function retrieveRoots(Criteria \$criteria = null, PropelPDO \$con = null) -{ - if (\$criteria === null) { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - } - \$criteria->add($peerClassname::LEFT_COL, 1, Criteria::EQUAL); - - return $peerClassname::doSelect(\$criteria, \$con); -} -"; - } - - protected function addRetrieveRoot(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Returns the root node for a given scope - *"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which root node to return"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - * @return {$this->objectClassname} Propel object for root node - */ -public static function retrieveRoot(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add($peerClassname::LEFT_COL, 1, Criteria::EQUAL);"; - if($useScope) { - $script .= " - \$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - return $peerClassname::doSelectOne(\$c, \$con); -} -"; - } - - protected function addRetrieveTree(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Returns the whole tree node for a given scope - *"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which root node to return"; - } - $script .= " - * @param Criteria \$criteria Optional Criteria to filter the query - * @param PropelPDO \$con Connection to use. - * @return {$this->objectClassname} Propel object for root node - */ -public static function retrieveTree(" . ($useScope ? "\$scope = null, " : "") . "Criteria \$criteria = null, PropelPDO \$con = null) -{ - if (\$criteria === null) { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - } - \$criteria->addAscendingOrderByColumn($peerClassname::LEFT_COL);"; - if($useScope) { - $script .= " - \$criteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - return $peerClassname::doSelect(\$criteria, \$con); -} -"; - } - - protected function addIsValid(&$script) - { - $objectClassname = $this->objectClassname; - $script .= " -/** - * Tests if node is valid - * - * @param $objectClassname \$node Propel object for src node - * @return bool - */ -public static function isValid($objectClassname \$node = null) -{ - if (is_object(\$node) && \$node->getRightValue() > \$node->getLeftValue()) { - return true; - } else { - return false; - } -} -"; - } - - protected function addDeleteTree(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Delete an entire tree - * "; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which tree to delete"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - * - * @return int The number of deleted nodes - */ -public static function deleteTree(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{"; - if($useScope) { - $script .= " - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL); - return $peerClassname::doDelete(\$c, \$con);"; - } else { - $script .= " - return $peerClassname::doDeleteAll(\$con);"; - } - $script .= " -} -"; - } - - protected function addShiftRLValues(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Adds \$delta to all L and R values that are >= \$first and <= \$last. - * '\$delta' can also be negative. - * - * @param int \$delta Value to be shifted by, can be negative - * @param int \$first First node to be shifted - * @param int \$last Last node to be shifted (optional)"; - if($useScope) { - $script .= " - * @param int \$scope Scope to use for the shift"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - */ -public static function shiftRLValues(\$delta, \$first, \$last = null" . ($useScope ? ", \$scope = null" : ""). ", PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - // Shift left column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion($peerClassname::LEFT_COL, \$first, Criteria::GREATER_EQUAL); - if (null !== \$last) { - \$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::LEFT_COL, \$last, Criteria::LESS_EQUAL)); - } - \$whereCriteria->add(\$criterion);"; - if ($useScope) { - $script .= " - \$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add($peerClassname::LEFT_COL, array('raw' => $peerClassname::LEFT_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL); - - {$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - - // Shift right column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion($peerClassname::RIGHT_COL, \$first, Criteria::GREATER_EQUAL); - if (null !== \$last) { - \$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::RIGHT_COL, \$last, Criteria::LESS_EQUAL)); - } - \$whereCriteria->add(\$criterion);"; - if ($useScope) { - $script .= " - \$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add($peerClassname::RIGHT_COL, array('raw' => $peerClassname::RIGHT_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL); - - {$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); -} -"; - } - - protected function addShiftLevel(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Adds \$delta to level for nodes having left value >= \$first and right value <= \$last. - * '\$delta' can also be negative. - * - * @param int \$delta Value to be shifted by, can be negative - * @param int \$first First node to be shifted - * @param int \$last Last node to be shifted"; - if($useScope) { - $script .= " - * @param int \$scope Scope to use for the shift"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - */ -public static function shiftLevel(\$delta, \$first, \$last" . ($useScope ? ", \$scope = null" : ""). ", PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$whereCriteria->add($peerClassname::LEFT_COL, \$first, Criteria::GREATER_EQUAL); - \$whereCriteria->add($peerClassname::RIGHT_COL, \$last, Criteria::LESS_EQUAL);"; - if ($useScope) { - $script .= " - \$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add($peerClassname::LEVEL_COL, array('raw' => $peerClassname::LEVEL_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL); - - {$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); -} -"; - } - - protected function addUpdateLoadedNodes(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Reload all already loaded nodes to sync them with updated db - * - * @param PropelPDO \$con Connection to use. - */ -public static function updateLoadedNodes(PropelPDO \$con = null) -{ - if (Propel::isInstancePoolingEnabled()) { - \$keys = array(); - foreach ($peerClassname::\$instances as \$obj) { - \$keys[] = \$obj->getPrimaryKey(); - } - - if (!empty(\$keys)) { - // We don't need to alter the object instance pool; we're just modifying these ones - // already in the pool. - \$criteria = new Criteria($peerClassname::DATABASE_NAME);"; - if (count($this->table->getPrimaryKey()) === 1) { - $pkey = $this->table->getPrimaryKey(); - $col = array_shift($pkey); - $script .= " - \$criteria->add(".$this->builder->getColumnConstant($col).", \$keys, Criteria::IN); -"; - } else { - $fields = array(); - foreach ($this->table->getPrimaryKey() as $k => $col) { - $fields[] = $this->builder->getColumnConstant($col); - }; - $script .= " - - // Loop on each instances in pool - foreach (\$keys as \$values) { - // Create initial Criterion - \$cton = \$criteria->getNewCriterion(" . $fields[0] . ", \$values[0]);"; - unset($fields[0]); - foreach ($fields as $k => $col) { - $script .= " - - // Create next criterion - \$nextcton = \$criteria->getNewCriterion(" . $col . ", \$values[$k]); - // And merge it with the first - \$cton->addAnd(\$nextcton);"; - } - $script .= " - - // Add final Criterion to Criteria - \$criteria->addOr(\$cton); - }"; - } - - $script .= " - \$stmt = $peerClassname::doSelectStmt(\$criteria, \$con); - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key = $peerClassname::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$object = $peerClassname::getInstanceFromPool(\$key))) {"; - $n = 0; - foreach ($this->table->getColumns() as $col) { - if ($col->getPhpName() == $this->getColumnPhpName('left_column')) { - $script .= " - \$object->setLeftValue(\$row[$n]);"; - } else if ($col->getPhpName() == $this->getColumnPhpName('right_column')) { - $script .= " - \$object->setRightValue(\$row[$n]);"; - } else if ($col->getPhpName() == $this->getColumnPhpName('level_column')) { - $script .= " - \$object->setLevel(\$row[$n]); - \$object->clearNestedSetChildren();"; - } - $n++; - } - $script .= " - } - } - \$stmt->closeCursor(); - } - } -} -"; - } - - protected function addMakeRoomForLeaf(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Update the tree to allow insertion of a leaf at the specified position - * - * @param int \$left left column value"; - if ($useScope) { - $script .= " - * @param integer \$scope scope column value"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - */ -public static function makeRoomForLeaf(\$left" . ($useScope ? ", \$scope" : ""). ", PropelPDO \$con = null) -{ - // Update database nodes - $peerClassname::shiftRLValues(2, \$left, null" . ($useScope ? ", \$scope" : "") . ", \$con); - - // Update all loaded nodes - $peerClassname::updateLoadedNodes(\$con); -} -"; - } - - protected function addFixLevels(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Update the tree to allow insertion of a leaf at the specified position - *"; - if ($useScope) { - $script .= " - * @param integer \$scope scope column value"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - */ -public static function fixLevels(" . ($useScope ? "\$scope, " : ""). "PropelPDO \$con = null) -{ - \$c = new Criteria();"; - if ($useScope) { - $script .= " - \$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - \$c->addAscendingOrderByColumn($peerClassname::LEFT_COL); - \$stmt = $peerClassname::doSelectStmt(\$c, \$con); - "; - if (!$this->table->getChildrenColumn()) { - $script .= " - // set the class once to avoid overhead in the loop - \$cls = $peerClassname::getOMClass(false);"; - } - - $script .= " - \$level = null; - // iterate over the statement - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - - // hydrate object - \$key = $peerClassname::getPrimaryKeyHashFromRow(\$row, 0); - if (null === (\$obj = $peerClassname::getInstanceFromPool(\$key))) {"; - if ($this->table->getChildrenColumn()) { - $script .= " - // class must be set each time from the record row - \$cls = $peerClassname::getOMClass(\$row, 0); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); - " . $this->builder->buildObjectInstanceCreationCode('$obj', '$cls') . " - \$obj->hydrate(\$row); - $peerClassname::addInstanceToPool(\$obj, \$key);"; - } else { - $script .= " - " . $this->builder->buildObjectInstanceCreationCode('$obj', '$cls') . " - \$obj->hydrate(\$row); - $peerClassname::addInstanceToPool(\$obj, \$key);"; - } - $script .= " - } - - // compute level - // Algorithm shamelessly stolen from sfPropelActAsNestedSetBehaviorPlugin - // Probably authored by Tristan Rivoallan - if (\$level === null) { - \$level = 0; - \$i = 0; - \$prev = array(\$obj->getRightValue()); - } else { - while (\$obj->getRightValue() > \$prev[\$i]) { - \$i--; - } - \$level = ++\$i; - \$prev[\$i] = \$obj->getRightValue(); - } - - // update level in node if necessary - if (\$obj->getLevel() !== \$level) { - \$obj->setLevel(\$level); - \$obj->save(\$con); - } - } - \$stmt->closeCursor(); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorQueryBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorQueryBuilderModifier.php deleted file mode 100644 index 31cd32d58..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/nestedset/NestedSetBehaviorQueryBuilderModifier.php +++ /dev/null @@ -1,357 +0,0 @@ -behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumn($name) - { - return $this->behavior->getColumnForParameter($name); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->queryClassname = $builder->getStubQueryBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - public function queryMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - - // select filters - if ($this->behavior->useScope()) { - $this->addTreeRoots($script); - $this->addInTree($script); - } - $this->addDescendantsOf($script); - $this->addBranchOf($script); - $this->addChildrenOf($script); - $this->addSiblingsOf($script); - $this->addAncestorsOf($script); - $this->addRootsOf($script); - // select orders - $this->addOrderByBranch($script); - $this->addOrderByLevel($script); - // select termination methods - $this->addFindRoot($script); - $this->addFindTree($script); - - return $script; - } - - protected function addTreeRoots(&$script) - { - $script .= " -/** - * Filter the query to restrict the result to root objects - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function treeRoots() -{ - return \$this->addUsingAlias({$this->peerClassname}::LEFT_COL, 1, Criteria::EQUAL); -} -"; - } - - protected function addInTree(&$script) - { - $script .= " -/** - * Returns the objects in a certain tree, from the tree scope - * - * @param int \$scope Scope to determine which objects node to return - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function inTree(\$scope = null) -{ - return \$this->addUsingAlias({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL); -} -"; - } - - protected function addDescendantsOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to descendants of an object - * - * @param {$this->objectClassname} $objectName The object to use for descendant search - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function descendantsOf($objectName) -{ - return \$this"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree({$objectName}->getScopeValue())"; - } - $script .= " - ->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::GREATER_THAN) - ->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::LESS_THAN); -} -"; - } - - protected function addBranchOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to the branch of an object. - * Same as descendantsOf(), except that it includes the object passed as parameter in the result - * - * @param {$this->objectClassname} $objectName The object to use for branch search - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function branchOf($objectName) -{ - return \$this"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree({$objectName}->getScopeValue())"; - } - $script .= " - ->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::GREATER_EQUAL) - ->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::LESS_EQUAL); -} -"; - } - - protected function addChildrenOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to children of an object - * - * @param {$this->objectClassname} $objectName The object to use for child search - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function childrenOf($objectName) -{ - return \$this - ->descendantsOf($objectName) - ->addUsingAlias({$this->peerClassname}::LEVEL_COL, {$objectName}->getLevel() + 1, Criteria::EQUAL); -} -"; - } - - protected function addSiblingsOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to siblings of an object. - * The result does not include the object passed as parameter. - * - * @param {$this->objectClassname} $objectName The object to use for sibling search - * @param PropelPDO \$con Connection to use. - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function siblingsOf($objectName, PropelPDO \$con = null) -{ - if ({$objectName}->isRoot()) { - return \$this-> - add({$this->peerClassname}::LEVEL_COL, '1<>1', Criteria::CUSTOM); - } else { - return \$this - ->childrenOf({$objectName}->getParent(\$con)) - ->prune($objectName); - } -} -"; - } - - protected function addAncestorsOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to ancestors of an object - * - * @param {$this->objectClassname} $objectName The object to use for ancestors search - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function ancestorsOf($objectName) -{ - return \$this"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree({$objectName}->getScopeValue())"; - } - $script .= " - ->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::LESS_THAN) - ->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::GREATER_THAN); -} -"; - } - - protected function addRootsOf(&$script) - { - $objectName = '$' . $this->table->getStudlyPhpName(); - $script .= " -/** - * Filter the query to restrict the result to roots of an object. - * Same as ancestorsOf(), except that it includes the object passed as parameter in the result - * - * @param {$this->objectClassname} $objectName The object to use for roots search - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function rootsOf($objectName) -{ - return \$this"; - if ($this->behavior->useScope()) { - $script .= " - ->inTree({$objectName}->getScopeValue())"; - } - $script .= " - ->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::LESS_EQUAL) - ->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::GREATER_EQUAL); -} -"; - } - - protected function addOrderByBranch(&$script) - { - $script .= " -/** - * Order the result by branch, i.e. natural tree order - * - * @param bool \$reverse if true, reverses the order - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function orderByBranch(\$reverse = false) -{ - if (\$reverse) { - return \$this - ->addDescendingOrderByColumn({$this->peerClassname}::LEFT_COL); - } else { - return \$this - ->addAscendingOrderByColumn({$this->peerClassname}::LEFT_COL); - } -} -"; - } - - protected function addOrderByLevel(&$script) - { - $script .= " -/** - * Order the result by level, the closer to the root first - * - * @param bool \$reverse if true, reverses the order - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function orderByLevel(\$reverse = false) -{ - if (\$reverse) { - return \$this - ->addAscendingOrderByColumn({$this->peerClassname}::RIGHT_COL); - } else { - return \$this - ->addDescendingOrderByColumn({$this->peerClassname}::RIGHT_COL); - } -} -"; - } - - protected function addFindRoot(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Returns " . ($useScope ? 'a' : 'the') ." root node for the tree - *"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which root node to return"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - * - * @return {$this->objectClassname} The tree root object - */ -public function findRoot(" . ($useScope ? "\$scope = null, " : "") . "\$con = null) -{ - return \$this - ->addUsingAlias({$this->peerClassname}::LEFT_COL, 1, Criteria::EQUAL)"; - if ($useScope) { - $script .= " - ->inTree(\$scope)"; - } - $script .= " - ->findOne(\$con); -} -"; - } - - protected function addFindTree(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Returns " . ($useScope ? 'a' : 'the') ." tree of objects - *"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which tree node to return"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - * - * @return mixed the list of results, formatted by the current formatter - */ -public function findTree(" . ($useScope ? "\$scope = null, " : "") . "\$con = null) -{ - return \$this"; - if ($useScope) { - $script .= " - ->inTree(\$scope)"; - } - $script .= " - ->orderByBranch() - ->find(\$con); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/query_cache/QueryCacheBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/query_cache/QueryCacheBehavior.php deleted file mode 100644 index 44db968ae..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/query_cache/QueryCacheBehavior.php +++ /dev/null @@ -1,262 +0,0 @@ - 'apc', - 'lifetime' => 3600, - ); - - public function queryAttributes($builder) - { - $script = "protected \$queryKey = ''; -"; - switch ($this->getParameter('backend')) { - case 'backend': - $script .= "protected static \$cacheBackend = array(); - "; - break; - case 'apc': - break; - case 'custom': - default: - $script .= "protected static \$cacheBackend; - "; - break; - } - - return $script; - } - - public function queryMethods($builder) - { - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - $script = ''; - $this->addSetQueryKey($script); - $this->addGetQueryKey($script); - $this->addCacheContains($script); - $this->addCacheFetch($script); - $this->addCacheStore($script); - $this->addGetSelectStatement($script); - $this->addGetCountStatement($script); - - return $script; - } - - protected function addSetQueryKey(&$script) - { - $script .= " -public function setQueryKey(\$key) -{ - \$this->queryKey = \$key; - return \$this; -} -"; - } - - protected function addGetQueryKey(&$script) - { - $script .= " -public function getQueryKey() -{ - return \$this->queryKey; -} -"; - } - - protected function addCacheContains(&$script) - { - $script .= " -public function cacheContains(\$key) -{"; - switch ($this->getParameter('backend')) { - case 'apc': - $script .= " - return apc_fetch(\$key);"; - break; - case 'array': - $script .= " - return isset(self::\$cacheBackend[\$key]);"; - break; - case 'custom': - default: - $script .= " - throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');"; - break; - - } - $script .= " -} -"; - } - - protected function addCacheStore(&$script) - { - $script .= " -public function cacheStore(\$key, \$value, \$lifetime = " .$this->getParameter('lifetime') . ") -{"; - switch ($this->getParameter('backend')) { - case 'apc': - $script .= " - apc_store(\$key, \$value, \$lifetime);"; - break; - case 'array': - $script .= " - self::\$cacheBackend[\$key] = \$value;"; - break; - case 'custom': - default: - $script .= " - throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');"; - break; - } - $script .= " -} -"; - } - - protected function addCacheFetch(&$script) - { - $script .= " -public function cacheFetch(\$key) -{"; - switch ($this->getParameter('backend')) { - case 'apc': - $script .= " - return apc_fetch(\$key);"; - break; - case 'array': - $script .= " - return isset(self::\$cacheBackend[\$key]) ? self::\$cacheBackend[\$key] : null;"; - break; - case 'custom': - default: - $script .= " - throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');"; - break; - } - $script .= " -} -"; - } - - protected function addGetSelectStatement(&$script) - { - $script .= " -protected function getSelectStatement(\$con = null) -{ - \$dbMap = Propel::getDatabaseMap(" . $this->peerClassname ."::DATABASE_NAME); - \$db = Propel::getDB(" . $this->peerClassname ."::DATABASE_NAME); - if (\$con === null) { - \$con = Propel::getConnection(" . $this->peerClassname ."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - if (!\$this->hasSelectClause()) { - \$this->addSelfSelectColumns(); - } - - \$con->beginTransaction(); - try { - \$this->basePreSelect(\$con); - \$key = \$this->getQueryKey(); - if (\$key && \$this->cacheContains(\$key)) { - \$params = \$this->getParams(); - \$sql = \$this->cacheFetch(\$key); - } else { - \$params = array(); - \$sql = BasePeer::createSelectSql(\$this, \$params); - if (\$key) { - \$this->cacheStore(\$key, \$sql); - } - } - \$stmt = \$con->prepare(\$sql); - BasePeer::populateStmtValues(\$stmt, \$params, \$dbMap, \$db); - \$stmt->execute(); - \$con->commit(); - } catch (PropelException \$e) { - \$con->rollback(); - throw \$e; - } - - return \$stmt; -} -"; - } - - protected function addGetCountStatement(&$script) - { - $script .= " -protected function getCountStatement(\$con = null) -{ - \$dbMap = Propel::getDatabaseMap(\$this->getDbName()); - \$db = Propel::getDB(\$this->getDbName()); - if (\$con === null) { - \$con = Propel::getConnection(\$this->getDbName(), Propel::CONNECTION_READ); - } - - \$con->beginTransaction(); - try { - \$this->basePreSelect(\$con); - \$key = \$this->getQueryKey(); - if (\$key && \$this->cacheContains(\$key)) { - \$params = \$this->getParams(); - \$sql = \$this->cacheFetch(\$key); - } else { - if (!\$this->hasSelectClause() && !\$this->getPrimaryCriteria()) { - \$this->addSelfSelectColumns(); - } - \$params = array(); - \$needsComplexCount = \$this->getGroupByColumns() - || \$this->getOffset() - || \$this->getLimit() - || \$this->getHaving() - || in_array(Criteria::DISTINCT, \$this->getSelectModifiers()); - if (\$needsComplexCount) { - if (BasePeer::needsSelectAliases(\$this)) { - if (\$this->getHaving()) { - throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part'); - } - BasePeer::turnSelectColumnsToAliases(\$this); - } - \$selectSql = BasePeer::createSelectSql(\$this, \$params); - \$sql = 'SELECT COUNT(*) FROM (' . \$selectSql . ') propelmatch4cnt'; - } else { - // Replace SELECT columns with COUNT(*) - \$this->clearSelectColumns()->addSelectColumn('COUNT(*)'); - \$sql = BasePeer::createSelectSql(\$this, \$params); - } - if (\$key) { - \$this->cacheStore(\$key, \$sql); - } - } - \$stmt = \$con->prepare(\$sql); - BasePeer::populateStmtValues(\$stmt, \$params, \$dbMap, \$db); - \$stmt->execute(); - \$con->commit(); - } catch (PropelException \$e) { - \$con->rollback(); - throw \$e; - } - - return \$stmt; -} -"; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/sluggable/SluggableBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/sluggable/SluggableBehavior.php deleted file mode 100644 index d9909a335..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/sluggable/SluggableBehavior.php +++ /dev/null @@ -1,332 +0,0 @@ - 'slug', - 'slug_pattern' => '', - 'replace_pattern' => '/\W+/', // Tip: use '/[^\\pL\\d]+/u' instead if you're in PHP5.3 - 'replacement' => '-', - 'separator' => '-', - 'permanent' => 'false' - ); - - /** - * Add the slug_column to the current table - */ - public function modifyTable() - { - if(!$this->getTable()->containsColumn($this->getParameter('slug_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('slug_column'), - 'type' => 'VARCHAR', - 'size' => 255 - )); - // add a unique to column - $unique = new Unique($this->getColumnForParameter('slug_column')); - $unique->setName($this->getTable()->getName() . '_slug'); - $unique->addColumn($this->getTable()->getColumn($this->getParameter('slug_column'))); - $this->getTable()->addUnique($unique); - } - } - - /** - * Get the getter of the column of the behavior - * - * @return string The related getter, e.g. 'getSlug' - */ - protected function getColumnGetter() - { - return 'get' . $this->getColumnForParameter('slug_column')->getPhpName(); - } - - /** - * Get the setter of the column of the behavior - * - * @return string The related setter, e.g. 'setSlug' - */ - protected function getColumnSetter() - { - return 'set' . $this->getColumnForParameter('slug_column')->getPhpName(); - } - - /** - * Add code in ObjectBuilder::preSave - * - * @return string The code to put at the hook - */ - public function preSave($builder) - { - $const = $builder->getColumnConstant($this->getColumnForParameter('slug_column'), $this->getTable()->getPhpName() . 'Peer'); - $script = " -if (\$this->isColumnModified($const) && \$this->{$this->getColumnGetter()}()) { - \$this->{$this->getColumnSetter()}(\$this->makeSlugUnique(\$this->{$this->getColumnGetter()}()));"; - if ($this->getParameter('permanent') == 'true') { - $script .= " -} elseif (!\$this->{$this->getColumnGetter()}()) { - \$this->{$this->getColumnSetter()}(\$this->createSlug()); -}"; - } else { - $script .= " -} else { - \$this->{$this->getColumnSetter()}(\$this->createSlug()); -}"; - } - - return $script; - } - - public function objectMethods($builder) - { - $this->builder = $builder; - $script = ''; - if ($this->getParameter('slug_column') != 'slug') { - $this->addSlugSetter($script); - $this->addSlugGetter($script); - } - $this->addCreateSlug($script); - $this->addCreateRawSlug($script); - $this->addCleanupSlugPart($script); - $this->addLimitSlugSize($script); - $this->addMakeSlugUnique($script); - - return $script; - } - - protected function addSlugSetter(&$script) - { - $script .= " -/** - * Wrap the setter for slug value - * - * @param string - * @return " . $this->getTable()->getPhpName() . " - */ -public function setSlug(\$v) -{ - return \$this->" . $this->getColumnSetter() . "(\$v); -} -"; - } - - protected function addSlugGetter(&$script) - { - $script .= " -/** - * Wrap the getter for slug value - * - * @return string - */ -public function getSlug() -{ - return \$this->" . $this->getColumnGetter() . "(); -} -"; - } - - protected function addCreateSlug(&$script) - { - $script .= " -/** - * Create a unique slug based on the object - * - * @return string The object slug - */ -protected function createSlug() -{ - \$slug = \$this->createRawSlug(); - \$slug = \$this->limitSlugSize(\$slug); - \$slug = \$this->makeSlugUnique(\$slug); - - return \$slug; -} -"; - } - - protected function addCreateRawSlug(&$script) - { - $pattern = $this->getParameter('slug_pattern'); - $script .= " -/** - * Create the slug from the appropriate columns - * - * @return string - */ -protected function createRawSlug() -{ - "; - if ($pattern) { - $script .= "return '" . str_replace(array('{', '}'), array('\' . $this->cleanupSlugPart($this->get', '()) . \''), $pattern). "';"; - } else { - $script .= "return \$this->cleanupSlugPart(\$this->__toString());"; - } - $script .= " -} -"; - return $script; - } - - public function addCleanupSlugPart(&$script) - { - $script .= " -/** - * Cleanup a string to make a slug of it - * Removes special characters, replaces blanks with a separator, and trim it - * - * @param string \$text the text to slugify - * @param string \$separator the separator used by slug - * @return string the slugified text - */ -protected static function cleanupSlugPart(\$slug, \$replacement = '" . $this->getParameter('replacement') . "') -{ - // transliterate - if (function_exists('iconv')) { - \$slug = iconv('utf-8', 'us-ascii//TRANSLIT', \$slug); - } - - // lowercase - if (function_exists('mb_strtolower')) { - \$slug = mb_strtolower(\$slug); - } else { - \$slug = strtolower(\$slug); - } - - // remove accents resulting from OSX's iconv - \$slug = str_replace(array('\'', '`', '^'), '', \$slug); - - // replace non letter or digits with separator - \$slug = preg_replace('" . $this->getParameter('replace_pattern') . "', \$replacement, \$slug); - - // trim - \$slug = trim(\$slug, \$replacement); - - if (empty(\$slug)) { - return 'n-a'; - } - - return \$slug; -} -"; - } - - public function addLimitSlugSize(&$script) - { - $size = $this->getColumnForParameter('slug_column')->getSize(); - $script .= " - -/** - * Make sure the slug is short enough to accomodate the column size - * - * @param string \$slug the slug to check - * - * @return string the truncated slug - */ -protected static function limitSlugSize(\$slug, \$incrementReservedSpace = 3) -{ - // check length, as suffix could put it over maximum - if (strlen(\$slug) > ($size - \$incrementReservedSpace)) { - \$slug = substr(\$slug, 0, $size - \$incrementReservedSpace); - } - return \$slug; -} -"; - } - - public function addMakeSlugUnique(&$script) - { - $script .= " - -/** - * Get the slug, ensuring its uniqueness - * - * @param string \$slug the slug to check - * @param string \$separator the separator used by slug - * @return string the unique slug - */ -protected function makeSlugUnique(\$slug, \$separator = '" . $this->getParameter('separator') ."', \$increment = 0) -{ - \$slug2 = empty(\$increment) ? \$slug : \$slug . \$separator . \$increment; - \$slugAlreadyExists = " . $this->builder->getStubQueryBuilder()->getClassname() . "::create() - ->filterBySlug(\$slug2) - ->prune(\$this)"; - // watch out: some of the columns may be hidden by the soft_delete behavior - if ($this->table->hasBehavior('soft_delete')) { - $script .= " - ->includeDeleted()"; - } - $script .= " - ->count(); - if (\$slugAlreadyExists) { - return \$this->makeSlugUnique(\$slug, \$separator, ++\$increment); - } else { - return \$slug2; - } -} -"; - } - - public function queryMethods($builder) - { - $this->builder = $builder; - $script = ''; - if ($this->getParameter('slug_column') != 'slug') { - $this->addFilterBySlug($script); - } - $this->addFindOneBySlug($script); - - return $script; - } - - protected function addFilterBySlug(&$script) - { - $script .= " -/** - * Filter the query on the slug column - * - * @param string \$slug The value to use as filter. - * - * @return " . $this->builder->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface - */ -public function filterBySlug(\$slug) -{ - return \$this->addUsingAlias(" . $this->builder->getColumnConstant($this->getColumnForParameter('slug_column')) . ", \$slug, Criteria::EQUAL); -} -"; - } - - protected function addFindOneBySlug(&$script) - { - $script .= " -/** - * Find one object based on its slug - * - * @param string \$slug The value to use as filter. - * @param PropelPDO \$con The optional connection object - * - * @return " . $this->builder->getStubObjectBuilder()->getClassname() . " the result, formatted by the current formatter - */ -public function findOneBySlug(\$slug, \$con = null) -{ - return \$this->filterBySlug(\$slug)->findOne(\$con); -} -"; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehavior.php b/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehavior.php deleted file mode 100644 index 3fe78cb9c..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehavior.php +++ /dev/null @@ -1,83 +0,0 @@ - 'sortable_rank', - 'use_scope' => 'false', - 'scope_column' => 'sortable_scope', - ); - - protected $objectBuilderModifier, $queryBuilderModifier, $peerBuilderModifier; - - /** - * Add the rank_column to the current table - */ - public function modifyTable() - { - if (!$this->getTable()->containsColumn($this->getParameter('rank_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('rank_column'), - 'type' => 'INTEGER' - )); - } - if ($this->getParameter('use_scope') == 'true' && - !$this->getTable()->containsColumn($this->getParameter('scope_column'))) { - $this->getTable()->addColumn(array( - 'name' => $this->getParameter('scope_column'), - 'type' => 'INTEGER' - )); - } - } - - public function getObjectBuilderModifier() - { - if (is_null($this->objectBuilderModifier)) { - $this->objectBuilderModifier = new SortableBehaviorObjectBuilderModifier($this); - } - return $this->objectBuilderModifier; - } - - public function getQueryBuilderModifier() - { - if (is_null($this->queryBuilderModifier)) { - $this->queryBuilderModifier = new SortableBehaviorQueryBuilderModifier($this); - } - return $this->queryBuilderModifier; - } - - public function getPeerBuilderModifier() - { - if (is_null($this->peerBuilderModifier)) { - $this->peerBuilderModifier = new SortableBehaviorPeerBuilderModifier($this); - } - return $this->peerBuilderModifier; - } - - public function useScope() - { - return $this->getParameter('use_scope') == 'true'; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorObjectBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorObjectBuilderModifier.php deleted file mode 100644 index a59d28b0e..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorObjectBuilderModifier.php +++ /dev/null @@ -1,636 +0,0 @@ - - * @package propel.generator.behavior.sortable - */ -class SortableBehaviorObjectBuilderModifier -{ - protected $behavior, $table, $builder, $objectClassname, $peerClassname; - - public function __construct($behavior) - { - $this->behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumnAttribute($name) - { - return strtolower($this->behavior->getColumnForParameter($name)->getName()); - } - - protected function getColumnPhpName($name) - { - return $this->behavior->getColumnForParameter($name)->getPhpName(); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->queryClassname = $builder->getStubQueryBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - /** - * Get the getter of the column of the behavior - * - * @return string The related getter, e.g. 'getRank' - */ - protected function getColumnGetter($columnName = 'rank_column') - { - return 'get' . $this->behavior->getColumnForParameter($columnName)->getPhpName(); - } - - /** - * Get the setter of the column of the behavior - * - * @return string The related setter, e.g. 'setRank' - */ - protected function getColumnSetter($columnName = 'rank_column') - { - return 'set' . $this->behavior->getColumnForParameter($columnName)->getPhpName(); - } - - public function preSave($builder) - { - return "\$this->processSortableQueries(\$con);"; - } - - public function preInsert($builder) - { - $useScope = $this->behavior->useScope(); - $this->setBuilder($builder); - return "if (!\$this->isColumnModified({$this->peerClassname}::RANK_COL)) { - \$this->{$this->getColumnSetter()}({$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con) + 1); -} -"; - } - - public function preDelete($builder) - { - $useScope = $this->behavior->useScope(); - $this->setBuilder($builder); - return " -{$this->peerClassname}::shiftRank(-1, \$this->{$this->getColumnGetter()}() + 1, null, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con); -{$this->peerClassname}::clearInstancePool(); -"; - } - - public function objectAttributes($builder) - { - return " -/** - * Queries to be executed in the save transaction - * @var array - */ -protected \$sortableQueries = array(); -"; - } - - public function objectMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - if ($this->getParameter('rank_column') != 'rank') { - $this->addRankAccessors($script); - } - if ($this->behavior->useScope() && - $this->getParameter('scope_column') != 'scope_value') { - $this->addScopeAccessors($script); - } - $this->addIsFirst($script); - $this->addIsLast($script); - $this->addGetNext($script); - $this->addGetPrevious($script); - $this->addInsertAtRank($script); - $this->addInsertAtBottom($script); - $this->addInsertAtTop($script); - $this->addMoveToRank($script); - $this->addSwapWith($script); - $this->addMoveUp($script); - $this->addMoveDown($script); - $this->addMoveToTop($script); - $this->addMoveToBottom($script); - $this->addRemoveFromList($script); - $this->addProcessSortableQueries($script); - - return $script; - } - - /** - * Get the wraps for getter/setter, if the rank column has not the default name - * - * @return string - */ - protected function addRankAccessors(&$script) - { - $script .= " -/** - * Wrap the getter for rank value - * - * @return int - */ -public function getRank() -{ - return \$this->{$this->getColumnAttribute('rank_column')}; -} - -/** - * Wrap the setter for rank value - * - * @param int - * @return {$this->objectClassname} - */ -public function setRank(\$v) -{ - return \$this->{$this->getColumnSetter()}(\$v); -} -"; - } - - /** - * Get the wraps for getter/setter, if the scope column has not the default name - * - * @return string - */ - protected function addScopeAccessors(&$script) - { - $script .= " -/** - * Wrap the getter for scope value - * - * @return int - */ -public function getScopeValue() -{ - return \$this->{$this->getColumnAttribute('scope_column')}; -} - -/** - * Wrap the setter for scope value - * - * @param int - * @return {$this->objectClassname} - */ -public function setScopeValue(\$v) -{ - return \$this->{$this->getColumnSetter('scope_column')}(\$v); -} -"; - } - - protected function addIsFirst(&$script) - { - $script .= " -/** - * Check if the object is first in the list, i.e. if it has 1 for rank - * - * @return boolean - */ -public function isFirst() -{ - return \$this->{$this->getColumnGetter()}() == 1; -} -"; - } - - protected function addIsLast(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Check if the object is last in the list, i.e. if its rank is the highest rank - * - * @param PropelPDO \$con optional connection - * - * @return boolean - */ -public function isLast(PropelPDO \$con = null) -{ - return \$this->{$this->getColumnGetter()}() == {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con); -} -"; - } - - protected function addGetNext(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Get the next item in the list, i.e. the one for which rank is immediately higher - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} - */ -public function getNext(PropelPDO \$con = null) -{"; - if ($this->behavior->getParameter('rank_column') == 'rank' && $useScope) { - $script .= " - return {$this->queryClassname}::create() - ->filterByRank(\$this->{$this->getColumnGetter()}() + 1) - ->inList(\$this->{$this->getColumnGetter('scope_column')}()) - ->findOne(\$con);"; - } else { - $script .= " - return {$this->queryClassname}::create()->findOneByRank(\$this->{$this->getColumnGetter()}() + 1, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);"; - } - - $script .= " -} -"; - } - - protected function addGetPrevious(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Get the previous item in the list, i.e. the one for which rank is immediately lower - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} - */ -public function getPrevious(PropelPDO \$con = null) -{"; - if ($this->behavior->getParameter('rank_column') == 'rank' && $useScope) { - $script .= " - return {$this->queryClassname}::create() - ->filterByRank(\$this->{$this->getColumnGetter()}() - 1) - ->inList(\$this->{$this->getColumnGetter('scope_column')}()) - ->findOne(\$con);"; - } else { - $script .= " - return {$this->queryClassname}::create()->findOneByRank(\$this->{$this->getColumnGetter()}() - 1, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);"; - } - $script .= " -} -"; - } - - protected function addInsertAtRank(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Insert at specified rank - * The modifications are not persisted until the object is saved. - * - * @param integer \$rank rank value - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - * - * @throws PropelException - */ -public function insertAtRank(\$rank, PropelPDO \$con = null) -{"; - if ($useScope) { - $script .= " - if (null === \$this->{$this->getColumnGetter('scope_column')}()) { - throw new PropelException('The scope must be defined before inserting an object in a suite'); - }"; - } - $script .= " - \$maxRank = {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con); - if (\$rank < 1 || \$rank > \$maxRank + 1) { - throw new PropelException('Invalid rank ' . \$rank); - } - // move the object in the list, at the given rank - \$this->{$this->getColumnSetter()}(\$rank); - if (\$rank != \$maxRank + 1) { - // Keep the list modification query for the save() transaction - \$this->sortableQueries []= array( - 'callable' => array('$peerClassname', 'shiftRank'), - 'arguments' => array(1, \$rank, null, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}()" : '') . ") - ); - } - - return \$this; -} -"; - } - - protected function addInsertAtBottom(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Insert in the last rank - * The modifications are not persisted until the object is saved. - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - * - * @throws PropelException - */ -public function insertAtBottom(PropelPDO \$con = null) -{"; - if ($useScope) { - $script .= " - if (null === \$this->{$this->getColumnGetter('scope_column')}()) { - throw new PropelException('The scope must be defined before inserting an object in a suite'); - }"; - } - $script .= " - \$this->{$this->getColumnSetter()}({$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con) + 1); - - return \$this; -} -"; - } - - protected function addInsertAtTop(&$script) - { - $script .= " -/** - * Insert in the first rank - * The modifications are not persisted until the object is saved. - * - * @return {$this->objectClassname} the current object - */ -public function insertAtTop() -{ - return \$this->insertAtRank(1); -} -"; - } - - protected function addMoveToRank(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Move the object to a new rank, and shifts the rank - * Of the objects inbetween the old and new rank accordingly - * - * @param integer \$newRank rank value - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - * - * @throws PropelException - */ -public function moveToRank(\$newRank, PropelPDO \$con = null) -{ - if (\$this->isNew()) { - throw new PropelException('New objects cannot be moved. Please use insertAtRank() instead'); - } - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - } - if (\$newRank < 1 || \$newRank > {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con)) { - throw new PropelException('Invalid rank ' . \$newRank); - } - - \$oldRank = \$this->{$this->getColumnGetter()}(); - if (\$oldRank == \$newRank) { - return \$this; - } - - \$con->beginTransaction(); - try { - // shift the objects between the old and the new rank - \$delta = (\$oldRank < \$newRank) ? -1 : 1; - $peerClassname::shiftRank(\$delta, min(\$oldRank, \$newRank), max(\$oldRank, \$newRank), " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con); - - // move the object to its new rank - \$this->{$this->getColumnSetter()}(\$newRank); - \$this->save(\$con); - - \$con->commit(); - return \$this; - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addSwapWith(&$script) - { - $script .= " -/** - * Exchange the rank of the object with the one passed as argument, and saves both objects - * - * @param {$this->objectClassname} \$object - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - * - * @throws Exception if the database cannot execute the two updates - */ -public function swapWith(\$object, PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - \$con->beginTransaction(); - try { - \$oldRank = \$this->{$this->getColumnGetter()}(); - \$newRank = \$object->{$this->getColumnGetter()}(); - \$this->{$this->getColumnSetter()}(\$newRank); - \$this->save(\$con); - \$object->{$this->getColumnSetter()}(\$oldRank); - \$object->save(\$con); - \$con->commit(); - - return \$this; - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addMoveUp(&$script) - { - $script .= " -/** - * Move the object higher in the list, i.e. exchanges its rank with the one of the previous object - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - */ -public function moveUp(PropelPDO \$con = null) -{ - if (\$this->isFirst()) { - return \$this; - } - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - \$con->beginTransaction(); - try { - \$prev = \$this->getPrevious(\$con); - \$this->swapWith(\$prev, \$con); - \$con->commit(); - - return \$this; - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addMoveDown(&$script) - { - $script .= " -/** - * Move the object higher in the list, i.e. exchanges its rank with the one of the next object - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - */ -public function moveDown(PropelPDO \$con = null) -{ - if (\$this->isLast(\$con)) { - return \$this; - } - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - \$con->beginTransaction(); - try { - \$next = \$this->getNext(\$con); - \$this->swapWith(\$next, \$con); - \$con->commit(); - - return \$this; - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addMoveToTop(&$script) - { - $script .= " -/** - * Move the object to the top of the list - * - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} the current object - */ -public function moveToTop(PropelPDO \$con = null) -{ - if (\$this->isFirst()) { - return \$this; - } - return \$this->moveToRank(1, \$con); -} -"; - } - - protected function addMoveToBottom(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Move the object to the bottom of the list - * - * @param PropelPDO \$con optional connection - * - * @return integer the old object's rank - */ -public function moveToBottom(PropelPDO \$con = null) -{ - if (\$this->isLast(\$con)) { - return false; - } - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - \$con->beginTransaction(); - try { - \$bottom = {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con); - \$res = \$this->moveToRank(\$bottom, \$con); - \$con->commit(); - - return \$res; - } catch (Exception \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addRemoveFromList(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Removes the current object from the list. - * The modifications are not persisted until the object is saved. - * - * @return {$this->objectClassname} the current object - */ -public function removeFromList() -{ - // Keep the list modification query for the save() transaction - \$this->sortableQueries []= array( - 'callable' => array('$peerClassname', 'shiftRank'), - 'arguments' => array(-1, \$this->{$this->getColumnGetter()}() + 1, null" . ($useScope ? ", \$this->{$this->getColumnGetter('scope_column')}()" : '') . ") - ); - // remove the object from the list - \$this->{$this->getColumnSetter('rank_column')}(null);"; - if ($useScope) { - $script .= " - \$this->{$this->getColumnSetter('scope_column')}(null);"; - } - $script .= " - - return \$this; -} -"; - } - - protected function addProcessSortableQueries(&$script) - { - $script .= " -/** - * Execute queries that were saved to be run inside the save transaction - */ -protected function processSortableQueries(\$con) -{ - foreach (\$this->sortableQueries as \$query) { - \$query['arguments'][]= \$con; - call_user_func_array(\$query['callable'], \$query['arguments']); - } - \$this->sortableQueries = array(); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php deleted file mode 100644 index bb2b687ff..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php +++ /dev/null @@ -1,367 +0,0 @@ - - * @package propel.generator.behavior.sortable - */ -class SortableBehaviorPeerBuilderModifier -{ - protected $behavior, $table, $builder, $objectClassname, $peerClassname; - - public function __construct($behavior) - { - $this->behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumnAttribute($name) - { - return strtolower($this->behavior->getColumnForParameter($name)->getName()); - } - - protected function getColumnConstant($name) - { - return strtoupper($this->behavior->getColumnForParameter($name)->getName()); - } - - protected function getColumnPhpName($name) - { - return $this->behavior->getColumnForParameter($name)->getPhpName(); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - public function staticAttributes($builder) - { - $tableName = $this->table->getName(); - $script = " -/** - * rank column - */ -const RANK_COL = '" . $tableName . '.' . $this->getColumnConstant('rank_column') . "'; -"; - - if ($this->behavior->useScope()) { - $script .= " -/** - * Scope column for the set - */ -const SCOPE_COL = '" . $tableName . '.' . $this->getColumnConstant('scope_column') . "'; -"; - } - - return $script; - } - - /** - * Static methods - * - * @return string - */ - public function staticMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - - $this->addGetMaxRank($script); - $this->addRetrieveByRank($script); - $this->addReorder($script); - $this->addDoSelectOrderByRank($script); - if ($this->behavior->useScope()) { - $this->addRetrieveList($script); - $this->addCountList($script); - $this->addDeleteList($script); - } - $this->addShiftRank($script); - - return $script; - } - - protected function addGetMaxRank(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Get the highest rank - * "; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which suite to consider"; - } - $script .= " - * @param PropelPDO optional connection - * - * @return integer highest position - */ -public static function getMaxRank(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - // shift the objects with a position lower than the one of object - \$c = new Criteria(); - \$c->addSelectColumn('MAX(' . {$this->peerClassname}::RANK_COL . ')');"; - if ($useScope) { - $script .= " - \$c->add({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - \$stmt = {$this->peerClassname}::doSelectStmt(\$c, \$con); - - return \$stmt->fetchColumn(); -} -"; - } - - protected function addRetrieveByRank(&$script) - { - $peerClassname = $this->peerClassname; - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Get an item from the list based on its rank - * - * @param integer \$rank rank"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which suite to consider"; - } - $script .= " - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} - */ -public static function retrieveByRank(\$rank, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - } - - \$c = new Criteria; - \$c->add($peerClassname::RANK_COL, \$rank);"; - if($useScope) { - $script .= " - \$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - return $peerClassname::doSelectOne(\$c, \$con); -} -"; - } - - protected function addReorder(&$script) - { - $peerClassname = $this->peerClassname; - $columnGetter = 'get' . $this->behavior->getColumnForParameter('rank_column')->getPhpName(); - $columnSetter = 'set' . $this->behavior->getColumnForParameter('rank_column')->getPhpName(); - $script .= " -/** - * Reorder a set of sortable objects based on a list of id/position - * Beware that there is no check made on the positions passed - * So incoherent positions will result in an incoherent list - * - * @param array \$order id => rank pairs - * @param PropelPDO \$con optional connection - * - * @return boolean true if the reordering took place, false if a database problem prevented it - */ -public static function reorder(array \$order, PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - } - - \$con->beginTransaction(); - try { - \$ids = array_keys(\$order); - \$objects = $peerClassname::retrieveByPKs(\$ids); - foreach (\$objects as \$object) { - \$pk = \$object->getPrimaryKey(); - if (\$object->$columnGetter() != \$order[\$pk]) { - \$object->$columnSetter(\$order[\$pk]); - \$object->save(\$con); - } - } - \$con->commit(); - - return true; - } catch (PropelException \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - - protected function addDoSelectOrderByRank(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Return an array of sortable objects ordered by position - * - * @param Criteria \$criteria optional criteria object - * @param string \$order sorting order, to be chosen between Criteria::ASC (default) and Criteria::DESC - * @param PropelPDO \$con optional connection - * - * @return array list of sortable objects - */ -public static function doSelectOrderByRank(Criteria \$criteria = null, \$order = Criteria::ASC, PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - } - - if (\$criteria === null) { - \$criteria = new Criteria(); - } elseif (\$criteria instanceof Criteria) { - \$criteria = clone \$criteria; - } - - \$criteria->clearOrderByColumns(); - - if (\$order == Criteria::ASC) { - \$criteria->addAscendingOrderByColumn($peerClassname::RANK_COL); - } else { - \$criteria->addDescendingOrderByColumn($peerClassname::RANK_COL); - } - - return $peerClassname::doSelect(\$criteria, \$con); -} -"; - } - - protected function addRetrieveList(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Return an array of sortable objects in the given scope ordered by position - * - * @param int \$scope the scope of the list - * @param string \$order sorting order, to be chosen between Criteria::ASC (default) and Criteria::DESC - * @param PropelPDO \$con optional connection - * - * @return array list of sortable objects - */ -public static function retrieveList(\$scope, \$order = Criteria::ASC, PropelPDO \$con = null) -{ - \$c = new Criteria(); - \$c->add($peerClassname::SCOPE_COL, \$scope); - - return $peerClassname::doSelectOrderByRank(\$c, \$order, \$con); -} -"; - } - - protected function addCountList(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Return the number of sortable objects in the given scope - * - * @param int \$scope the scope of the list - * @param PropelPDO \$con optional connection - * - * @return array list of sortable objects - */ -public static function countList(\$scope, PropelPDO \$con = null) -{ - \$c = new Criteria(); - \$c->add($peerClassname::SCOPE_COL, \$scope); - - return $peerClassname::doCount(\$c, \$con); -} -"; - } - - protected function addDeleteList(&$script) - { - $peerClassname = $this->peerClassname; - $script .= " -/** - * Deletes the sortable objects in the given scope - * - * @param int \$scope the scope of the list - * @param PropelPDO \$con optional connection - * - * @return int number of deleted objects - */ -public static function deleteList(\$scope, PropelPDO \$con = null) -{ - \$c = new Criteria(); - \$c->add($peerClassname::SCOPE_COL, \$scope); - - return $peerClassname::doDelete(\$c, \$con); -} -"; - } - protected function addShiftRank(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Adds \$delta to all Rank values that are >= \$first and <= \$last. - * '\$delta' can also be negative. - * - * @param int \$delta Value to be shifted by, can be negative - * @param int \$first First node to be shifted - * @param int \$last Last node to be shifted"; - if($useScope) { - $script .= " - * @param int \$scope Scope to use for the shift"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - */ -public static function shiftRank(\$delta, \$first, \$last = null, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion($peerClassname::RANK_COL, \$first, Criteria::GREATER_EQUAL); - if (null !== \$last) { - \$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::RANK_COL, \$last, Criteria::LESS_EQUAL)); - } - \$whereCriteria->add(\$criterion);"; - if ($useScope) { - $script .= " - \$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add($peerClassname::RANK_COL, array('raw' => $peerClassname::RANK_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL); - - {$this->builder->getPeerBuilder()->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - $peerClassname::clearInstancePool(); -} -"; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorQueryBuilderModifier.php b/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorQueryBuilderModifier.php deleted file mode 100644 index 5e469ca32..000000000 --- a/airtime_mvc/library/propel/generator/lib/behavior/sortable/SortableBehaviorQueryBuilderModifier.php +++ /dev/null @@ -1,283 +0,0 @@ -behavior = $behavior; - $this->table = $behavior->getTable(); - } - - protected function getParameter($key) - { - return $this->behavior->getParameter($key); - } - - protected function getColumn($name) - { - return $this->behavior->getColumnForParameter($name); - } - - protected function setBuilder($builder) - { - $this->builder = $builder; - $this->objectClassname = $builder->getStubObjectBuilder()->getClassname(); - $this->queryClassname = $builder->getStubQueryBuilder()->getClassname(); - $this->peerClassname = $builder->getStubPeerBuilder()->getClassname(); - } - - public function queryMethods($builder) - { - $this->setBuilder($builder); - $script = ''; - - // select filters - if ($this->behavior->useScope()) { - $this->addInList($script); - } - if ($this->getParameter('rank_column') != 'rank') { - $this->addFilterByRank($script); - $this->addOrderByRank($script); - } - - // select termination methods - if ($this->getParameter('rank_column') != 'rank') { - $this->addFindOneByRank($script); - } - $this->addFindList($script); - - // utilities - $this->addGetMaxRank($script); - $this->addReorder($script); - - return $script; - } - - protected function addInList(&$script) - { - $script .= " -/** - * Returns the objects in a certain list, from the list scope - * - * @param int \$scope Scope to determine which objects node to return - * - * @return {$this->queryClassname} The current query, for fuid interface - */ -public function inList(\$scope = null) -{ - return \$this->addUsingAlias({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL); -} -"; - } - - protected function addFilterByRank(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Filter the query based on a rank in the list - * - * @param integer \$rank rank"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which suite to consider"; - } - $script .= " - * - * @return " . $this->queryClassname . " The current query, for fluid interface - */ -public function filterByRank(\$rank" . ($useScope ? ", \$scope = null" : "") . ") -{ - return \$this"; - if ($useScope) { - $script .= " - ->inList(\$scope)"; - } - $script .= " - ->addUsingAlias($peerClassname::RANK_COL, \$rank, Criteria::EQUAL); -} -"; - } - - protected function addOrderByRank(&$script) - { - $script .= " -/** - * Order the query based on the rank in the list. - * Using the default \$order, returns the item with the lowest rank first - * - * @param string \$order either Criteria::ASC (default) or Criteria::DESC - * - * @return " . $this->queryClassname . " The current query, for fluid interface - */ -public function orderByRank(\$order = Criteria::ASC) -{ - \$order = strtoupper(\$order); - switch (\$order) { - case Criteria::ASC: - return \$this->addAscendingOrderByColumn(\$this->getAliasedColName(" . $this->peerClassname . "::RANK_COL)); - break; - case Criteria::DESC: - return \$this->addDescendingOrderByColumn(\$this->getAliasedColName(" . $this->peerClassname . "::RANK_COL)); - break; - default: - throw new PropelException('" . $this->queryClassname . "::orderBy() only accepts \"asc\" or \"desc\" as argument'); - } -} -"; - } - - protected function addFindOneByRank(&$script) - { - $useScope = $this->behavior->useScope(); - $peerClassname = $this->peerClassname; - $script .= " -/** - * Get an item from the list based on its rank - * - * @param integer \$rank rank"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which suite to consider"; - } - $script .= " - * @param PropelPDO \$con optional connection - * - * @return {$this->objectClassname} - */ -public function findOneByRank(\$rank, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - return \$this - ->filterByRank(\$rank" . ($useScope ? ", \$scope" : "") . ") - ->findOne(\$con); -} -"; - } - - protected function addFindList(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Returns " . ($useScope ? 'a' : 'the') ." list of objects - *"; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which list to return"; - } - $script .= " - * @param PropelPDO \$con Connection to use. - * - * @return mixed the list of results, formatted by the current formatter - */ -public function findList(" . ($useScope ? "\$scope = null, " : "") . "\$con = null) -{ - return \$this"; - if ($useScope) { - $script .= " - ->inList(\$scope)"; - } - $script .= " - ->orderByRank() - ->find(\$con); -} -"; - } - - protected function addGetMaxRank(&$script) - { - $useScope = $this->behavior->useScope(); - $script .= " -/** - * Get the highest rank - * "; - if($useScope) { - $script .= " - * @param int \$scope Scope to determine which suite to consider"; - } - $script .= " - * @param PropelPDO optional connection - * - * @return integer highest position - */ -public function getMaxRank(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME); - } - // shift the objects with a position lower than the one of object - \$this->addSelectColumn('MAX(' . {$this->peerClassname}::RANK_COL . ')');"; - if ($useScope) { - $script .= " - \$this->add({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);"; - } - $script .= " - \$stmt = \$this->getSelectStatement(\$con); - - return \$stmt->fetchColumn(); -} -"; - } - - protected function addReorder(&$script) - { - $peerClassname = $this->peerClassname; - $columnGetter = 'get' . $this->behavior->getColumnForParameter('rank_column')->getPhpName(); - $columnSetter = 'set' . $this->behavior->getColumnForParameter('rank_column')->getPhpName(); - $script .= " -/** - * Reorder a set of sortable objects based on a list of id/position - * Beware that there is no check made on the positions passed - * So incoherent positions will result in an incoherent list - * - * @param array \$order id => rank pairs - * @param PropelPDO \$con optional connection - * - * @return boolean true if the reordering took place, false if a database problem prevented it - */ -public function reorder(array \$order, PropelPDO \$con = null) -{ - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - } - - \$con->beginTransaction(); - try { - \$ids = array_keys(\$order); - \$objects = \$this->findPks(\$ids, \$con); - foreach (\$objects as \$object) { - \$pk = \$object->getPrimaryKey(); - if (\$object->$columnGetter() != \$order[\$pk]) { - \$object->$columnSetter(\$order[\$pk]); - \$object->save(\$con); - } - } - \$con->commit(); - - return true; - } catch (PropelException \$e) { - \$con->rollback(); - throw \$e; - } -} -"; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/builder/DataModelBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/DataModelBuilder.php deleted file mode 100644 index 605f0d5d1..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/DataModelBuilder.php +++ /dev/null @@ -1,607 +0,0 @@ - - * @package propel.generator.builder - */ -abstract class DataModelBuilder -{ - - /** - * The current table. - * @var Table - */ - private $table; - - /** - * The generator config object holding build properties, etc. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * An array of warning messages that can be retrieved for display (e.g. as part of phing build process). - * @var array string[] - */ - private $warnings = array(); - - /** - * Peer builder class for current table. - * @var DataModelBuilder - */ - private $peerBuilder; - - /** - * Stub Peer builder class for current table. - * @var DataModelBuilder - */ - private $stubPeerBuilder; - - /** - * Object builder class for current table. - * @var DataModelBuilder - */ - private $objectBuilder; - - /** - * Stub Object builder class for current table. - * @var DataModelBuilder - */ - private $stubObjectBuilder; - - /** - * Query builder class for current table. - * @var DataModelBuilder - */ - private $queryBuilder; - - /** - * Stub Query builder class for current table. - * @var DataModelBuilder - */ - private $stubQueryBuilder; - - /** - * TableMap builder class for current table. - * @var DataModelBuilder - */ - protected $tablemapBuilder; - - /** - * Stub Interface builder class for current table. - * @var DataModelBuilder - */ - private $interfaceBuilder; - - /** - * Stub child object for current table. - * @var DataModelBuilder - */ - private $multiExtendObjectBuilder; - - /** - * Node object builder for current table. - * @var DataModelBuilder - */ - private $nodeBuilder; - - /** - * Node peer builder for current table. - * @var DataModelBuilder - */ - private $nodePeerBuilder; - - /** - * Stub node object builder for current table. - * @var DataModelBuilder - */ - private $stubNodeBuilder; - - /** - * Stub node peer builder for current table. - * @var DataModelBuilder - */ - private $stubNodePeerBuilder; - - /** - * NestedSet object builder for current table. - * @var DataModelBuilder - */ - private $nestedSetBuilder; - - /** - * NestedSet peer builder for current table. - * @var DataModelBuilder - */ - private $nestedSetPeerBuilder; - - /** - * The DDL builder for current table. - * @var DDLBuilder - */ - private $ddlBuilder; - - /** - * The Data-SQL builder for current table. - * @var DataSQLBuilder - */ - private $dataSqlBuilder; - - /** - * The Pluralizer class to use. - * @var Pluralizer - */ - private $pluralizer; - - - /** - * Creates new instance of DataModelBuilder subclass. - * @param Table $table The Table which we are using to build [OM, DDL, etc.]. - */ - public function __construct(Table $table) - { - $this->table = $table; - } - - /** - * Returns new or existing Peer builder class for this table. - * @return PeerBuilder - */ - public function getPeerBuilder() - { - if (!isset($this->peerBuilder)) { - $this->peerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'peer'); - } - return $this->peerBuilder; - } - - /** - * Returns new or existing Pluralizer class. - * @return Pluralizer - */ - public function getPluralizer() - { - if (!isset($this->pluralizer)) { - $this->pluralizer = $this->getGeneratorConfig()->getConfiguredPluralizer(); - } - return $this->pluralizer; - } - - /** - * Returns new or existing stub Peer builder class for this table. - * @return PeerBuilder - */ - public function getStubPeerBuilder() - { - if (!isset($this->stubPeerBuilder)) { - $this->stubPeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'peerstub'); - } - return $this->stubPeerBuilder; - } - - /** - * Returns new or existing Object builder class for this table. - * @return ObjectBuilder - */ - public function getObjectBuilder() - { - if (!isset($this->objectBuilder)) { - $this->objectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'object'); - } - return $this->objectBuilder; - } - - /** - * Returns new or existing stub Object builder class for this table. - * @return ObjectBuilder - */ - public function getStubObjectBuilder() - { - if (!isset($this->stubObjectBuilder)) { - $this->stubObjectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'objectstub'); - } - return $this->stubObjectBuilder; - } - - /** - * Returns new or existing Query builder class for this table. - * @return ObjectBuilder - */ - public function getQueryBuilder() - { - if (!isset($this->queryBuilder)) { - $this->queryBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'query'); - } - return $this->queryBuilder; - } - - /** - * Returns new or existing stub Query builder class for this table. - * @return ObjectBuilder - */ - public function getStubQueryBuilder() - { - if (!isset($this->stubQueryBuilder)) { - $this->stubQueryBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'querystub'); - } - return $this->stubQueryBuilder; - } - - /** - * Returns new or existing Object builder class for this table. - * @return ObjectBuilder - */ - public function getTableMapBuilder() - { - if (!isset($this->tablemapBuilder)) { - $this->tablemapBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'tablemap'); - } - return $this->tablemapBuilder; - } - - /** - * Returns new or existing stub Interface builder class for this table. - * @return ObjectBuilder - */ - public function getInterfaceBuilder() - { - if (!isset($this->interfaceBuilder)) { - $this->interfaceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'interface'); - } - return $this->interfaceBuilder; - } - - /** - * Returns new or existing stub child object builder class for this table. - * @return ObjectBuilder - */ - public function getMultiExtendObjectBuilder() - { - if (!isset($this->multiExtendObjectBuilder)) { - $this->multiExtendObjectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'objectmultiextend'); - } - return $this->multiExtendObjectBuilder; - } - - /** - * Returns new or existing node Object builder class for this table. - * @return ObjectBuilder - */ - public function getNodeBuilder() - { - if (!isset($this->nodeBuilder)) { - $this->nodeBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'node'); - } - return $this->nodeBuilder; - } - - /** - * Returns new or existing node Peer builder class for this table. - * @return PeerBuilder - */ - public function getNodePeerBuilder() - { - if (!isset($this->nodePeerBuilder)) { - $this->nodePeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodepeer'); - } - return $this->nodePeerBuilder; - } - - /** - * Returns new or existing stub node Object builder class for this table. - * @return ObjectBuilder - */ - public function getStubNodeBuilder() - { - if (!isset($this->stubNodeBuilder)) { - $this->stubNodeBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodestub'); - } - return $this->stubNodeBuilder; - } - - /** - * Returns new or existing stub node Peer builder class for this table. - * @return PeerBuilder - */ - public function getStubNodePeerBuilder() - { - if (!isset($this->stubNodePeerBuilder)) { - $this->stubNodePeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodepeerstub'); - } - return $this->stubNodePeerBuilder; - } - - /** - * Returns new or existing nested set object builder class for this table. - * @return ObjectBuilder - */ - public function getNestedSetBuilder() - { - if (!isset($this->nestedSetBuilder)) { - $this->nestedSetBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nestedset'); - } - return $this->nestedSetBuilder; - } - - /** - * Returns new or existing nested set Peer builder class for this table. - * @return PeerBuilder - */ - public function getNestedSetPeerBuilder() - { - if (!isset($this->nestedSetPeerBuilder)) { - $this->nestedSetPeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nestedsetpeer'); - } - return $this->nestedSetPeerBuilder; - } - - /** - * Returns new or existing ddl builder class for this table. - * @return DDLBuilder - */ - public function getDDLBuilder() - { - if (!isset($this->ddlBuilder)) { - $this->ddlBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'ddl'); - } - return $this->ddlBuilder; - } - - /** - * Returns new or existing data sql builder class for this table. - * @return DataSQLBuilder - */ - public function getDataSQLBuilder() - { - if (!isset($this->dataSqlBuilder)) { - $this->dataSqlBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'datasql'); - } - return $this->dataSqlBuilder; - } - - /** - * Convenience method to return a NEW Peer class builder instance. - * - * This is used very frequently from the peer and object builders to get - * a peer builder for a RELATED table. - * - * @param Table $table - * @return PeerBuilder - */ - public function getNewPeerBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'peer'); - } - - /** - * Convenience method to return a NEW Peer stub class builder instance. - * - * This is used from the peer and object builders to get - * a peer builder for a RELATED table. - * - * @param Table $table - * @return PeerBuilder - */ - public function getNewStubPeerBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'peerstub'); - } - - /** - * Convenience method to return a NEW Object class builder instance. - * - * This is used very frequently from the peer and object builders to get - * an object builder for a RELATED table. - * - * @param Table $table - * @return ObjectBuilder - */ - public function getNewObjectBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'object'); - } - - /** - * Convenience method to return a NEW Object stub class builder instance. - * - * This is used from the query builders to get - * an object builder for a RELATED table. - * - * @param Table $table - * @return ObjectBuilder - */ - public function getNewStubObjectBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'objectstub'); - } - - /** - * Convenience method to return a NEW query class builder instance. - * - * This is used from the query builders to get - * a query builder for a RELATED table. - * - * @param Table $table - * @return QueryBuilder - */ - public function getNewQueryBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'query'); - } - - /** - * Convenience method to return a NEW query stub class builder instance. - * - * This is used from the query builders to get - * a query builder for a RELATED table. - * - * @param Table $table - * @return QueryBuilder - */ - public function getNewStubQueryBuilder(Table $table) - { - return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'querystub'); - } - - /** - * Returns new Query Inheritance builder class for this table. - * @return ObjectBuilder - */ - public function getNewQueryInheritanceBuilder($child) - { - $queryInheritanceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'queryinheritance'); - $queryInheritanceBuilder->setChild($child); - return $queryInheritanceBuilder; - } - - /** - * Returns new stub Query Inheritance builder class for this table. - * @return ObjectBuilder - */ - public function getNewStubQueryInheritanceBuilder($child) - { - $stubQueryInheritanceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'queryinheritancestub'); - $stubQueryInheritanceBuilder->setChild($child); - return $stubQueryInheritanceBuilder; - } - - /** - * Gets the GeneratorConfig object. - * - * @return GeneratorConfig - */ - public function getGeneratorConfig() - { - return $this->generatorConfig; - } - - /** - * Get a specific [name transformed] build property. - * - * @param string $name - * @return string - */ - public function getBuildProperty($name) - { - if ($this->getGeneratorConfig()) { - return $this->getGeneratorConfig()->getBuildProperty($name); - } - return null; // just to be explicit - } - - /** - * Sets the GeneratorConfig object. - * - * @param GeneratorConfig $v - */ - public function setGeneratorConfig(GeneratorConfig $v) - { - $this->generatorConfig = $v; - } - - /** - * Sets the table for this builder. - * @param Table $table - */ - public function setTable(Table $table) - { - $this->table = $table; - } - - /** - * Returns the current Table object. - * @return Table - */ - public function getTable() - { - return $this->table; - } - - /** - * Convenience method to returns the Platform class for this table (database). - * @return Platform - */ - public function getPlatform() - { - if ($this->getTable() && $this->getTable()->getDatabase()) { - return $this->getTable()->getDatabase()->getPlatform(); - } - } - - /** - * Convenience method to returns the database for current table. - * @return Database - */ - public function getDatabase() - { - if ($this->getTable()) { - return $this->getTable()->getDatabase(); - } - } - - /** - * Pushes a message onto the stack of warnings. - * @param string $msg The warning message. - */ - protected function warn($msg) - { - $this->warnings[] = $msg; - } - - /** - * Gets array of warning messages. - * @return array string[] - */ - public function getWarnings() - { - return $this->warnings; - } - - /** - * Wraps call to Platform->quoteIdentifier() with a check to see whether quoting is enabled. - * - * All subclasses should call this quoteIdentifier() method rather than calling the Platform - * method directly. This method is used by both DataSQLBuilder and DDLBuilder, and potentially - * in the OM builders also, which is why it is defined in this class. - * - * @param string $text The text to quote. - * @return string Quoted text. - */ - public function quoteIdentifier($text) - { - if (!$this->getBuildProperty('disableIdentifierQuoting')) { - return $this->getPlatform()->quoteIdentifier($text); - } - return $text; - } - - /** - * Returns the name of the current class being built, with a possible prefix. - * @return string - * @see OMBuilder#getClassname() - */ - public function prefixClassname($identifier) - { - return $this->getBuildProperty('classPrefix') . $identifier; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/ClassTools.php b/airtime_mvc/library/propel/generator/lib/builder/om/ClassTools.php deleted file mode 100644 index 5e3b5a5f2..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/ClassTools.php +++ /dev/null @@ -1,120 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.builder.om - */ -class ClassTools -{ - - /** - * Gets just classname, given a dot-path to class. - * @param string $qualifiedName - * @return string - */ - public static function classname($qualifiedName) - { - $pos = strrpos($qualifiedName, '.'); - if ($pos === false) { - return $qualifiedName; // there is no '.' in the qualifed name - } else { - return substr($qualifiedName, $pos + 1); // start just after '.' - } - } - - /** - * Gets the path to be used in include()/require() statement. - * - * Supports multiple function signatures: - * - * (1) getFilePath($dotPathClass); - * (2) getFilePath($dotPathPrefix, $className); - * (3) getFilePath($dotPathPrefix, $className, $extension); - * - * @param string $path dot-path to class or to package prefix. - * @param string $classname class name - * @param string $extension The extension to use on the file. - * @return string The constructed file path. - */ - public static function getFilePath($path, $classname = null, $extension = '.php') - { - $path = strtr(ltrim($path, '.'), '.', '/'); - if ($classname !== null) { - if ($path !== "") { $path .= '/'; } - return $path . $classname . $extension; - } else { - return $path . $extension; - } - } - - /** - * Gets the basePeer path if specified for table/db. - * If not, will return 'propel.util.BasePeer' - * @return string - */ - public static function getBasePeer(Table $table) { - $class = $table->getBasePeer(); - if ($class === null) { - $class = "propel.util.BasePeer"; - } - return $class; - } - - /** - * Gets the baseClass path if specified for table/db. - * If not, will return 'propel.om.BaseObject' - * @return string - */ - public static function getBaseClass(Table $table) { - $class = $table->getBaseClass(); - if ($class === null) { - $class = "propel.om.BaseObject"; - } - return $class; - } - - /** - * Gets the interface path if specified for table. - * If not, will return 'propel.om.Persistent'. - * @return string - */ - public static function getInterface(Table $table) { - $interface = $table->getInterface(); - if ($interface === null && !$table->isReadOnly()) { - $interface = "propel.om.Persistent"; - } - return $interface; - } - - /** - * Gets a list of PHP reserved words. - * - * @return array string[] - */ - public static function getPhpReservedWords() - { - return array( - 'and', 'or', 'xor', 'exception', '__FILE__', '__LINE__', - 'array', 'as', 'break', 'case', 'class', 'const', 'continue', - 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', - 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', - 'eval', 'exit', 'extends', 'for', 'foreach', 'function', 'global', - 'if', 'include', 'include_once', 'isset', 'list', 'new', 'print', 'require', - 'require_once', 'return', 'static', 'switch', 'unset', 'use', 'var', 'while', - '__FUNCTION__', '__CLASS__', '__METHOD__', 'final', 'php_user_filter', 'interface', - 'implements', 'extends', 'public', 'protected', 'private', 'abstract', 'clone', 'try', 'catch', - 'throw', 'this', 'namespace' - ); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryBuilder.php deleted file mode 100644 index 8472c677c..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryBuilder.php +++ /dev/null @@ -1,139 +0,0 @@ -getTable()->getPhpName() . 'Query'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $requiredClassFilePath = $this->getQueryBuilder()->getClassFilePath(); - - $script .=" -require '".$requiredClassFilePath."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $this->declareClassFromBuilder($this->getQueryBuilder()); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - $baseClassname = $this->getQueryBuilder()->getClassname(); - - $script .= " - -/** - * Skeleton subclass for performing query and update operations on the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends $baseClassname { -"; - } - - /** - * Specifies the methods that are added as part of the stub query class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see QueryBuilder::addClassBody() - */ - - protected function addClassBody(&$script) - { - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('extensionQueryFilter', $script, ""); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier = null) - { - return parent::hasBehaviorModifier($hookName, 'QueryBuilderModifier'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifier($hookName, &$script, $tab = " ") - { - return $this->applyBehaviorModifierBase($hookName, 'QueryBuilderModifier', $script, $tab); - } - - /** - * Checks whether any registered behavior content creator on that table exists a contentName - * @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname" - */ - public function getBehaviorContent($contentName) - { - return $this->getBehaviorContentBase($contentName, 'QueryBuilderModifier'); - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php deleted file mode 100644 index 2b8e3f30e..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php +++ /dev/null @@ -1,138 +0,0 @@ -getChild()->getClassName() . 'Query'; - } - - /** - * Set the child object that we're operating on currrently. - * @param $child Inheritance - */ - public function setChild(Inheritance $child) - { - $this->child = $child; - } - - /** - * Returns the child object we're operating on currently. - * @return Inheritance - * @throws BuildException - if child was not set. - */ - public function getChild() - { - if (!$this->child) { - throw new BuildException("The PHP5MultiExtendObjectBuilder needs to be told which child class to build (via setChild() method) before it can build the stub class."); - } - return $this->child; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $requiredClassFilePath = $this->getStubQueryBuilder()->getClassFilePath(); - - $script .=" -require '".$requiredClassFilePath."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseBuilder = $this->getNewQueryInheritanceBuilder($this->getChild()); - $this->declareClassFromBuilder($baseBuilder); - $baseClassname = $baseBuilder->getClassname(); - - $script .= " - -/** - * Skeleton subclass for representing a query for one of the subclasses of the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class " .$this->getClassname() . " extends " . $baseClassname . " { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // MultiExtensionQueryBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/OMBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/OMBuilder.php deleted file mode 100644 index c78334708..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/OMBuilder.php +++ /dev/null @@ -1,526 +0,0 @@ - - * @package propel.generator.builder.om - */ -abstract class OMBuilder extends DataModelBuilder -{ - /** - * Declared fully qualified classnames, to build the 'namespace' statements - * according to this table's namespace. - * @var array - */ - protected $declaredClasses = array(); - - /** - * Builds the PHP source for current class and returns it as a string. - * - * This is the main entry point and defines a basic structure that classes should follow. - * In most cases this method will not need to be overridden by subclasses. This method - * does assume that the output language is PHP code, so it will need to be overridden if - * this is not the case. - * - * @return string The resulting PHP sourcecode. - */ - public function build() - { - $this->validateModel(); - - $script = ''; - if ($this->isAddIncludes()) { - $this->addIncludes($script); - } - $this->addClassOpen($script); - $this->addClassBody($script); - $this->addClassClose($script); - - if($useStatements = $this->getUseStatements($ignoredNamespace = $this->getNamespace())) { - $script = $useStatements . $script; - } - if($namespaceStatement = $this->getNamespaceStatement()) { - $script = $namespaceStatement . $script; - } - //if($this->getTable()->getName() == 'book_club_list') die($ignoredNamespace); - - return "<" . "?php - -" . $script; - } - - /** - * Validates the current table to make sure that it won't - * result in generated code that will not parse. - * - * This method may emit warnings for code which may cause problems - * and will throw exceptions for errors that will definitely cause - * problems. - */ - protected function validateModel() - { - // Validation is currently only implemented in the subclasses. - } - - /** - * Creates a $obj = new Book(); code snippet. Can be used by frameworks, for instance, to - * extend this behavior, e.g. initialize the object after creating the instance or so. - * - * @return string Some code - */ - public function buildObjectInstanceCreationCode($objName, $clsName) - { - return "$objName = new $clsName();"; - } - - /** - * Returns the qualified (prefixed) classname that is being built by the current class. - * This method must be implemented by child classes. - * @return string - */ - abstract public function getUnprefixedClassname(); - - /** - * Returns the prefixed classname that is being built by the current class. - * @return string - * @see DataModelBuilder#prefixClassname() - */ - public function getClassname() - { - return $this->prefixClassname($this->getUnprefixedClassname()); - } - - /** - * Returns the namespaced classname if there is a namespace, and the raw classname otherwise - * @return string - */ - public function getFullyQualifiedClassname() - { - if ($namespace = $this->getNamespace()) { - return $namespace . '\\' . $this->getClassname(); - } else { - return $this->getClassname(); - } - } - - /** - * Gets the dot-path representation of current class being built. - * @return string - */ - public function getClasspath() - { - if ($this->getPackage()) { - $path = $this->getPackage() . '.' . $this->getClassname(); - } else { - $path = $this->getClassname(); - } - return $path; - } - - /** - * Gets the full path to the file for the current class. - * @return string - */ - public function getClassFilePath() - { - return ClassTools::getFilePath($this->getPackage(), $this->getClassname()); - } - - /** - * Gets package name for this table. - * This is overridden by child classes that have different packages. - * @return string - */ - public function getPackage() - { - $pkg = ($this->getTable()->getPackage() ? $this->getTable()->getPackage() : $this->getDatabase()->getPackage()); - if (!$pkg) { - $pkg = $this->getBuildProperty('targetPackage'); - } - return $pkg; - } - - /** - * Returns filesystem path for current package. - * @return string - */ - public function getPackagePath() - { - return strtr($this->getPackage(), '.', '/'); - } - - /** - * Return the user-defined namespace for this table, - * or the database namespace otherwise. - * - * @return string - */ - public function getNamespace() - { - return $this->getTable()->getNamespace(); - } - - public function declareClassNamespace($class, $namespace = '') - { - if (isset($this->declaredClasses[$namespace]) - && in_array($class, $this->declaredClasses[$namespace])) { - return; - } - $this->declaredClasses[$namespace][] = $class; - } - - public function declareClass($fullyQualifiedClassName) - { - $fullyQualifiedClassName = trim($fullyQualifiedClassName, '\\'); - if (($pos = strrpos($fullyQualifiedClassName, '\\')) !== false) { - $this->declareClassNamespace(substr($fullyQualifiedClassName, $pos + 1), substr($fullyQualifiedClassName, 0, $pos)); - } else { - // root namespace - $this->declareClassNamespace($fullyQualifiedClassName); - } - } - - public function declareClassFromBuilder($builder) - { - $this->declareClassNamespace($builder->getClassname(), $builder->getNamespace()); - } - - public function declareClasses() - { - $args = func_get_args(); - foreach ($args as $class) { - $this->declareClass($class); - } - } - - public function getDeclaredClasses($namespace = null) - { - if (null !== $namespace && isset($this->declaredClasses[$namespace])) { - return $this->declaredClasses[$namespace]; - } else { - return $this->declaredClasses; - } - } - - public function getNamespaceStatement() - { - $namespace = $this->getNamespace(); - if ($namespace != '') { - return sprintf("namespace %s; - -", $namespace); - } - } - - public function getUseStatements($ignoredNamespace = null) - { - $declaredClasses = $this->declaredClasses; - unset($declaredClasses[$ignoredNamespace]); - ksort($declaredClasses); - foreach ($declaredClasses as $namespace => $classes) { - sort($classes); - foreach ($classes as $class) { - $script .= sprintf("use %s\\%s; -", $namespace, $class); - } - } - return $script; - } - - /** - * Shortcut method to return the [stub] peer classname for current table. - * This is the classname that is used whenever object or peer classes want - * to invoke methods of the peer classes. - * @return string (e.g. 'MyPeer') - * @see StubPeerBuilder::getClassname() - */ - public function getPeerClassname() { - return $this->getStubPeerBuilder()->getClassname(); - } - - /** - * Shortcut method to return the [stub] query classname for current table. - * This is the classname that is used whenever object or peer classes want - * to invoke methods of the query classes. - * @return string (e.g. 'Myquery') - * @see StubQueryBuilder::getClassname() - */ - public function getQueryClassname() { - return $this->getStubQueryBuilder()->getClassname(); - } - - /** - * Returns the object classname for current table. - * This is the classname that is used whenever object or peer classes want - * to invoke methods of the object classes. - * @return string (e.g. 'My') - * @see StubPeerBuilder::getClassname() - */ - public function getObjectClassname() { - return $this->getStubObjectBuilder()->getClassname(); - } - - /** - * Get the column constant name (e.g. PeerName::COLUMN_NAME). - * - * @param Column $col The column we need a name for. - * @param string $classname The Peer classname to use. - * - * @return string If $classname is provided, then will return $classname::COLUMN_NAME; if not, then the peername is looked up for current table to yield $currTablePeer::COLUMN_NAME. - */ - public function getColumnConstant($col, $classname = null) - { - if ($col === null) { - $e = new Exception("No col specified."); - print $e; - throw $e; - } - if ($classname === null) { - return $this->getBuildProperty('classPrefix') . $col->getConstantName(); - } - // was it overridden in schema.xml ? - if ($col->getPeerName()) { - $const = strtoupper($col->getPeerName()); - } else { - $const = strtoupper($col->getName()); - } - return $classname.'::'.$const; - } - - /** - * Gets the basePeer path if specified for table/db. - * If not, will return 'propel.util.BasePeer' - * @return string - */ - public function getBasePeer(Table $table) { - $class = $table->getBasePeer(); - if ($class === null) { - $class = "propel.util.BasePeer"; - } - return $class; - } - - /** - * Convenience method to get the foreign Table object for an fkey. - * @deprecated use ForeignKey::getForeignTable() instead - * @return Table - */ - protected function getForeignTable(ForeignKey $fk) - { - return $this->getTable()->getDatabase()->getTable($fk->getForeignTableName()); - } - - /** - * Convenience method to get the default Join Type for a relation. - * If the key is required, an INNER JOIN will be returned, else a LEFT JOIN will be suggested, - * unless the schema is provided with the DefaultJoin attribute, which overrules the default Join Type - * - * @param ForeignKey $fk - * @return string - */ - protected function getJoinType(ForeignKey $fk) - { - return $fk->getDefaultJoin() ? - "'".$fk->getDefaultJoin()."'" : - ($fk->isLocalColumnsRequired() ? 'Criteria::INNER_JOIN' : 'Criteria::LEFT_JOIN'); - } - - /** - * Gets the PHP method name affix to be used for fkeys for the current table (not referrers to this table). - * - * The difference between this method and the getRefFKPhpNameAffix() method is that in this method the - * classname in the affix is the foreign table classname. - * - * @param ForeignKey $fk The local FK that we need a name for. - * @param boolean $plural Whether the php name should be plural (e.g. initRelatedObjs() vs. addRelatedObj() - * @return string - */ - public function getFKPhpNameAffix(ForeignKey $fk, $plural = false) - { - if ($fk->getPhpName()) { - if ($plural) { - return $this->getPluralizer()->getPluralForm($fk->getPhpName()); - } else { - return $fk->getPhpName(); - } - } else { - $className = $fk->getForeignTable()->getPhpName(); - if ($plural) { - $className = $this->getPluralizer()->getPluralForm($className); - } - return $className . $this->getRelatedBySuffix($fk); - } - } - - /** - * Gets the "RelatedBy*" suffix (if needed) that is attached to method and variable names. - * - * The related by suffix is based on the local columns of the foreign key. If there is more than - * one column in a table that points to the same foreign table, then a 'RelatedByLocalColName' suffix - * will be appended. - * - * @return string - */ - protected static function getRelatedBySuffix(ForeignKey $fk) - { - $relCol = ''; - foreach ($fk->getLocalForeignMapping() as $localColumnName => $foreignColumnName) { - $localTable = $fk->getTable(); - $localColumn = $localTable->getColumn($localColumnName); - if (!$localColumn) { - throw new Exception("Could not fetch column: $columnName in table " . $localTable->getName()); - } - if (count($localTable->getForeignKeysReferencingTable($fk->getForeignTableName())) > 1 - || count($fk->getForeignTable()->getForeignKeysReferencingTable($fk->getTableName())) > 0 - || $fk->getForeignTableName() == $fk->getTableName()) { - // self referential foreign key, or several foreign keys to the same table, or cross-reference fkey - $relCol .= $localColumn->getPhpName(); - } - } - - if ($relCol != '') { - $relCol = 'RelatedBy' . $relCol; - } - - return $relCol; - } - - /** - * Gets the PHP method name affix to be used for referencing foreign key methods and variable names (e.g. set????(), $coll???). - * - * The difference between this method and the getFKPhpNameAffix() method is that in this method the - * classname in the affix is the classname of the local fkey table. - * - * @param ForeignKey $fk The referrer FK that we need a name for. - * @param boolean $plural Whether the php name should be plural (e.g. initRelatedObjs() vs. addRelatedObj() - * @return string - */ - public function getRefFKPhpNameAffix(ForeignKey $fk, $plural = false) - { - if ($fk->getRefPhpName()) { - if ($plural) { - return $this->getPluralizer()->getPluralForm($fk->getRefPhpName()); - } else { - return $fk->getRefPhpName(); - } - } else { - $className = $fk->getTable()->getPhpName(); - if ($plural) { - $className = $this->getPluralizer()->getPluralForm($className); - } - return $className . $this->getRefRelatedBySuffix($fk); - } - } - - protected static function getRefRelatedBySuffix(ForeignKey $fk) - { - $relCol = ''; - foreach ($fk->getLocalForeignMapping() as $localColumnName => $foreignColumnName) { - $localTable = $fk->getTable(); - $localColumn = $localTable->getColumn($localColumnName); - if (!$localColumn) { - throw new Exception("Could not fetch column: $columnName in table " . $localTable->getName()); - } - $foreignKeysToForeignTable = $localTable->getForeignKeysReferencingTable($fk->getForeignTableName()); - if ($fk->getForeignTableName() == $fk->getTableName()) { - // self referential foreign key - $relCol .= $fk->getForeignTable()->getColumn($foreignColumnName)->getPhpName(); - if (count($foreignKeysToForeignTable) > 1) { - // several self-referential foreign keys - $relCol .= array_search($fk, $foreignKeysToForeignTable); - } - } elseif (count($foreignKeysToForeignTable) > 1 || count($fk->getForeignTable()->getForeignKeysReferencingTable($fk->getTableName())) > 0) { - // several foreign keys to the same table, or symmetrical foreign key in foreign table - $relCol .= $localColumn->getPhpName(); - } - } - - if ($relCol != '') { - $relCol = 'RelatedBy' . $relCol; - } - - return $relCol; - } - - /** - * Whether to add the include statements. - * This is based on the build property propel.addIncludes - */ - protected function isAddIncludes() - { - return $this->getBuildProperty('addIncludes'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string $modifier The name of the modifier object providing the method in the behavior - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier) - { - $modifierGetter = 'get' . $modifier; - foreach ($this->getTable()->getBehaviors() as $behavior) { - if(method_exists($behavior->$modifierGetter(), $hookName)) { - return true; - } - } - return false; - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string $modifier The name of the modifier object providing the method in the behavior - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifierBase($hookName, $modifier, &$script, $tab = " ") - { - $modifierGetter = 'get' . $modifier; - foreach ($this->getTable()->getBehaviors() as $behavior) { - $modifier = $behavior->$modifierGetter(); - if(method_exists($modifier, $hookName)) { - if (strpos($hookName, 'Filter') !== false) { - // filter hook: the script string will be modified by the behavior - $modifier->$hookName($script, $this); - } else { - // regular hook: the behavior returns a string to append to the script string - $script .= "\n" . $tab . '// ' . $behavior->getName() . " behavior\n"; - $script .= preg_replace('/^/m', $tab, $modifier->$hookName($this)); - } - } - } - } - - /** - * Checks whether any registered behavior content creator on that table exists a contentName - * @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname" - * @param string $modifier The name of the modifier object providing the method in the behavior - */ - public function getBehaviorContentBase($contentName, $modifier) - { - $modifierGetter = 'get' . $modifier; - foreach ($this->getTable()->getBehaviors() as $behavior) { - $modifier = $behavior->$modifierGetter(); - if(method_exists($modifier, $contentName)) { - return $modifier->$contentName($this); - } - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/ObjectBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/ObjectBuilder.php deleted file mode 100644 index a8ed43bfd..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/ObjectBuilder.php +++ /dev/null @@ -1,186 +0,0 @@ - - * @package propel.generator.builder.om - */ -abstract class ObjectBuilder extends OMBuilder -{ - - /** - * Constructs a new PeerBuilder subclass. - */ - public function __construct(Table $table) { - parent::__construct($table); - } - - /** - * This method adds the contents of the generated class to the script. - * - * This method is abstract and should be overridden by the subclasses. - * - * Hint: Override this method in your subclass if you want to reorganize or - * drastically change the contents of the generated peer class. - * - * @param string &$script The script will be modified in this method. - */ - abstract protected function addClassBody(&$script); - - /** - * Adds the getter methods for the column values. - * This is here because it is probably generic enough to apply to templates being generated - * in different langauges (e.g. PHP4 and PHP5). - * @param string &$script The script will be modified in this method. - */ - protected function addColumnAccessorMethods(&$script) - { - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - - // if they're not using the DateTime class than we will generate "compatibility" accessor method - if ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) { - $this->addTemporalAccessor($script, $col); - } else { - $this->addDefaultAccessor($script, $col); - } - - if ($col->isLazyLoad()) { - $this->addLazyLoader($script, $col); - } - } - } - - /** - * Adds the mutator (setter) methods for setting column values. - * This is here because it is probably generic enough to apply to templates being generated - * in different langauges (e.g. PHP4 and PHP5). - * @param string &$script The script will be modified in this method. - */ - protected function addColumnMutatorMethods(&$script) - { - foreach ($this->getTable()->getColumns() as $col) { - - if ($col->isLobType()) { - $this->addLobMutator($script, $col); - } elseif ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) { - $this->addTemporalMutator($script, $col); - } else { - $this->addDefaultMutator($script, $col); - } - } - } - - - /** - * Gets the baseClass path if specified for table/db. - * If not, will return 'propel.om.BaseObject' - * @return string - */ - protected function getBaseClass() { - $class = $this->getTable()->getBaseClass(); - if ($class === null) { - $class = "propel.om.BaseObject"; - } - return $class; - } - - /** - * Gets the interface path if specified for current table. - * If not, will return 'propel.om.Persistent'. - * @return string - */ - protected function getInterface() { - $interface = $this->getTable()->getInterface(); - if ($interface === null && !$this->getTable()->isReadOnly()) { - $interface = "propel.om.Persistent"; - } - return $interface; - } - - /** - * Whether to add the generic mutator methods (setByName(), setByPosition(), fromArray()). - * This is based on the build property propel.addGenericMutators, and also whether the - * table is read-only or an alias. - */ - protected function isAddGenericMutators() - { - $table = $this->getTable(); - return (!$table->isAlias() && $this->getBuildProperty('addGenericMutators') && !$table->isReadOnly()); - } - - /** - * Whether to add the generic accessor methods (getByName(), getByPosition(), toArray()). - * This is based on the build property propel.addGenericAccessors, and also whether the - * table is an alias. - */ - protected function isAddGenericAccessors() - { - $table = $this->getTable(); - return (!$table->isAlias() && $this->getBuildProperty('addGenericAccessors')); - } - - /** - * Whether to add the validate() method. - * This is based on the build property propel.addValidateMethod - */ - protected function isAddValidateMethod() - { - return $this->getBuildProperty('addValidateMethod'); - } - - protected function hasDefaultValues() - { - foreach ($this->getTable()->getColumns() as $col) { - if($col->getDefaultValue() !== null) return true; - } - return false; - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier = null) - { - return parent::hasBehaviorModifier($hookName, 'ObjectBuilderModifier'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifier($hookName, &$script, $tab = " ") - { - return $this->applyBehaviorModifierBase($hookName, 'ObjectBuilderModifier', $script, $tab); - } - - /** - * Checks whether any registered behavior content creator on that table exists a contentName - * @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname" - */ - public function getBehaviorContent($contentName) - { - return $this->getBehaviorContentBase($contentName, 'ObjectBuilderModifier'); - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php deleted file mode 100644 index 8b1bdae65..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php +++ /dev/null @@ -1,111 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5ExtensionNodeBuilder extends ObjectBuilder -{ - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getTable()->getPhpName() . 'Node'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $script .= " -require '".$this->getNodeBuilder()->getClassFilePath()."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseClassname = $this->getNodeBuilder()->getClassname(); - - $script .= " - -/** - * Skeleton subclass for representing a node from the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends $baseClassname { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - // there is no class body - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // PHP5ExtensionObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php deleted file mode 100644 index 8f5f16cf4..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php +++ /dev/null @@ -1,112 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5ExtensionNodePeerBuilder extends PeerBuilder -{ - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getStubNodeBuilder()->getClassname() . 'Peer'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $script .=" -require '".$this->getNodePeerBuilder()->getClassFilePath()."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseClassname = $this->getNodePeerBuilder()->getClassname(); - - $script .= " - -/** - * Skeleton subclass for performing query and update operations on nodes of the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends $baseClassname { -"; - } - - /** - * Specifies the methods that are added as part of the stub peer class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - - protected function addClassBody(&$script) - { - // there is no class body - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // PHP5ExtensionPeerBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php deleted file mode 100644 index b88e1df0d..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php +++ /dev/null @@ -1,133 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5ExtensionObjectBuilder extends ObjectBuilder -{ - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getTable()->getPhpName(); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - switch($this->getTable()->treeMode()) { - case 'NestedSet': - $requiredClassFilePath = $this->getNestedSetBuilder()->getClassFilePath(); - break; - - case 'MaterializedPath': - case 'AdjacencyList': - default: - $requiredClassFilePath = $this->getObjectBuilder()->getClassFilePath(); - break; - } - - $script .=" -require '".$requiredClassFilePath."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $this->declareClassFromBuilder($this->getObjectBuilder()); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - switch($table->treeMode()) { - case 'NestedSet': - $baseClassname = $this->getNestedSetBuilder()->getClassname(); - break; - - case 'MaterializedPath': - case "AdjacencyList": - default: - $baseClassname = $this->getObjectBuilder()->getClassname(); - break; - } - - $script .= " - -/** - * Skeleton subclass for representing a row from the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -".($table->isAbstract() ? "abstract " : "")."class ".$this->getClassname()." extends $baseClassname { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('extensionObjectFilter', $script, ""); - } - -} // PHP5ExtensionObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php deleted file mode 100644 index ef22ae4ca..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php +++ /dev/null @@ -1,136 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5ExtensionPeerBuilder extends PeerBuilder -{ - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getStubObjectBuilder()->getUnprefixedClassname() . 'Peer'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - switch($this->getTable()->treeMode()) { - case 'NestedSet': - $requiredClassFilePath = $this->getNestedSetPeerBuilder()->getClassFilePath(); - break; - - case 'MaterializedPath': - case 'AdjacencyList': - default: - $requiredClassFilePath = $this->getPeerBuilder()->getClassFilePath(); - break; - } - - $script .=" -require '".$requiredClassFilePath."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $this->declareClassFromBuilder($this->getPeerBuilder()); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - switch($table->treeMode()) { - case 'NestedSet': - $baseClassname = $this->getNestedSetPeerBuilder()->getClassname(); - break; - - case 'MaterializedPath': - case 'AdjacencyList': - default: - $baseClassname = $this->getPeerBuilder()->getClassname(); - break; - } - - $script .= " - -/** - * Skeleton subclass for performing query and update operations on the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends $baseClassname { -"; - } - - /** - * Specifies the methods that are added as part of the stub peer class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - - protected function addClassBody(&$script) - { - // there is no class body - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('extensionPeerFilter', $script, ""); - } - - -} // PHP5ExtensionPeerBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5InterfaceBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5InterfaceBuilder.php deleted file mode 100644 index ba6f094a2..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5InterfaceBuilder.php +++ /dev/null @@ -1,108 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5InterfaceBuilder extends ObjectBuilder -{ - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return ClassTools::classname($this->getInterface()); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseClassname = $this->getObjectBuilder()->getClassname(); - - $script .= " -/** - * This is an interface that should be filled with the public api of the $tableName objects. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional method declarations to this interface to meet the - * application requirements. This interface will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -interface ".$this->getClassname()." { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - // there is no class body - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // PHP5ExtensionObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php deleted file mode 100644 index 5ac7eae06..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php +++ /dev/null @@ -1,196 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5MultiExtendObjectBuilder extends ObjectBuilder -{ - - /** - * The current child "object" we are operating on. - */ - private $child; - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getChild()->getClassname(); - } - - /** - * Override method to return child package, if specified. - * @return string - */ - public function getPackage() - { - return ($this->child->getPackage() ? $this->child->getPackage() : parent::getPackage()); - } - - /** - * Set the child object that we're operating on currrently. - * @param $child Inheritance - */ - public function setChild(Inheritance $child) - { - $this->child = $child; - } - - /** - * Returns the child object we're operating on currently. - * @return Inheritance - * @throws BuildException - if child was not set. - */ - public function getChild() - { - if (!$this->child) { - throw new BuildException("The PHP5MultiExtendObjectBuilder needs to be told which child class to build (via setChild() method) before it can build the stub class."); - } - return $this->child; - } - - /** - * Returns classpath to parent class. - * @return string - */ - protected function getParentClasspath() - { - if ($this->getChild()->getAncestor()) { - return $this->getChild()->getAncestor(); - } else { - return $this->getObjectBuilder()->getClasspath(); - } - } - - /** - * Returns classname of parent class. - * @return string - */ - protected function getParentClassname() - { - return ClassTools::classname($this->getParentClasspath()); - } - - /** - * Gets the file path to the parent class. - * @return string - */ - protected function getParentClassFilePath() - { - return ClassTools::getFilePath($this->getParentClasspath()); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - if ($this->getChild()->getAncestor()) { - $this->declareClassFromBuilder($this->getNewStubObjectBuilder($this->getDatabase()->getTableByPhpName($this->getChild()->getAncestor()))); - } else { - $this->declareClassFromBuilder($this->getObjectBuilder()); - } - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseClassname = $this->getObjectBuilder()->getClassname(); - - $script .= " - -/** - * Skeleton subclass for representing a row from one of the subclasses of the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends ".$this->getParentClassname()." { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $this->declareClassFromBuilder($this->getStubPeerBuilder()); - $child = $this->getChild(); - $col = $child->getColumn(); - $cfc = $col->getPhpName(); - - $const = "CLASSKEY_".strtoupper($child->getKey()); - - $script .= " - /** - * Constructs a new ".$this->getChild()->getClassname()." class, setting the ".$col->getName()." column to ".$this->getPeerClassname()."::$const. - */ - public function __construct() - {"; - $script .= " - parent::__construct(); - \$this->set$cfc(".$this->getPeerClassname()."::CLASSKEY_".strtoupper($child->getKey())."); - } -"; - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // PHP5ExtensionObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetBuilder.php deleted file mode 100644 index d7e0bb8fc..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetBuilder.php +++ /dev/null @@ -1,1136 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5NestedSetBuilder extends ObjectBuilder -{ - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubObjectBuilder()->getUnprefixedClassname() . 'NestedSet'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $script .=" -require '".$this->getObjectBuilder()->getClassFilePath()."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $script .= " -/** - * Base class that represents a row from the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * @deprecated Since Propel 1.5. Use the nested_set behavior instead of the NestedSet treeMode - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." extends ".$this->getObjectBuilder()->getClassname()." implements NodeObject { -"; - } - - /** - * Specifies the methods that are added as part of the basic OM class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $table = $this->getTable(); - - $this->addAttributes($script); - - $this->addGetIterator($script); - - $this->addSave($script); - $this->addDelete($script); - - $this->addMakeRoot($script); - - $this->addGetLevel($script); - $this->addGetPath($script); - - $this->addGetNumberOfChildren($script); - $this->addGetNumberOfDescendants($script); - - $this->addGetChildren($script); - $this->addGetDescendants($script); - - $this->addSetLevel($script); - - $this->addSetChildren($script); - $this->addSetParentNode($script); - $this->addSetPrevSibling($script); - $this->addSetNextSibling($script); - - $this->addIsRoot($script); - $this->addIsLeaf($script); - $this->addIsEqualTo($script); - - $this->addHasParent($script); - $this->addHasChildren($script); - $this->addHasPrevSibling($script); - $this->addHasNextSibling($script); - - $this->addRetrieveParent($script); - $this->addRetrieveFirstChild($script); - $this->addRetrieveLastChild($script); - $this->addRetrievePrevSibling($script); - $this->addRetrieveNextSibling($script); - - $this->addInsertAsFirstChildOf($script); - $this->addInsertAsLastChildOf($script); - - $this->addInsertAsPrevSiblingOf($script); - $this->addInsertAsNextSiblingOf($script); - - $this->addMoveToFirstChildOf($script); - $this->addMoveToLastChildOf($script); - - $this->addMoveToPrevSiblingOf($script); - $this->addMoveToNextSiblingOf($script); - - $this->addInsertAsParentOf($script); - - $this->addGetLeft($script); - $this->addGetRight($script); - $this->addGetScopeId($script); - - $this->addSetLeft($script); - $this->addSetRight($script); - $this->addSetScopeId($script); - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - - - /** - * Adds class attributes. - * @param string &$script The script will be modified in this method. - */ - protected function addAttributes(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $script .= " - /** - * Store level of node - * @var int - */ - protected \$level = null; - - /** - * Store if node has prev sibling - * @var bool - */ - protected \$hasPrevSibling = null; - - /** - * Store node if has prev sibling - * @var $objectClassName - */ - protected \$prevSibling = null; - - /** - * Store if node has next sibling - * @var bool - */ - protected \$hasNextSibling = null; - - /** - * Store node if has next sibling - * @var $objectClassName - */ - protected \$nextSibling = null; - - /** - * Store if node has parent node - * @var bool - */ - protected \$hasParentNode = null; - - /** - * The parent node for this node. - * @var $objectClassName - */ - protected \$parentNode = null; - - /** - * Store children of the node - * @var array - */ - protected \$_children = null; -"; - } - - protected function addGetIterator(&$script) - { - $script .= " - /** - * Returns a pre-order iterator for this node and its children. - * - * @return NodeIterator - */ - public function getIterator() - { - return new NestedSetRecursiveIterator(\$this); - } -"; - } - - protected function addSave(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Saves modified object data to the datastore. - * If object is saved without left/right values, set them as undefined (0) - * - * @param PropelPDO Connection to use. - * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. - * May be unreliable with parent/children/brother changes - * @throws PropelException - */ - public function save(PropelPDO \$con = null) - { - \$left = \$this->getLeftValue(); - \$right = \$this->getRightValue(); - if (empty(\$left) || empty(\$right)) { - \$root = $peerClassname::retrieveRoot(\$this->getScopeIdValue(), \$con); - $peerClassname::insertAsLastChildOf(\$this, \$root, \$con); - } - - return parent::save(\$con); - } -"; - } - - protected function addDelete(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Removes this object and all descendants from datastore. - * - * @param PropelPDO Connection to use. - * @return void - * @throws PropelException - */ - public function delete(PropelPDO \$con = null) - { - // delete node first - parent::delete(\$con); - - // delete descendants and then shift tree - $peerClassname::deleteDescendants(\$this, \$con); - } -"; - } - - protected function addMakeRoot(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Sets node properties to make it a root node. - * - * @return $objectClassName The current object (for fluent API support) - * @throws PropelException - */ - public function makeRoot() - { - $peerClassname::createRoot(\$this); - return \$this; - } -"; - } - - protected function addGetLevel(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets the level if set, otherwise calculates this and returns it - * - * @param PropelPDO Connection to use. - * @return int - */ - public function getLevel(PropelPDO \$con = null) - { - if (null === \$this->level) { - \$this->level = $peerClassname::getLevel(\$this, \$con); - } - return \$this->level; - } -"; - } - - protected function addSetLevel(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $script .= " - /** - * Sets the level of the node in the tree - * - * @param int \$v new value - * @return $objectClassName The current object (for fluent API support) - */ - public function setLevel(\$level) - { - \$this->level = \$level; - return \$this; - } -"; - } - - protected function addSetChildren(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $script .= " - /** - * Sets the children array of the node in the tree - * - * @param array of $objectClassName \$children array of Propel node object - * @return $objectClassName The current object (for fluent API support) - */ - public function setChildren(array \$children) - { - \$this->_children = \$children; - return \$this; - } -"; - } - - protected function addSetParentNode(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Sets the parentNode of the node in the tree - * - * @param $objectClassName \$parent Propel node object - * @return $objectClassName The current object (for fluent API support) - */ - public function setParentNode(NodeObject \$parent = null) - { - \$this->parentNode = (true === (\$this->hasParentNode = $peerClassname::isValid(\$parent))) ? \$parent : null; - return \$this; - } -"; - } - - protected function addSetPrevSibling(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Sets the previous sibling of the node in the tree - * - * @param $objectClassName \$node Propel node object - * @return $objectClassName The current object (for fluent API support) - */ - public function setPrevSibling(NodeObject \$node = null) - { - \$this->prevSibling = \$node; - \$this->hasPrevSibling = $peerClassname::isValid(\$node); - return \$this; - } -"; - } - - protected function addSetNextSibling(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Sets the next sibling of the node in the tree - * - * @param $objectClassName \$node Propel node object - * @return $objectClassName The current object (for fluent API support) - */ - public function setNextSibling(NodeObject \$node = null) - { - \$this->nextSibling = \$node; - \$this->hasNextSibling = $peerClassname::isValid(\$node); - return \$this; - } -"; - } - - protected function addGetPath(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Get the path to the node in the tree - * - * @param PropelPDO Connection to use. - * @return array - */ - public function getPath(PropelPDO \$con = null) - { - return $peerClassname::getPath(\$this, \$con); - } -"; - } - - protected function addGetNumberOfChildren(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets the number of children for the node (direct descendants) - * - * @param PropelPDO Connection to use. - * @return int - */ - public function getNumberOfChildren(PropelPDO \$con = null) - { - return $peerClassname::getNumberOfChildren(\$this, \$con); - } -"; - } - - protected function addGetNumberOfDescendants(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets the total number of descendants for the node - * - * @param PropelPDO Connection to use. - * @return int - */ - public function getNumberOfDescendants(PropelPDO \$con = null) - { - return $peerClassname::getNumberOfDescendants(\$this, \$con); - } -"; - } - - protected function addGetChildren(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets the children for the node - * - * @param PropelPDO Connection to use. - * @return array - */ - public function getChildren(PropelPDO \$con = null) - { - \$this->getLevel(); - - if (is_array(\$this->_children)) { - return \$this->_children; - } - - return $peerClassname::retrieveChildren(\$this, \$con); - } -"; - } - - protected function addGetDescendants(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets the descendants for the node - * - * @param PropelPDO Connection to use. - * @return array - */ - public function getDescendants(PropelPDO \$con = null) - { - \$this->getLevel(); - - return $peerClassname::retrieveDescendants(\$this, \$con); - } -"; - } - - protected function addIsRoot(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Returns true if node is the root node of the tree. - * - * @return bool - */ - public function isRoot() - { - return $peerClassname::isRoot(\$this); - } -"; - } - - protected function addIsLeaf(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Return true if the node is a leaf node - * - * @return bool - */ - public function isLeaf() - { - return $peerClassname::isLeaf(\$this); - } -"; - } - - protected function addIsEqualTo(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if object is equal to \$node - * - * @param object \$node Propel object for node to compare to - * @return bool - */ - public function isEqualTo(NodeObject \$node) - { - return $peerClassname::isEqualTo(\$this, \$node); - } -"; - } - - protected function addHasParent(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if object has an ancestor - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public function hasParent(PropelPDO \$con = null) - { - if (null === \$this->hasParentNode) { - $peerClassname::hasParent(\$this, \$con); - } - return \$this->hasParentNode; - } -"; - } - - protected function addHasChildren(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Determines if the node has children / descendants - * - * @return bool - */ - public function hasChildren() - { - return $peerClassname::hasChildren(\$this); - } -"; - } - - protected function addHasPrevSibling(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Determines if the node has previous sibling - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public function hasPrevSibling(PropelPDO \$con = null) - { - if (null === \$this->hasPrevSibling) { - $peerClassname::hasPrevSibling(\$this, \$con); - } - return \$this->hasPrevSibling; - } -"; - } - - protected function addHasNextSibling(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Determines if the node has next sibling - * - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public function hasNextSibling(PropelPDO \$con = null) - { - if (null === \$this->hasNextSibling) { - $peerClassname::hasNextSibling(\$this, \$con); - } - return \$this->hasNextSibling; - } -"; - } - - protected function addRetrieveParent(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets ancestor for the given node if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveParent(PropelPDO \$con = null) - { - if (null === \$this->hasParentNode) { - \$this->parentNode = $peerClassname::retrieveParent(\$this, \$con); - \$this->hasParentNode = $peerClassname::isValid(\$this->parentNode); - } - return \$this->parentNode; - } -"; - } - - protected function addRetrieveFirstChild(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets first child if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveFirstChild(PropelPDO \$con = null) - { - if (\$this->hasChildren(\$con)) { - if (is_array(\$this->_children)) { - return \$this->_children[0]; - } - - return $peerClassname::retrieveFirstChild(\$this, \$con); - } - return false; - } -"; - } - - protected function addRetrieveLastChild(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets last child if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveLastChild(PropelPDO \$con = null) - { - if (\$this->hasChildren(\$con)) { - if (is_array(\$this->_children)) { - \$last = count(\$this->_children) - 1; - return \$this->_children[\$last]; - } - - return $peerClassname::retrieveLastChild(\$this, \$con); - } - return false; - } -"; - } - - protected function addRetrievePrevSibling(&$script) - { - $script .= " - /** - * Gets prev sibling for the given node if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrievePrevSibling(PropelPDO \$con = null) - { - if (\$this->hasPrevSibling(\$con)) { - return \$this->prevSibling; - } - return \$this->hasPrevSibling; - } -"; - } - - protected function addRetrieveNextSibling(&$script) - { - $script .= " - /** - * Gets next sibling for the given node if it exists - * - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveNextSibling(PropelPDO \$con = null) - { - if (\$this->hasNextSibling(\$con)) { - return \$this->nextSibling; - } - return \$this->hasNextSibling; - } -"; - } - - protected function addInsertAsFirstChildOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts as first child of given destination node \$parent - * - * @param $objectClassName \$parent Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - * @throws PropelException - if this object already exists - */ - public function insertAsFirstChildOf(NodeObject \$parent, PropelPDO \$con = null) - { - if (!\$this->isNew()) - { - throw new PropelException(\"$objectClassName must be new.\"); - } - $peerClassname::insertAsFirstChildOf(\$this, \$parent, \$con); - return \$this; - } -"; - } - - protected function addInsertAsLastChildOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts as last child of given destination node \$parent - * - * @param $objectClassName \$parent Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - * @throws PropelException - if this object already exists - */ - public function insertAsLastChildOf(NodeObject \$parent, PropelPDO \$con = null) - { - if (!\$this->isNew()) - { - throw new PropelException(\"$objectClassName must be new.\"); - } - $peerClassname::insertAsLastChildOf(\$this, \$parent, \$con); - return \$this; - } -"; - } - - protected function addInsertAsPrevSiblingOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$node as previous sibling to given destination node \$dest - * - * @param $objectClassName \$dest Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - * @throws PropelException - if this object already exists - */ - public function insertAsPrevSiblingOf(NodeObject \$dest, PropelPDO \$con = null) - { - if (!\$this->isNew()) - { - throw new PropelException(\"$objectClassName must be new.\"); - } - $peerClassname::insertAsPrevSiblingOf(\$this, \$dest, \$con); - return \$this; - } -"; - } - - protected function addInsertAsNextSiblingOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$node as next sibling to given destination node \$dest - * - * @param $objectClassName \$dest Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - * @throws PropelException - if this object already exists - */ - public function insertAsNextSiblingOf(NodeObject \$dest, PropelPDO \$con = null) - { - if (!\$this->isNew()) - { - throw new PropelException(\"$objectClassName must be new.\"); - } - $peerClassname::insertAsNextSiblingOf(\$this, \$dest, \$con); - return \$this; - } -"; - } - - protected function addMoveToFirstChildOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves node to be first child of \$parent - * - * @param $objectClassName \$parent Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - */ - public function moveToFirstChildOf(NodeObject \$parent, PropelPDO \$con = null) - { - if (\$this->isNew()) - { - throw new PropelException(\"$objectClassName must exist in tree.\"); - } - $peerClassname::moveToFirstChildOf(\$parent, \$this, \$con); - return \$this; - } -"; - } - - protected function addMoveToLastChildOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves node to be last child of \$parent - * - * @param $objectClassName \$parent Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - */ - public function moveToLastChildOf(NodeObject \$parent, PropelPDO \$con = null) - { - if (\$this->isNew()) - { - throw new PropelException(\"$objectClassName must exist in tree.\"); - } - $peerClassname::moveToLastChildOf(\$parent, \$this, \$con); - return \$this; - } -"; - } - - protected function addMoveToPrevSiblingOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves node to be prev sibling to \$dest - * - * @param $objectClassName \$dest Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - */ - public function moveToPrevSiblingOf(NodeObject \$dest, PropelPDO \$con = null) - { - if (\$this->isNew()) - { - throw new PropelException(\"$objectClassName must exist in tree.\"); - } - $peerClassname::moveToPrevSiblingOf(\$dest, \$this, \$con); - return \$this; - } -"; - } - - protected function addMoveToNextSiblingOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves node to be next sibling to \$dest - * - * @param $objectClassName \$dest Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - */ - public function moveToNextSiblingOf(NodeObject \$dest, PropelPDO \$con = null) - { - if (\$this->isNew()) - { - throw new PropelException(\"$objectClassName must exist in tree.\"); - } - $peerClassname::moveToNextSiblingOf(\$dest, \$this, \$con); - return \$this; - } -"; - } - - protected function addInsertAsParentOf(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts node as parent of given node. - * - * @param $objectClassName \$node Propel object for destination node - * @param PropelPDO \$con Connection to use. - * @return $objectClassName The current object (for fluent API support) - */ - public function insertAsParentOf(NodeObject \$node, PropelPDO \$con = null) - { - $peerClassname::insertAsParentOf(\$this, \$node, \$con); - return \$this; - } -"; - } - - protected function addGetLeft(&$script) - { - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetLeftKey()) { - $left_col_getter_name = 'get'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Wraps the getter for the left value - * - * @return int - */ - public function getLeftValue() - { - return \$this->$left_col_getter_name(); - } -"; - } - - protected function addGetRight(&$script) - { - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetRightKey()) { - $right_col_getter_name = 'get'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Wraps the getter for the right value - * - * @return int - */ - public function getRightValue() - { - return \$this->$right_col_getter_name(); - } -"; - } - - protected function addGetScopeId(&$script) - { - $table = $this->getTable(); - - $scope_col_getter_name = null; - foreach ($table->getColumns() as $col) { - if ($col->isTreeScopeKey()) { - $scope_col_getter_name = 'get'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Wraps the getter for the scope value - * - * @return int or null if scope is disabled - */ - public function getScopeIdValue() - {"; - if ($scope_col_getter_name) { - $script .= " - return \$this->$scope_col_getter_name();"; - } else { - $script .= " - return null;"; - } - $script .= " - } -"; - } - - protected function addSetLeft(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetLeftKey()) { - $left_col_setter_name = 'set'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Set the value left column - * - * @param int \$v new value - * @return $objectClassName The current object (for fluent API support) - */ - public function setLeftValue(\$v) - { - \$this->$left_col_setter_name(\$v); - return \$this; - } -"; - } - - protected function addSetRight(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetRightKey()) { - $right_col_setter_name = 'set'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Set the value of right column - * - * @param int \$v new value - * @return $objectClassName The current object (for fluent API support) - */ - public function setRightValue(\$v) - { - \$this->$right_col_setter_name(\$v); - return \$this; - } -"; - } - - protected function addSetScopeId(&$script) - { - $objectClassName = $this->getStubObjectBuilder()->getClassname(); - $table = $this->getTable(); - - $scope_col_setter_name = null; - foreach ($table->getColumns() as $col) { - if ($col->isTreeScopeKey()) { - $scope_col_setter_name = 'set'.$col->getPhpName(); - break; - } - } - - $script .= " - /** - * Set the value of scope column - * - * @param int \$v new value - * @return $objectClassName The current object (for fluent API support) - */ - public function setScopeIdValue(\$v) - {"; - if ($scope_col_setter_name) { - $script .= " - \$this->$scope_col_setter_name(\$v);"; - } - $script .= " - return \$this; - } -"; - - } - -} // PHP5NestedSetBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php deleted file mode 100644 index ad5fa05c1..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php +++ /dev/null @@ -1,1727 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5NestedSetPeerBuilder extends PeerBuilder -{ - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubObjectBuilder()->getUnprefixedClassname() . 'NestedSetPeer'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $script .=" -require '".$this->getPeerBuilder()->getClassFilePath()."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $script .= " -/** - * Base static class for performing query operations on the tree contained by the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * @deprecated Since Propel 1.5. Use the nested_set behavior instead of the NestedSet treeMode - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." extends ".$this->getPeerBuilder()->getClassName()." implements NodePeer { -"; - } - - /** - * Specifies the methods that are added as part of the basic OM class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $table = $this->getTable(); - - // FIXME - // - Probably the build needs to be customized for supporting - // tables that are "aliases". -- definitely a fringe usecase, though. - - $this->addConstants($script); - - $this->addCreateRoot($script); - - $this->addRetrieveRoot($script); - - $this->addInsertAsFirstChildOf($script); - $this->addInsertAsLastChildOf($script); - $this->addInsertAsPrevSiblingOf($script); - $this->addInsertAsNextSiblingOf($script); - $this->addInsertAsParentOf($script); - - $this->addInsertRoot($script); - $this->addInsertParent($script); - - $this->addDeleteRoot($script); - $this->addDeleteNode($script); - - $this->addMoveToFirstChildOf($script); - $this->addMoveToLastChildOf($script); - $this->addMoveToPrevSiblingOf($script); - $this->addMoveToNextSiblingOf($script); - - $this->addRetrieveFirstChild($script); - $this->addRetrieveLastChild($script); - $this->addRetrievePrevSibling($script); - $this->addRetrieveNextSibling($script); - - $this->addRetrieveTree($script); - $this->addRetrieveBranch($script); - $this->addRetrieveChildren($script); - $this->addRetrieveDescendants($script); - $this->addRetrieveSiblings($script); - $this->addRetrieveParent($script); - - $this->addGetLevel($script); - $this->addGetNumberOfChildren($script); - $this->addGetNumberOfDescendants($script); - $this->addGetPath($script); - - $this->addIsValid($script); - $this->addIsRoot($script); - $this->addIsLeaf($script); - $this->addIsChildOf($script); - $this->addIsChildOfOrSiblingTo($script); - $this->addIsEqualTo($script); - - $this->addHasParent($script); - $this->addHasPrevSibling($script); - $this->addHasNextSibling($script); - $this->addHasChildren($script); - - $this->addDeleteDescendants($script); - - $this->addGetNode($script); - - $this->addHydrateDescendants($script); - $this->addHydrateChildren($script); - - $this->addShiftRParent($script); - $this->addUpdateLoadedNode($script); - $this->addUpdateDBNode($script); - - $this->addShiftRLValues($script); - $this->addShiftRLRange($script); - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - - protected function addConstants(&$script) - { - $table = $this->getTable(); - $tableName = $table->getName(); - - $colname = array(); - - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetLeftKey()) { - $colname['left'] = $tableName . '.' . strtoupper($col->getName()); - } - - if ($col->isNestedSetRightKey()) { - $colname['right'] = $tableName . '.' . strtoupper($col->getName()); - } - - if ($col->isTreeScopeKey()) { - $colname['scope'] = $tableName . '.' . strtoupper($col->getName()); - } - - if (3 == count($colname)) { - break; - } - } - - if(!isset($colname['left'])) { - throw new EngineException("One column must have nestedSetLeftKey attribute set to true for [" . $table->getName() . "] table"); - } - - if(!isset($colname['right'])) { - throw new EngineException("One column must have nestedSetRightKey attribute set to true for [" . $table->getName() . "] table"); - } - - $colname['scope'] = isset($colname['scope']) ? $colname['scope'] : null; - - $script .= " - /** - * Left column for the set - */ - const LEFT_COL = " . var_export($colname['left'], true) . "; - - /** - * Right column for the set - */ - const RIGHT_COL = " . var_export($colname['right'], true) . "; - - /** - * Scope column for the set - */ - const SCOPE_COL = " . var_export($colname['scope'], true) . "; -"; - } - - protected function addCreateRoot(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Creates the supplied node as the root node. - * - * @param $objectClassname \$node Propel object for model - * @throws PropelException - */ - public static function createRoot(NodeObject \$node) - { - if (\$node->getLeftValue()) { - throw new PropelException('Cannot turn an existing node into a root node.'); - } - - \$node->setLeftValue(1); - \$node->setRightValue(2); - } -"; - } - - protected function addRetrieveRoot(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Returns the root node for a given scope id - * - * @param int \$scopeId Scope id to determine which root node to return - * @param PropelPDO \$con Connection to use. - * @return $objectClassname Propel object for root node - */ - public static function retrieveRoot(\$scopeId = null, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - - \$c->add(self::LEFT_COL, 1, Criteria::EQUAL); - - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$scopeId, Criteria::EQUAL); - } - - return $peerClassname::doSelectOne(\$c, \$con); - } -"; - } - - protected function addInsertAsFirstChildOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$child as first child of given \$parent node - * - * @param $objectClassname \$child Propel object for child node - * @param $objectClassname \$parent Propel object for parent node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertAsFirstChildOf(NodeObject \$child, NodeObject \$parent, PropelPDO \$con = null) - { - // Update \$child node properties - \$child->setLeftValue(\$parent->getLeftValue() + 1); - \$child->setRightValue(\$parent->getLeftValue() + 2); - \$child->setParentNode(\$parent); - - \$sidv = null; - if (self::SCOPE_COL) { - \$child->setScopeIdValue(\$sidv = \$parent->getScopeIdValue()); - } - - // Update database nodes - self::shiftRLValues(\$child->getLeftValue(), 2, \$con, \$sidv); - - // Update all loaded nodes - self::updateLoadedNode(\$parent, 2, \$con); - } -"; - } - - protected function addInsertAsLastChildOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$child as last child of destination node \$parent - * - * @param $objectClassname \$child Propel object for child node - * @param $objectClassname \$parent Propel object for parent node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertAsLastChildOf(NodeObject \$child, NodeObject \$parent, PropelPDO \$con = null) - { - // Update \$child node properties - \$child->setLeftValue(\$parent->getRightValue()); - \$child->setRightValue(\$parent->getRightValue() + 1); - \$child->setParentNode(\$parent); - - \$sidv = null; - if (self::SCOPE_COL) { - \$child->setScopeIdValue(\$sidv = \$parent->getScopeIdValue()); - } - - // Update database nodes - self::shiftRLValues(\$child->getLeftValue(), 2, \$con, \$sidv); - - // Update all loaded nodes - self::updateLoadedNode(\$parent, 2, \$con); - } -"; - } - - protected function addInsertAsPrevSiblingOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$sibling as previous sibling to destination node \$node - * - * @param $objectClassname \$node Propel object for destination node - * @param $objectClassname \$sibling Propel object for source node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertAsPrevSiblingOf(NodeObject \$node, NodeObject \$sibling, PropelPDO \$con = null) - { - if (\$sibling->isRoot()) { - throw new PropelException('Root nodes cannot have siblings'); - } - - \$node->setLeftValue(\$sibling->getLeftValue()); - \$node->setRightValue(\$sibling->getLeftValue() + 1); - \$node->setParentNode(\$sibling->retrieveParent()); - - \$sidv = null; - if (self::SCOPE_COL) { - \$node->setScopeIdValue(\$sidv = \$sibling->getScopeIdValue()); - } - - // Update database nodes - self::shiftRLValues(\$node->getLeftValue(), 2, \$con, \$sidv); - - // Update all loaded nodes - self::updateLoadedNode(\$sibling->retrieveParent(), 2, \$con); - } -"; - } - - protected function addInsertAsNextSiblingOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$sibling as next sibling to destination node \$node - * - * @param $objectClassname \$node Propel object for destination node - * @param $objectClassname \$sibling Propel object for source node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertAsNextSiblingOf(NodeObject \$node, NodeObject \$sibling, PropelPDO \$con = null) - { - if (\$sibling->isRoot()) { - throw new PropelException('Root nodes cannot have siblings'); - } - - \$node->setLeftValue(\$sibling->getRightValue() + 1); - \$node->setRightValue(\$sibling->getRightValue() + 2); - \$node->setParentNode(\$sibling->retrieveParent()); - - \$sidv = null; - if (self::SCOPE_COL) { - \$node->setScopeIdValue(\$sidv = \$sibling->getScopeIdValue()); - } - - // Update database nodes - self::shiftRLValues(\$node->getLeftValue(), 2, \$con, \$sidv); - - // Update all loaded nodes - self::updateLoadedNode(\$sibling->retrieveParent(), 2, \$con); - } -"; - } - - protected function addInsertAsParentOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$parent as parent of given node. - * - * @param $objectClassname \$parent Propel object for given parent node - * @param $objectClassname \$node Propel object for given destination node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertAsParentOf(NodeObject \$parent, NodeObject \$node, PropelPDO \$con = null) - { - \$sidv = null; - if (self::SCOPE_COL) { - \$sidv = \$node->getScopeIdValue(); - } - - self::shiftRLValues(\$node->getLeftValue(), 1, \$con, \$sidv); - self::shiftRLValues(\$node->getRightValue() + 2, 1, \$con, \$sidv); - - if (self::SCOPE_COL) { - \$parent->setScopeIdValue(\$sidv); - } - - \$parent->setLeftValue(\$node->getLeftValue()); - \$parent->setRightValue(\$node->getRightValue() + 2); - - \$previous_parent = \$node->retrieveParent(); - \$parent->setParentNode(\$previous_parent); - \$node->setParentNode(\$parent); - - \$node->save(\$con); - - // Update all loaded nodes - self::updateLoadedNode(\$previous_parent, 2, \$con); - } -"; - } - - protected function addInsertRoot(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$node as root node - * - * @param $objectClassname \$node Propel object as root node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertRoot(NodeObject \$node, PropelPDO \$con = null) - { - \$sidv = null; - if (self::SCOPE_COL) { - \$sidv = \$node->getScopeIdValue(); - } - - $peerClassname::insertAsParentOf($peerClassname::retrieveRoot(\$sidv, \$con), \$node, \$con); - } -"; - } - - protected function addInsertParent(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Inserts \$parent as parent to destination node \$child - * - * @deprecated 1.3 - 2007/11/06 - * @see insertAsParentOf() - * @param $objectClassname \$child Propel object to become child node - * @param $objectClassname \$parent Propel object as parent node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function insertParent(NodeObject \$child, NodeObject \$parent, PropelPDO \$con = null) - { - self::insertAsParentOf(\$parent, \$child, \$con); - } -"; - } - - protected function addDeleteRoot(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Delete root node - * - * @param PropelPDO \$con Connection to use. - * @return boolean Deletion status - */ - public static function deleteRoot(\$scopeId = null, PropelPDO \$con = null) - { - if (!self::SCOPE_COL) { - \$scopeId = null; - } - \$root = $peerClassname::retrieveRoot(\$scopeId, \$con); - if ($peerClassname::getNumberOfChildren(\$root) == 1) { - return $peerClassname::deleteNode(\$root, \$con); - } else { - return false; - } - } -"; - } - - protected function addDeleteNode(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Delete \$dest node - * - * @param $objectClassname \$dest Propel object node to delete - * @param PropelPDO \$con Connection to use. - * @return boolean Deletion status - */ - public static function deleteNode(NodeObject \$dest, PropelPDO \$con = null) - { - if (\$dest->getLeftValue() == 1) { - // deleting root implies conditions (see deleteRoot() method) - return $peerClassname::deleteRoot(\$con); - } - - \$sidv = null; - if (self::SCOPE_COL) { - \$sidv = \$dest->getScopeIdValue(); - } - - self::shiftRLRange(\$dest->getLeftValue(), \$dest->getRightValue(), -1, \$con, \$sidv); - self::shiftRLValues(\$dest->getRightValue() + 1, -2, \$con, \$sidv); - return \$dest->delete(\$con); - } -"; - } - - protected function addMoveToFirstChildOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves \$child to be first child of \$parent - * - * @param $objectClassname \$parent Propel object for parent node - * @param $objectClassname \$child Propel object for child node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function moveToFirstChildOf(NodeObject \$parent, NodeObject \$child, PropelPDO \$con = null) - { - if (\$parent->getScopeIdValue() != \$child->getScopeIdValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - } - \$destLeft = \$parent->getLeftValue() + 1; - self::updateDBNode(\$child, \$destLeft, \$con); - - // Update all loaded nodes - self::updateLoadedNode(\$parent, 2, \$con); - } -"; - } - - protected function addMoveToLastChildOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves \$child to be last child of \$parent - * - * @param $objectClassname \$parent Propel object for parent node - * @param $objectClassname \$child Propel object for child node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function moveToLastChildOf(NodeObject \$parent, NodeObject \$child, PropelPDO \$con = null) - { - if (\$parent->getScopeIdValue() != \$child->getScopeIdValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - } - \$destLeft = \$parent->getRightValue(); - self::updateDBNode(\$child, \$destLeft, \$con); - - // Update all loaded nodes - self::updateLoadedNode(\$parent, 2, \$con); - } -"; - } - - protected function addMoveToPrevSiblingOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves \$node to be prev sibling to \$dest - * - * @param $objectClassname \$dest Propel object for destination node - * @param $objectClassname \$node Propel object for source node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function moveToPrevSiblingOf(NodeObject \$dest, NodeObject \$node, PropelPDO \$con = null) - { - if (\$dest->getScopeIdValue() != \$node->getScopeIdValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - } - \$destLeft = \$dest->getLeftValue(); - self::updateDBNode(\$node, \$destLeft, \$con); - - // Update all loaded nodes - self::updateLoadedNode(\$dest->retrieveParent(), 2, \$con); - } -"; - } - - protected function addMoveToNextSiblingOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Moves \$node to be next sibling to \$dest - * - * @param $objectClassname \$dest Propel object for destination node - * @param $objectClassname \$node Propel object for source node - * @param PropelPDO \$con Connection to use. - * @return void - */ - public static function moveToNextSiblingOf(NodeObject \$dest, NodeObject \$node, PropelPDO \$con = null) - { - if (\$dest->getScopeIdValue() != \$node->getScopeIdValue()) { - throw new PropelException('Moving nodes across trees is not supported'); - } - \$destLeft = \$dest->getRightValue(); - \$destLeft = \$destLeft + 1; - self::updateDBNode(\$node, \$destLeft, \$con); - - // Update all loaded nodes - self::updateLoadedNode(\$dest->retrieveParent(), 2, \$con); - } -"; - } - - protected function addRetrieveFirstChild(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets first child for the given node if it exists - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveFirstChild(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add(self::LEFT_COL, \$node->getLeftValue() + 1, Criteria::EQUAL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - - return $peerClassname::doSelectOne(\$c, \$con); - } -"; - } - - protected function addRetrieveLastChild(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets last child for the given node if it exists - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveLastChild(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add(self::RIGHT_COL, \$node->getRightValue() - 1, Criteria::EQUAL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - - return $peerClassname::doSelectOne(\$c, \$con); - } -"; - } - - protected function addRetrievePrevSibling(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets prev sibling for the given node if it exists - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else null - */ - public static function retrievePrevSibling(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add(self::RIGHT_COL, \$node->getLeftValue() - 1, Criteria::EQUAL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$prevSibling = $peerClassname::doSelectOne(\$c, \$con); - \$node->setPrevSibling(\$prevSibling); - return \$prevSibling; - } -"; - } - - protected function addRetrieveNextSibling(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets next sibling for the given node if it exists - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveNextSibling(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->add(self::LEFT_COL, \$node->getRightValue() + 1, Criteria::EQUAL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$nextSibling = $peerClassname::doSelectOne(\$c, \$con); - \$node->setNextSibling(\$nextSibling); - return \$nextSibling; - } -"; - } - - protected function addRetrieveTree(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Retrieves the entire tree from root - * - * @param PropelPDO \$con Connection to use. - */ - public static function retrieveTree(\$scopeId = null, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->addAscendingOrderByColumn(self::LEFT_COL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$scopeId, Criteria::EQUAL); - } - \$stmt = $peerClassname::doSelectStmt(\$c, \$con); - if (false !== (\$row = \$stmt->fetch(PDO::FETCH_NUM))) { - \$omClass = $peerClassname::getOMClass(\$row, 0); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); - - \$key = ".$peerClassname."::getPrimaryKeyHashFromRow(\$row, 0); - if (null === (\$root = ".$peerClassname."::getInstanceFromPool(\$key))) { - " . $this->buildObjectInstanceCreationCode('$root', '$cls') . " - \$root->hydrate(\$row); - } - - \$root->setLevel(0); - $peerClassname::hydrateDescendants(\$root, \$stmt); - $peerClassname::addInstanceToPool(\$root); - - \$stmt->closeCursor(); - return \$root; - } - return false; - } -"; - } - - protected function addRetrieveBranch(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Retrieves the entire tree from parent \$node - * - * @param $objectClassname \$node Propel object for parent node - * @param PropelPDO \$con Connection to use. - */ - public static function retrieveBranch(NodeObject \$node, PropelPDO \$con = null) - { - return $peerClassname::retrieveDescendants(\$node, \$con); - } -"; - } - - protected function addRetrieveChildren(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets direct children for the node - * - * @param $objectClassname \$node Propel object for parent node - * @param PropelPDO \$con Connection to use. - */ - public static function retrieveChildren(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->addAscendingOrderByColumn(self::LEFT_COL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$c->add(self::LEFT_COL, \$node->getLeftValue(), Criteria::GREATER_THAN); - \$c->addAnd(self::RIGHT_COL, \$node->getRightValue(), Criteria::LESS_THAN); - \$stmt = $peerClassname::doSelectStmt(\$c, \$con); - - return $peerClassname::hydrateChildren(\$node, \$stmt); - } -"; - } - - protected function addRetrieveDescendants(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets all descendants for the node - * - * @param $objectClassname \$node Propel object for parent node - * @param PropelPDO \$con Connection to use. - */ - public static function retrieveDescendants(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c->addAscendingOrderByColumn(self::LEFT_COL); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$c->add(self::LEFT_COL, \$node->getLeftValue(), Criteria::GREATER_THAN); - \$c->addAnd(self::RIGHT_COL, \$node->getRightValue(), Criteria::LESS_THAN); - \$stmt = $peerClassname::doSelectStmt(\$c, \$con); - - return $peerClassname::hydrateDescendants(\$node, \$stmt); - } -"; - } - - protected function addRetrieveSiblings(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets all siblings for the node - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - */ - public static function retrieveSiblings(NodeObject \$node, PropelPDO \$con = null) - { - \$parent = $peerClassname::retrieveParent(\$node, \$con); - \$siblings = $peerClassname::retrieveChildren(\$parent, \$con); - - return \$siblings; - } -"; - } - - protected function addRetrieveParent(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets immediate ancestor for the given node if it exists - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return mixed Propel object if exists else null - */ - public static function retrieveParent(NodeObject \$node, PropelPDO \$con = null) - { - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c1 = \$c->getNewCriterion(self::LEFT_COL, \$node->getLeftValue(), Criteria::LESS_THAN); - \$c2 = \$c->getNewCriterion(self::RIGHT_COL, \$node->getRightValue(), Criteria::GREATER_THAN); - - \$c1->addAnd(\$c2); - - \$c->add(\$c1); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$c->addAscendingOrderByColumn(self::RIGHT_COL); - - \$parent = $peerClassname::doSelectOne(\$c, \$con); - - \$node->setParentNode(\$parent); - - return \$parent; - } -"; - } - - protected function addGetLevel(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets level for the given node - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return int Level for the given node - */ - public static function getLevel(NodeObject \$node, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_READ); - } - - \$sql = \"SELECT COUNT(*) AS level FROM \" . self::TABLE_NAME . \" WHERE \" . self::LEFT_COL . \" < :left AND \" . self::RIGHT_COL . \" > :right\"; - - if (self::SCOPE_COL) { - \$sql .= ' AND ' . self::SCOPE_COL . ' = :scope'; - } - - \$stmt = \$con->prepare(\$sql); - \$stmt->bindValue(':left', \$node->getLeftValue(), PDO::PARAM_INT); - \$stmt->bindValue(':right', \$node->getRightValue(), PDO::PARAM_INT); - if (self::SCOPE_COL) { - \$stmt->bindValue(':scope', \$node->getScopeIdValue()); - } - \$stmt->execute(); - \$row = \$stmt->fetch(); - return \$row['level']; - } -"; - } - - protected function addGetNumberOfChildren(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets number of direct children for given node - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return int Level for the given node - */ - public static function getNumberOfChildren(NodeObject \$node, PropelPDO \$con = null) - { - \$children = $peerClassname::retrieveChildren(\$node); - return count(\$children); - } -"; - } - - protected function addGetNumberOfDescendants(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Gets number of descendants for given node - * - * @param $objectClassname \$node Propel object for src node - * @param PropelPDO \$con Connection to use. - * @return int Level for the given node - */ - public static function getNumberOfDescendants(NodeObject \$node, PropelPDO \$con = null) - { - \$right = \$node->getRightValue(); - \$left = \$node->getLeftValue(); - \$num = (\$right - \$left - 1) / 2; - return \$num; - } -"; - } - - protected function addGetPath(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Returns path to a specific node as an array, useful to create breadcrumbs - * - * @param $objectClassname \$node Propel object of node to create path to - * @param PropelPDO \$con Connection to use. - * @return array Array in order of heirarchy - */ - public static function getPath(NodeObject \$node, PropelPDO \$con = null) - { - \$criteria = new Criteria(); - if (self::SCOPE_COL) { - \$criteria->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$criteria->add(self::LEFT_COL, \$node->getLeftValue(), Criteria::LESS_EQUAL); - \$criteria->add(self::RIGHT_COL, \$node->getRightValue(), Criteria::GREATER_EQUAL); - \$criteria->addAscendingOrderByColumn(self::LEFT_COL); - - return self::doSelect(\$criteria, \$con); - } -"; - } - - protected function addIsValid(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if node is valid - * - * @param $objectClassname \$node Propel object for src node - * @return bool - */ - public static function isValid(NodeObject \$node = null) - { - if (is_object(\$node) && \$node->getRightValue() > \$node->getLeftValue()) { - return true; - } else { - return false; - } - } -"; - } - - protected function addIsRoot(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if node is a root - * - * @param $objectClassname \$node Propel object for src node - * @return bool - */ - public static function isRoot(NodeObject \$node) - { - return (\$node->getLeftValue()==1); - } -"; - } - - protected function addIsLeaf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if node is a leaf - * - * @param $objectClassname \$node Propel object for src node - * @return bool - */ - public static function isLeaf(NodeObject \$node) - { - return ((\$node->getRightValue()-\$node->getLeftValue())==1); - } -"; - } - - protected function addIsChildOf(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$child is a child of \$parent - * - * @param $objectClassname \$child Propel object for node - * @param $objectClassname \$parent Propel object for node - * @return bool - */ - public static function isChildOf(NodeObject \$child, NodeObject \$parent) - { - return ((\$child->getLeftValue()>\$parent->getLeftValue()) && (\$child->getRightValue()<\$parent->getRightValue())); - } -"; - } - - protected function addIsChildOfOrSiblingTo(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node1 is a child of or equal to \$node2 - * - * @deprecated 1.3 - 2007/11/09 - * @param $objectClassname \$node1 Propel object for node - * @param $objectClassname \$node2 Propel object for node - * @return bool - */ - public static function isChildOfOrSiblingTo(NodeObject \$node1, NodeObject \$node2) - { - return ((\$node1->getLeftValue()>=\$node2->getLeftValue()) and (\$node1->getRightValue()<=\$node2->getRightValue())); - } -"; - } - - protected function addIsEqualTo(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node1 is equal to \$node2 - * - * @param $objectClassname \$node1 Propel object for node - * @param $objectClassname \$node2 Propel object for node - * @return bool - */ - public static function isEqualTo(NodeObject \$node1, NodeObject \$node2) - { - \$also = true; - if (self::SCOPE_COL) { - \$also = (\$node1->getScopeIdValue() === \$node2->getScopeIdValue()); - } - return \$node1->getLeftValue() == \$node2->getLeftValue() && \$node1->getRightValue() == \$node2->getRightValue() && \$also; - } -"; - } - - protected function addHasParent(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node has an ancestor - * - * @param $objectClassname \$node Propel object for node - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public static function hasParent(NodeObject \$node, PropelPDO \$con = null) - { - return $peerClassname::isValid($peerClassname::retrieveParent(\$node, \$con)); - } -"; - } - - protected function addHasPrevSibling(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node has prev sibling - * - * @param $objectClassname \$node Propel object for node - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public static function hasPrevSibling(NodeObject \$node, PropelPDO \$con = null) - { - return $peerClassname::isValid($peerClassname::retrievePrevSibling(\$node, \$con)); - } -"; - } - - protected function addHasNextSibling(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node has next sibling - * - * @param $objectClassname \$node Propel object for node - * @param PropelPDO \$con Connection to use. - * @return bool - */ - public static function hasNextSibling(NodeObject \$node, PropelPDO \$con = null) - { - return $peerClassname::isValid($peerClassname::retrieveNextSibling(\$node, \$con)); - } -"; - } - - protected function addHasChildren(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Tests if \$node has children - * - * @param $objectClassname \$node Propel object for node - * @return bool - */ - public static function hasChildren(NodeObject \$node) - { - return ((\$node->getRightValue()-\$node->getLeftValue())>1); - } -"; - } - - protected function addDeleteDescendants(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Deletes \$node and all of its descendants - * - * @param $objectClassname \$node Propel object for source node - * @param PropelPDO \$con Connection to use. - */ - public static function deleteDescendants(NodeObject \$node, PropelPDO \$con = null) - { - \$left = \$node->getLeftValue(); - \$right = \$node->getRightValue(); - - \$c = new Criteria($peerClassname::DATABASE_NAME); - \$c1 = \$c->getNewCriterion(self::LEFT_COL, \$left, Criteria::GREATER_THAN); - \$c2 = \$c->getNewCriterion(self::RIGHT_COL, \$right, Criteria::LESS_THAN); - - \$c1->addAnd(\$c2); - - \$c->add(\$c1); - if (self::SCOPE_COL) { - \$c->add(self::SCOPE_COL, \$node->getScopeIdValue(), Criteria::EQUAL); - } - \$c->addAscendingOrderByColumn(self::RIGHT_COL); - - \$result = $peerClassname::doDelete(\$c, \$con); - - self::shiftRLValues(\$right + 1, \$left - \$right -1, \$con, \$node->getScopeIdValue()); - - return \$result; - } -"; - } - - protected function addGetNode(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Returns a node given its primary key or the node itself - * - * @param int/$objectClassname \$node Primary key/instance of required node - * @param PropelPDO \$con Connection to use. - * @return object Propel object for model - */ - public static function getNode(\$node, PropelPDO \$con = null) - { - if (is_object(\$node)) { - return \$node; - } else { - \$object = $peerClassname::retrieveByPK(\$node, \$con); - \$rtn = is_object(\$object) ? \$object : false; - return \$rtn; - } - } -"; - } - - protected function addHydrateDescendants(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $table = $this->getTable(); - $script .= " - /** - * Hydrate recursively the descendants of the given node - * @param $objectClassname \$node Propel object for src node - * @param PDOStatement \$stmt Executed PDOStatement - */ - protected static function hydrateDescendants(NodeObject \$node, PDOStatement \$stmt) - { - \$descendants = array(); - \$children = array(); - \$prevSibling = null; -"; - - if (!$table->getChildrenColumn()) { - $script .= " - // set the class once to avoid overhead in the loop - \$cls = $peerClassname::getOMClass(); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key = ".$peerClassname."::getPrimaryKeyHashFromRow(\$row, 0); - if (null === (\$child = ".$peerClassname."::getInstanceFromPool(\$key))) {"; - - if ($table->getChildrenColumn()) { - $script .= " - // class must be set each time from the record row - \$cls = ".$peerClassname."::getOMClass(\$row, 0); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$child', '$cls') . " - \$child->hydrate(\$row); - } - - \$child->setLevel(\$node->getLevel() + 1); - \$child->setParentNode(\$node); - if (!empty(\$prevSibling)) { - \$child->setPrevSibling(\$prevSibling); - \$prevSibling->setNextSibling(\$child); - } - - \$descendants[] = \$child; - - if (\$child->hasChildren()) { - \$descendants = array_merge(\$descendants, $peerClassname::hydrateDescendants(\$child, \$stmt)); - } else { - \$child->setChildren(array()); - } - - \$children[] = \$child; - \$prevSibling = \$child; - - $peerClassname::addInstanceToPool(\$child); - if (\$child->getRightValue() + 1 == \$node->getRightValue()) { - \$child->setNextSibling(null); - break; - } - } - \$node->setChildren(\$children); - return \$descendants; - } -"; - } - - protected function addHydrateChildren(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $table = $this->getTable(); - $script .= " - /** - * Hydrate the children of the given node - * @param $objectClassname \$node Propel object for src node - * @param PDOStatement \$stmt Executed PDOStatement - */ - protected static function hydrateChildren(NodeObject \$node, PDOStatement \$stmt) - { - \$children = array(); - \$prevRight = 0; -"; - - if (!$table->getChildrenColumn()) { - $script .= " - // set the class once to avoid overhead in the loop - \$cls = $peerClassname::getOMClass(); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key = ".$peerClassname."::getPrimaryKeyHashFromRow(\$row, 0); - if (null === (\$child = ".$peerClassname."::getInstanceFromPool(\$key))) {"; - - if ($table->getChildrenColumn()) { - $script .= " - // class must be set each time from the record row - \$cls = ".$peerClassname."::getOMClass(\$row, 0); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$child', '$cls') . " - \$child->hydrate(\$row); - } - - \$child->setLevel(\$node->getLevel() + 1); - - if (\$child->getRightValue() > \$prevRight) { - \$children[] = \$child; - \$prevRight = \$child->getRightValue(); - } - - if (\$child->getRightValue() + 1 == \$node->getRightValue()) { - break; - } - } - \$node->setChildren(\$children); - return \$children; - } -"; - } - - /** - * @deprecated 1.3 - 2008/03/11 - * Won't be fixed, defect by design - * Never trust it - */ - protected function addShiftRParent(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Adds '\$delta' to all parent R values. - * '\$delta' can also be negative. - * - * @deprecated 1.3 - 2008/03/11 - * @param $objectClassname \$node Propel object for parent node - * @param int \$delta Value to be shifted by, can be negative - * @param PropelPDO \$con Connection to use. - */ - protected static function shiftRParent(NodeObject \$node, \$delta, PropelPDO \$con = null) - { - if (\$node->hasParent(\$con)) { - \$parent = \$node->retrieveParent(); - self::shiftRParent(\$parent, \$delta, \$con); - } - \$node->setRightValue(\$node->getRightValue() + \$delta); - } -"; - } - - protected function addUpdateLoadedNode(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $table = $this->getTable(); - - $script .= " - /** - * Reload all already loaded nodes to sync them with updated db - * - * @param $objectClassname \$node Propel object for parent node - * @param int \$delta Value to be shifted by, can be negative - * @param PropelPDO \$con Connection to use. - */ - protected static function updateLoadedNode(NodeObject \$node, \$delta, PropelPDO \$con = null) - { - if (Propel::isInstancePoolingEnabled()) { - \$keys = array(); - foreach (self::\$instances as \$obj) { - \$keys[] = \$obj->getPrimaryKey(); - } - - if (!empty(\$keys)) { - // We don't need to alter the object instance pool; we're just modifying these ones - // already in the pool. - \$criteria = new Criteria(self::DATABASE_NAME);"; - if (count($table->getPrimaryKey()) === 1) { - $pkey = $table->getPrimaryKey(); - $col = array_shift($pkey); - $script .= " - \$criteria->add(".$this->getColumnConstant($col).", \$keys, Criteria::IN); -"; - } else { - $fields = array(); - foreach ($table->getPrimaryKey() as $k => $col) { - $fields[] = $this->getColumnConstant($col); - }; - $script .= " - - // Loop on each instances in pool - foreach (\$keys as \$values) { - // Create initial Criterion - \$cton = \$criteria->getNewCriterion(" . $fields[0] . ", \$values[0]);"; - unset($fields[0]); - foreach ($fields as $k => $col) { - $script .= " - - // Create next criterion - \$nextcton = \$criteria->getNewCriterion(" . $col . ", \$values[$k]); - // And merge it with the first - \$cton->addAnd(\$nextcton);"; - } - $script .= " - - // Add final Criterion to Criteria - \$criteria->addOr(\$cton); - }"; - } - - $script .= " - \$stmt = $peerClassname::doSelectStmt(\$criteria, \$con); - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key = $peerClassname::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$object = $peerClassname::getInstanceFromPool(\$key))) {"; - $n = 0; - foreach ($table->getColumns() as $col) { - if ($col->isNestedSetLeftKey()) { - $script .= " - \$object->setLeftValue(\$row[$n]);"; - } else if ($col->isNestedSetRightKey()) { - $script .= " - \$object->setRightValue(\$row[$n]);"; - } - $n++; - } - $script .= " - } - } - \$stmt->closeCursor(); - } - } - } -"; - } - - protected function addUpdateDBNode(&$script) - { - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - $script .= " - /** - * Move \$node and its children to location \$destLeft and updates rest of tree - * - * @param $objectClassname \$node Propel object for node to update - * @param int \$destLeft Destination left value - * @param PropelPDO \$con Connection to use. - */ - protected static function updateDBNode(NodeObject \$node, \$destLeft, PropelPDO \$con = null) - { - \$left = \$node->getLeftValue(); - \$right = \$node->getRightValue(); - - \$treeSize = \$right - \$left +1; - - self::shiftRLValues(\$destLeft, \$treeSize, \$con, \$node->getScopeIdValue()); - - if (\$left >= \$destLeft) { // src was shifted too? - \$left += \$treeSize; - \$right += \$treeSize; - } - - // now there's enough room next to target to move the subtree - self::shiftRLRange(\$left, \$right, \$destLeft - \$left, \$con, \$node->getScopeIdValue()); - - // correct values after source - self::shiftRLValues(\$right + 1, -\$treeSize, \$con, \$node->getScopeIdValue()); - } -"; - } - - protected function addShiftRLValues(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Adds '\$delta' to all L and R values that are >= '\$first'. '\$delta' can also be negative. - * - * @param int \$first First node to be shifted - * @param int \$delta Value to be shifted by, can be negative - * @param PropelPDO \$con Connection to use. - */ - protected static function shiftRLValues(\$first, \$delta, PropelPDO \$con = null, \$scopeId = null) - { - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$leftUpdateCol = self::LEFT_COL; - \$rightUpdateCol = self::RIGHT_COL; - - // Shift left column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion( - self::LEFT_COL, - \$first, - Criteria::GREATER_EQUAL); - - if (self::SCOPE_COL) { - \$criterion->addAnd( - \$whereCriteria->getNewCriterion( - self::SCOPE_COL, - \$scopeId, - Criteria::EQUAL)); - } - \$whereCriteria->add(\$criterion); - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add( - self::LEFT_COL, - array('raw' => \$leftUpdateCol . ' + ?', 'value' => \$delta), - Criteria::CUSTOM_EQUAL); - - {$this->basePeerClassname}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - - // Shift right column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion( - self::RIGHT_COL, - \$first, - Criteria::GREATER_EQUAL); - - if (self::SCOPE_COL) { - \$criterion->addAnd( - \$whereCriteria->getNewCriterion( - self::SCOPE_COL, - \$scopeId, - Criteria::EQUAL)); - } - \$whereCriteria->add(\$criterion); - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add( - self::RIGHT_COL, - array('raw' => \$rightUpdateCol . ' + ?', 'value' => \$delta), - Criteria::CUSTOM_EQUAL); - - {$this->basePeerClassname}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - } -"; - } - - protected function addShiftRLRange(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $script .= " - /** - * Adds '\$delta' to all L and R values that are >= '\$first' and <= '\$last'. - * '\$delta' can also be negative. - * - * @param int \$first First node to be shifted (L value) - * @param int \$last Last node to be shifted (L value) - * @param int \$delta Value to be shifted by, can be negative - * @param PropelPDO \$con Connection to use. - * @return array Shifted L and R values - */ - protected static function shiftRLRange(\$first, \$last, \$delta, PropelPDO \$con = null, \$scopeId = null) - { - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$leftUpdateCol = substr(self::LEFT_COL, strrpos(self::LEFT_COL, '.') + 1); - \$rightUpdateCol = substr(self::RIGHT_COL, strrpos(self::RIGHT_COL, '.') + 1); - - // Shift left column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion(self::LEFT_COL, \$first, Criteria::GREATER_EQUAL); - \$criterion->addAnd(\$whereCriteria->getNewCriterion(self::LEFT_COL, \$last, Criteria::LESS_EQUAL)); - if (self::SCOPE_COL) { - \$criterion->addAnd(\$whereCriteria->getNewCriterion(self::SCOPE_COL, \$scopeId, Criteria::EQUAL)); - } - \$whereCriteria->add(\$criterion); - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add( - self::LEFT_COL, - array('raw' => \$leftUpdateCol . ' + ?', 'value' => \$delta), - Criteria::CUSTOM_EQUAL); - - {$this->basePeerClassname}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - - // Shift right column values - \$whereCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$criterion = \$whereCriteria->getNewCriterion(self::RIGHT_COL, \$first, Criteria::GREATER_EQUAL); - \$criterion->addAnd(\$whereCriteria->getNewCriterion(self::RIGHT_COL, \$last, Criteria::LESS_EQUAL)); - if (self::SCOPE_COL) { - \$criterion->addAnd(\$whereCriteria->getNewCriterion(self::SCOPE_COL, \$scopeId, Criteria::EQUAL)); - } - \$whereCriteria->add(\$criterion); - - \$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME); - \$valuesCriteria->add( - self::RIGHT_COL, - array('raw' => \$rightUpdateCol . ' + ?', 'value' => \$delta), - Criteria::CUSTOM_EQUAL); - - {$this->basePeerClassname}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con); - - return array('left' => \$first + \$delta, 'right' => \$last + \$delta); - } -"; - } - -} // PHP5NestedSetPeerBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodeBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodeBuilder.php deleted file mode 100644 index 1f5b0eca1..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodeBuilder.php +++ /dev/null @@ -1,1104 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5NodeBuilder extends ObjectBuilder -{ - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubNodeBuilder()->getUnprefixedClassname(); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $script .= " -/** - * Base class that represents a row from the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." implements IteratorAggregate { -"; - } - - /** - * Specifies the methods that are added as part of the basic OM class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $table = $this->getTable(); - - $this->addAttributes($script); - - $this->addConstructor($script); - - $this->addCallOverload($script); - $this->addSetIteratorOptions($script); - $this->addGetIterator($script); - - $this->addGetNodeObj($script); - $this->addGetNodePath($script); - $this->addGetNodeIndex($script); - $this->addGetNodeLevel($script); - - $this->addHasChildNode($script); - $this->addGetChildNodeAt($script); - $this->addGetFirstChildNode($script); - $this->addGetLastChildNode($script); - $this->addGetSiblingNode($script); - - $this->addGetParentNode($script); - $this->addGetAncestors($script); - $this->addIsRootNode($script); - - $this->addSetNew($script); - $this->addSetDeleted($script); - $this->addAddChildNode($script); - $this->addMoveChildNode($script); - $this->addSave($script); - - $this->addDelete($script); - $this->addEquals($script); - - $this->addAttachParentNode($script); - $this->addAttachChildNode($script); - $this->addDetachParentNode($script); - $this->addDetachChildNode($script); - $this->addShiftChildNodes($script); - $this->addInsertNewChildNode($script); - - $this->addAdjustStatus($script); - $this->addAdjustNodePath($script); - - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - - - /** - * Adds class attributes. - * @param string &$script The script will be modified in this method. - */ - protected function addAttributes(&$script) - { - $script .= " - /** - * @var ".$this->getStubObjectBuilder()->getClassname()." object wrapped by this node. - */ - protected \$obj = null; - - /** - * The parent node for this node. - * @var ".$this->getStubNodeBuilder()->getClassname()." - */ - protected \$parentNode = null; - - /** - * Array of child nodes for this node. Nodes indexes are one-based. - * @var array - */ - protected \$childNodes = array(); -"; - } - - /** - * Adds the constructor. - * @param string &$script The script will be modified in this method. - */ - protected function addConstructor(&$script) - { - $script .= " - /** - * Constructor. - * - * @param ".$this->getStubObjectBuilder()->getClassname()." \$obj Object wrapped by this node. - */ - public function __construct(\$obj = null) - { - if (\$obj !== null) { - \$this->obj = \$obj; - } else { - \$setNodePath = 'set' . ".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_PHPNAME; - \$this->obj = new ".$this->getStubObjectBuilder()->getClassname()."(); - \$this->obj->\$setNodePath('0'); - } - } -"; - } - - - - protected function addCallOverload(&$script) - { - $script .= " - /** - * Convenience overload for wrapped object methods. - * - * @param string Method name to call on wrapped object. - * @param mixed Parameter accepted by wrapped object set method. - * @return mixed Return value of wrapped object method. - * @throws PropelException Fails if method is not defined for wrapped object. - */ - public function __call(\$name, \$parms) - { - if (method_exists(\$this->obj, \$name)) - return call_user_func_array(array(\$this->obj, \$name), \$parms); - else - throw new PropelException('get method not defined: \$name'); - } -"; - } - - protected function addSetIteratorOptions(&$script) - { - $script .= " - - /** - * Sets the default options for iterators created from this object. - * The options are specified in map format. The following options - * are supported by all iterators. Some iterators may support other - * options: - * - * \"querydb\" - True if nodes should be retrieved from database. - * \"con\" - Connection to use if retrieving from database. - * - * @param string Type of iterator to use (\"pre\", \"post\", \"level\"). - * @param array Map of option name => value. - * @return void - * @todo Implement other iterator types (i.e. post-order, level, etc.) - */ - public function setIteratorOptions(\$type, \$opts) - { - \$this->itType = \$type; - \$this->itOpts = \$opts; - } -"; - } - - protected function addGetIterator(&$script) - { - $script .= " - /** - * Returns a pre-order iterator for this node and its children. - * - * @param string Type of iterator to use (\"pre\", \"post\", \"level\") - * @param array Map of option name => value. - * @return NodeIterator - */ - public function getIterator(\$type = null, \$opts = null) - { - if (\$type === null) - \$type = (isset(\$this->itType) ? \$this->itType : 'Pre'); - - if (\$opts === null) - \$opts = (isset(\$this->itOpts) ? \$this->itOpts : array()); - - \$itclass = ucfirst(strtolower(\$type)) . 'OrderNodeIterator'; - - require_once('propel/om/' . \$itclass . '.php'); - return new \$itclass(\$this, \$opts); - } -"; - } - - protected function addGetNodeObj(&$script) - { - $script .= " - /** - * Returns the object wrapped by this class. - * @return ".$this->getStubObjectBuilder()->getClassname()." - */ - public function getNodeObj() - { - return \$this->obj; - } -"; - } - - protected function addGetNodePath(&$script) - { - $script .= " - /** - * Convenience method for retrieving nodepath. - * @return string - */ - public function getNodePath() - { - \$getNodePath = 'get' . ".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_PHPNAME; - return \$this->obj->\$getNodePath(); - } -"; - } - - protected function addGetNodeIndex(&$script) - { - $script .= " - /** - * Returns one-based node index among siblings. - * @return int - */ - public function getNodeIndex() - { - \$npath =& \$this->getNodePath(); - \$sep = strrpos(\$npath, ".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_SEP); - return (int) (\$sep !== false ? substr(\$npath, \$sep+1) : \$npath); - } -"; - } - - protected function addGetNodeLevel(&$script) - { - $script .= " - /** - * Returns one-based node level within tree (root node is level 1). - * @return int - */ - public function getNodeLevel() - { - return (substr_count(\$this->getNodePath(), ".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_SEP) + 1); - } -"; - } - - protected function addHasChildNode(&$script) - { - $script .= " - /** - * Returns true if specified node is a child of this node. If recurse is - * true, checks if specified node is a descendant of this node. - * - * @param ".$this->getStubNodeBuilder()->getClassname()." Node to look for. - * @param boolean True if strict comparison should be used. - * @param boolean True if all descendants should be checked. - * @return boolean - */ - public function hasChildNode(\$node, \$strict = false, \$recurse = false) - { - foreach (\$this->childNodes as \$childNode) - { - if (\$childNode->equals(\$node, \$strict)) - return true; - - if (\$recurse && \$childNode->hasChildNode(\$node, \$recurse)) - return true; - } - - return false; - } -"; - } - - protected function addGetChildNodeAt(&$script) - { - $script .= " - /** - * Returns child node at one-based index. Retrieves from database if not - * loaded yet. - * - * @param int One-based child node index. - * @param boolean True if child should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - * @return ".$this->getStubNodeBuilder()->getClassname()." - */ - public function getChildNodeAt(\$i, \$querydb = false, PropelPDO \$con = null) - { - if (\$querydb && - !\$this->obj->isNew() && - !\$this->obj->isDeleted() && - !isset(\$this->childNodes[\$i])) - { - \$criteria = new Criteria(".$this->getStubPeerBuilder()->getClassname()."::DATABASE_NAME); - \$criteria->add(".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_COLNAME, \$this->getNodePath() . ".$this->getStubNodePeerBuilder()->getClassname()."::NPATH_SEP . \$i, Criteria::EQUAL); - - if (\$childObj = ".$this->getStubPeerBuilder()->getClassname()."::doSelectOne(\$criteria, \$con)) - \$this->attachChildNode(new ".$this->getStubNodeBuilder()->getClassname()."(\$childObj)); - } - - return (isset(\$this->childNodes[\$i]) ? \$this->childNodes[\$i] : null); - } -"; - } - - protected function addGetFirstChildNode(&$script) - { - $script .= " - /** - * Returns first child node (if any). Retrieves from database if not loaded yet. - * - * @param boolean True if child should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - * @return ".$this->getStubNodeBuilder()->getClassname()." - */ - public function getFirstChildNode(\$querydb = false, PropelPDO \$con = null) - { - return \$this->getChildNodeAt(1, \$querydb, \$con); - } -"; - } - - protected function addGetLastChildNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Returns last child node (if any). - * - * @param boolean True if child should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - */ - public function getLastChildNode(\$querydb = false, PropelPDO \$con = null) - { - \$lastNode = null; - - if (\$this->obj->isNew() || \$this->obj->isDeleted()) - { - end(\$this->childNodes); - \$lastNode = (count(\$this->childNodes) ? current(\$this->childNodes) : null); - } - else if (\$querydb) - { - \$db = Propel::getDb($peerClassname::DATABASE_NAME); - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - \$criteria->add($nodePeerClassname::NPATH_COLNAME, \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . '%', Criteria::LIKE); - \$criteria->addAnd($nodePeerClassname::NPATH_COLNAME, \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . '%' . $nodePeerClassname::NPATH_SEP . '%', Criteria::NOT_LIKE); - $peerClassname::addSelectColumns(\$criteria); - \$criteria->addAsColumn('npathlen', \$db->strLength($nodePeerClassname::NPATH_COLNAME)); - \$criteria->addDescendingOrderByColumn('npathlen'); - \$criteria->addDescendingOrderByColumn($nodePeerClassname::NPATH_COLNAME); - - \$lastObj = $peerClassname::doSelectOne(\$criteria, \$con); - - if (\$lastObj !== null) - { - \$lastNode = new ".$this->getStubNodeBuilder()->getClassname()."(\$lastObj); - - end(\$this->childNodes); - \$endNode = (count(\$this->childNodes) ? current(\$this->childNodes) : null); - - if (\$endNode) - { - if (\$endNode->getNodePath() > \$lastNode->getNodePath()) - throw new PropelException('Cached child node inconsistent with database.'); - else if (\$endNode->getNodePath() == \$lastNode->getNodePath()) - \$lastNode = \$endNode; - else - \$this->attachChildNode(\$lastNode); - } - else - { - \$this->attachChildNode(\$lastNode); - } - } - } - - return \$lastNode; - } -"; - } - - protected function addGetSiblingNode(&$script) - { - $script .= " - /** - * Returns next (or previous) sibling node or null. Retrieves from database if - * not loaded yet. - * - * @param boolean True if previous sibling should be returned. - * @param boolean True if sibling should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - * @return ".$this->getStubNodeBuilder()->getClassname()." - */ - public function getSiblingNode(\$prev = false, \$querydb = false, PropelPDO \$con = null) - { - \$nidx = \$this->getNodeIndex(); - - if (\$this->isRootNode()) - { - return null; - } - else if (\$prev) - { - if (\$nidx > 1 && (\$parentNode = \$this->getParentNode(\$querydb, \$con))) - return \$parentNode->getChildNodeAt(\$nidx-1, \$querydb, \$con); - else - return null; - } - else - { - if (\$parentNode = \$this->getParentNode(\$querydb, \$con)) - return \$parentNode->getChildNodeAt(\$nidx+1, \$querydb, \$con); - else - return null; - } - } -"; - } - - protected function addGetParentNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Returns parent node. Loads from database if not cached yet. - * - * @param boolean True if parent should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - * @return ".$this->getStubNodeBuilder()->getClassname()." - */ - public function getParentNode(\$querydb = true, PropelPDO \$con = null) - { - if (\$querydb && - \$this->parentNode === null && - !\$this->isRootNode() && - !\$this->obj->isNew() && - !\$this->obj->isDeleted()) - { - \$npath =& \$this->getNodePath(); - \$sep = strrpos(\$npath, $nodePeerClassname::NPATH_SEP); - \$ppath = substr(\$npath, 0, \$sep); - - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - \$criteria->add($nodePeerClassname::NPATH_COLNAME, \$ppath, Criteria::EQUAL); - - if (\$parentObj = $peerClassname::doSelectOne(\$criteria, \$con)) - { - \$parentNode = new ".$this->getStubNodeBuilder()->getClassname()."(\$parentObj); - \$parentNode->attachChildNode(\$this); - } - } - - return \$this->parentNode; - } -"; - } - - protected function addGetAncestors(&$script) - { - $script .= " - /** - * Returns an array of all ancestor nodes, starting with the root node - * first. - * - * @param boolean True if ancestors should be retrieved from database. - * @param PropelPDO Connection to use if retrieving from database. - * @return array - */ - public function getAncestors(\$querydb = false, PropelPDO \$con = null) - { - \$ancestors = array(); - \$parentNode = \$this; - - while (\$parentNode = \$parentNode->getParentNode(\$querydb, \$con)) - array_unshift(\$ancestors, \$parentNode); - - return \$ancestors; - } -"; - } - - protected function addIsRootNode(&$script) - { - $script .= " - /** - * Returns true if node is the root node of the tree. - * @return boolean - */ - public function isRootNode() - { - return (\$this->getNodePath() === '1'); - } -"; - } - - protected function addSetNew(&$script) - { - $script .= " - /** - * Changes the state of the object and its descendants to 'new'. - * Also changes the node path to '0' to indicate that it is not a - * stored node. - * - * @param boolean - * @return void - */ - public function setNew(\$b) - { - \$this->adjustStatus('new', \$b); - \$this->adjustNodePath(\$this->getNodePath(), '0'); - } -"; - } - - protected function addSetDeleted(&$script) - { - $script .= " - /** - * Changes the state of the object and its descendants to 'deleted'. - * - * @param boolean - * @return void - */ - public function setDeleted(\$b) - { - \$this->adjustStatus('deleted', \$b); - } -"; - } - - protected function addAddChildNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Adds the specified node (and its children) as a child to this node. If a - * valid \$beforeNode is specified, the node will be inserted in front of - * \$beforeNode. If \$beforeNode is not specified the node will be appended to - * the end of the child nodes. - * - * @param ".$this->getStubNodeBuilder()->getClassname()." Node to add. - * @param ".$this->getStubNodeBuilder()->getClassname()." Node to insert before. - * @param PropelPDO Connection to use. - */ - public function addChildNode(\$node, \$beforeNode = null, PropelPDO \$con = null) - { - if (\$this->obj->isNew() && !\$node->obj->isNew()) - throw new PropelException('Cannot add stored nodes to a new node.'); - - if (\$this->obj->isDeleted() || \$node->obj->isDeleted()) - throw new PropelException('Cannot add children in a deleted state.'); - - if (\$this->hasChildNode(\$node)) - throw new PropelException('Node is already a child of this node.'); - - if (\$beforeNode && !\$this->hasChildNode(\$beforeNode)) - throw new PropelException('Invalid beforeNode.'); - - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - - if (!\$this->obj->isNew()) \$con->beginTransaction(); - - try { - if (\$beforeNode) - { - // Inserting before a node. - \$childIdx = \$beforeNode->getNodeIndex(); - \$this->shiftChildNodes(1, \$beforeNode->getNodeIndex(), \$con); - } - else - { - // Appending child node. - if (\$lastNode = \$this->getLastChildNode(true, \$con)) - \$childIdx = \$lastNode->getNodeIndex()+1; - else - \$childIdx = 1; - } - - // Add the child (and its children) at the specified index. - - if (!\$this->obj->isNew() && \$node->obj->isNew()) - { - \$this->insertNewChildNode(\$node, \$childIdx, \$con); - } - else - { - // \$this->isNew() && \$node->isNew() || - // !\$this->isNew() && !node->isNew() - - \$srcPath = \$node->getNodePath(); - \$dstPath = \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . \$childIdx; - - if (!\$node->obj->isNew()) - { - $nodePeerClassname::moveNodeSubTree(\$srcPath, \$dstPath, \$con); - \$parentNode = \$node->getParentNode(true, \$con); - } - else - { - \$parentNode = \$node->getParentNode(); - } - - if (\$parentNode) - { - \$parentNode->detachChildNode(\$node); - \$parentNode->shiftChildNodes(-1, \$node->getNodeIndex()+1, \$con); - } - - \$node->adjustNodePath(\$srcPath, \$dstPath); - } - - if (!\$this->obj->isNew()) \$con->commit(); - - \$this->attachChildNode(\$node); - - } catch (SQLException \$e) { - if (!\$this->obj->isNew()) \$con->rollBack(); - throw new PropelException(\$e); - } - } -"; - } - - protected function addMoveChildNode(&$script) - { - $script .= " - /** - * Moves the specified child node in the specified direction. - * - * @param ".$this->getStubNodeBuilder()->getClassname()." Node to move. - * @param int Number of spaces to move among siblings (may be negative). - * @param PropelPDO Connection to use. - * @throws PropelException - */ - public function moveChildNode(\$node, \$direction, PropelPDO \$con = null) - { - throw new PropelException('moveChildNode() not implemented yet.'); - } -"; - } - - - protected function addSave(&$script) - { - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $script .= " - /** - * Saves modified object data to the datastore. - * - * @param boolean If true, descendants will be saved as well. - * @param PropelPDO Connection to use. - */ - public function save(\$recurse = false, PropelPDO \$con = null) - { - if (\$this->obj->isDeleted()) - throw new PropelException('Cannot save deleted node.'); - - if (substr(\$this->getNodePath(), 0, 1) == '0') - throw new PropelException('Cannot save unattached node.'); - - if (\$this->obj->isColumnModified($nodePeerClassname::NPATH_COLNAME)) - throw new PropelException('Cannot save manually modified node path.'); - - \$this->obj->save(\$con); - - if (\$recurse) - { - foreach (\$this->childNodes as \$childNode) - \$childNode->save(\$recurse, \$con); - } - } -"; - } - - - protected function addDelete(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $script .= " - /** - * Removes this object and all descendants from datastore. - * - * @param PropelPDO Connection to use. - * @return void - * @throws PropelException - */ - public function delete(PropelPDO \$con = null) - { - if (\$this->obj->isDeleted()) { - throw new PropelException('This node has already been deleted.'); - } - - if (\$con === null) { - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - if (!\$this->obj->isNew()) { - $nodePeerClassname::deleteNodeSubTree(\$this->getNodePath(), \$con); - } - - if (\$parentNode = \$this->getParentNode(true, \$con)) { - \$parentNode->detachChildNode(\$this); - \$parentNode->shiftChildNodes(-1, \$this->getNodeIndex()+1, \$con); - } - - \$this->setDeleted(true); - } -"; - } - - protected function addEquals(&$script) - { - $nodeClassname = $this->getStubNodeBuilder()->getClassname(); - $script .= " - /** - * Compares the object wrapped by this node with that of another node. Use - * this instead of equality operators to prevent recursive dependency - * errors. - * - * @param $nodeClassname Node to compare. - * @param boolean True if strict comparison should be used. - * @return boolean - */ - public function equals(\$node, \$strict = false) - { - if (\$strict) { - return (\$this->obj === \$node->obj); - } else { - return (\$this->obj == \$node->obj); - } - } -"; - } - - protected function addAttachParentNode(&$script) - { - $nodeClassname = $this->getStubNodeBuilder()->getClassname(); - $script .= " - /** - * This method is used internally when constructing the tree structure - * from the database. To set the parent of a node, you should call - * addChildNode() on the parent. - * - * @param $nodeClassname Parent node to attach. - * @return void - * @throws PropelException - */ - public function attachParentNode(\$node) - { - if (!\$node->hasChildNode(\$this, true)) - throw new PropelException('Failed to attach parent node for non-child.'); - - \$this->parentNode = \$node; - } -"; - } - - - protected function addAttachChildNode(&$script) - { - $nodeClassname = $this->getStubNodeBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $script .= " - /** - * This method is used internally when constructing the tree structure - * from the database. To add a child to a node you should call the - * addChildNode() method instead. - * - * @param $nodeClassname Child node to attach. - * @return void - * @throws PropelException - */ - public function attachChildNode(\$node) - { - if (\$this->hasChildNode(\$node)) - throw new PropelException('Failed to attach child node. Node already exists.'); - - if (\$this->obj->isDeleted() || \$node->obj->isDeleted()) - throw new PropelException('Failed to attach node in deleted state.'); - - if (\$this->obj->isNew() && !\$node->obj->isNew()) - throw new PropelException('Failed to attach non-new child to new node.'); - - if (!\$this->obj->isNew() && \$node->obj->isNew()) - throw new PropelException('Failed to attach new child to non-new node.'); - - if (\$this->getNodePath() . $nodePeerClassname::NPATH_SEP . \$node->getNodeIndex() != \$node->getNodePath()) - throw new PropelException('Failed to attach child node. Node path mismatch.'); - - \$this->childNodes[\$node->getNodeIndex()] = \$node; - ksort(\$this->childNodes); - - \$node->attachParentNode(\$this); - } -"; - } - - protected function addDetachParentNode(&$script) - { - $nodeClassname = $this->getStubNodeBuilder()->getClassname(); - $script .= " - /** - * This method is used internally when deleting nodes. It is used to break - * the link to this node's parent. - * @param $nodeClassname Parent node to detach from. - * @return void - * @throws PropelException - */ - public function detachParentNode(\$node) - { - if (!\$node->hasChildNode(\$this, true)) - throw new PropelException('Failed to detach parent node from non-child.'); - - unset(\$node->childNodes[\$this->getNodeIndex()]); - \$this->parentNode = null; - } -"; - } - - protected function addDetachChildNode(&$script) - { - $script .= " - /** - * This method is used internally when deleting nodes. It is used to break - * the link to this between this node and the specified child. - * @param ".$this->getStubNodeBuilder()->getClassname()." Child node to detach. - * @return void - * @throws PropelException - */ - public function detachChildNode(\$node) - { - if (!\$this->hasChildNode(\$node, true)) - throw new PropelException('Failed to detach non-existent child node.'); - - unset(\$this->childNodes[\$node->getNodeIndex()]); - \$node->parentNode = null; - } -"; - } - - protected function addShiftChildNodes(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Shifts child nodes in the specified direction and offset index. This - * method assumes that there is already space available in the - * direction/offset indicated. - * - * @param int Direction/# spaces to shift. 1=leftshift, 1=rightshift - * @param int Node index to start shift at. - * @param PropelPDO The connection to be used. - * @return void - * @throws PropelException - */ - protected function shiftChildNodes(\$direction, \$offsetIdx, PropelPDO \$con) - { - if (\$this->obj->isDeleted()) - throw new PropelException('Cannot shift nodes for deleted object'); - - \$lastNode = \$this->getLastChildNode(true, \$con); - \$lastIdx = (\$lastNode !== null ? \$lastNode->getNodeIndex() : 0); - - if (\$lastNode === null || \$offsetIdx > \$lastIdx) - return; - - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - - if (!\$this->obj->isNew()) - { - // Shift nodes in database. - - \$con->beginTransaction(); - - try { - \$n = \$lastIdx - \$offsetIdx + 1; - \$i = \$direction < 1 ? \$offsetIdx : \$lastIdx; - - while (\$n--) - { - \$srcPath = \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . \$i; // 1.2.2 - \$dstPath = \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . (\$i+\$direction); // 1.2.3 - - $nodePeerClassname::moveNodeSubTree(\$srcPath, \$dstPath, \$con); - - \$i -= \$direction; - } - - \$con->commit(); - - } catch (SQLException \$e) { - \$con->rollBack(); - throw new PropelException(\$e); - } - } - - // Shift the in-memory objects. - - \$n = \$lastIdx - \$offsetIdx + 1; - \$i = \$direction < 1 ? \$offsetIdx : \$lastIdx; - - while (\$n--) - { - if (isset(\$this->childNodes[\$i])) - { - \$srcPath = \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . \$i; // 1.2.2 - \$dstPath = \$this->getNodePath() . $nodePeerClassname::NPATH_SEP . (\$i+\$direction); // 1.2.3 - - \$this->childNodes[\$i+\$direction] = \$this->childNodes[\$i]; - \$this->childNodes[\$i+\$direction]->adjustNodePath(\$srcPath, \$dstPath); - - unset(\$this->childNodes[\$i]); - } - - \$i -= \$direction; - } - - ksort(\$this->childNodes); - } -"; - } - - protected function addInsertNewChildNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Inserts the node and its children at the specified childIdx. - * - * @param $nodeClassname Node to insert. - * @param int One-based child index to insert at. - * @param PropelPDO Connection to use. - * @param void - */ - protected function insertNewChildNode(\$node, \$childIdx, PropelPDO \$con) - { - if (!\$node->obj->isNew()) - throw new PropelException('Failed to insert non-new node.'); - - \$setNodePath = 'set' . $nodePeerClassname::NPATH_PHPNAME; - - \$node->obj->\$setNodePath(\$this->getNodePath() . $nodePeerClassname::NPATH_SEP . \$childIdx); - \$node->obj->save(\$con); - - \$i = 1; - foreach (\$node->childNodes as \$childNode) - \$node->insertNewChildNode(\$childNode, \$i++, \$con); - } -"; - } - - protected function addAdjustStatus(&$script) - { - $script .= " - /** - * Adjust new/deleted status of node and all children. - * - * @param string Status to change ('New' or 'Deleted') - * @param boolean Value for status. - * @return void - */ - protected function adjustStatus(\$status, \$b) - { - \$setStatus = 'set' . \$status; - - \$this->obj->\$setStatus(\$b); - - foreach (\$this->childNodes as \$childNode) - \$childNode->obj->\$setStatus(\$b); - } -"; - } - - protected function addAdjustNodePath(&$script) - { - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $script .= " - /** - * Adjust path of node and all children. This is used internally when - * inserting/moving nodes. - * - * @param string Section of old path to change. - * @param string New section to replace old path with. - * @return void - */ - protected function adjustNodePath(\$oldBasePath, \$newBasePath) - { - \$setNodePath = 'set' . $nodePeerClassname::NPATH_PHPNAME; - - \$this->obj->\$setNodePath(\$newBasePath . substr(\$this->getNodePath(), strlen(\$oldBasePath))); - \$this->obj->resetModified($nodePeerClassname::NPATH_COLNAME); - - foreach (\$this->childNodes as \$childNode) - \$childNode->adjustNodePath(\$oldBasePath, \$newBasePath); - } -"; - } - -} // PHP5NodeObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodePeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodePeerBuilder.php deleted file mode 100644 index b84021e70..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5NodePeerBuilder.php +++ /dev/null @@ -1,754 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5NodePeerBuilder extends PeerBuilder -{ - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubNodePeerBuilder()->getUnprefixedClassname(); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $script .= " -/** - * Base static class for performing query operations on the tree contained by the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." { -"; - } - - /** - * Specifies the methods that are added as part of the basic OM class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $table = $this->getTable(); - - // FIXME - // - Probably the build needs to be customized for supporting - // tables that are "aliases". -- definitely a fringe usecase, though. - - $this->addConstants($script); - - $this->addIsCodeBase($script); - - $this->addRetrieveMethods($script); - - $this->addCreateNewRootNode($script); - $this->addInsertNewRootNode($script); - $this->addMoveNodeSubTree($script); - $this->addDeleteNodeSubTree($script); - - $this->addBuildFamilyCriteria($script); - $this->addBuildTree($script); - - $this->addPopulateNodes($script); - - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - - protected function addConstants(&$script) - { - $table = $this->getTable(); - - $npath_colname = ''; - $npath_phpname = ''; - $npath_len = 0; - $npath_sep = ''; - foreach ($table->getColumns() as $col) { - if ($col->isNodeKey()) { - $npath_colname = $table->getName() . '.' . strtoupper($col->getName()); - $npath_phpname = $col->getPhpName(); - $npath_len = $col->getSize(); - $npath_sep = $col->getNodeKeySep(); - break; - } - } - $script .= " - const NPATH_COLNAME = '$npath_colname'; - const NPATH_PHPNAME = '$npath_phpname'; - const NPATH_SEP = '$npath_sep'; - const NPATH_LEN = $npath_len; -"; - } - - - protected function addIsCodeBase(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Temp function for CodeBase hacks that will go away. - */ - public static function isCodeBase(\$con = null) - { - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME); - - return (get_class(\$con) == 'ODBCConnection' && - get_class(\$con->getAdapter()) == 'CodeBaseAdapter'); - } -"; - } - - - protected function addCreateNewRootNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Create a new Node at the top of tree. This method will destroy any - * existing root node (along with its children). - * - * Use at your own risk! - * - * @param $objectClassname Object wrapped by new node. - * @param PropelPDO Connection to use. - * @return $nodeObjectClassname - * @throws PropelException - */ - public static function createNewRootNode(\$obj, PropelPDO \$con = null) - { - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - - \$con->beginTransaction(); - - try { - self::deleteNodeSubTree('1', \$con); - - \$setNodePath = 'set' . self::NPATH_PHPNAME; - - \$obj->\$setNodePath('1'); - \$obj->save(\$con); - - \$con->commit(); - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - } - - return new $nodeObjectClassname(\$obj); - } -"; - } - - protected function addInsertNewRootNode(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Inserts a new Node at the top of tree. Any existing root node (along with - * its children) will be made a child of the new root node. This is a - * safer alternative to createNewRootNode(). - * - * @param $objectClassname Object wrapped by new node. - * @param PropelPDO Connection to use. - * @return $nodeObjectClassname - * @throws PropelException - */ - public static function insertNewRootNode(\$obj, PropelPDO \$con = null) - { - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - - \$con->beginTransaction(); - try { - // Move root tree to an invalid node path. - $nodePeerClassname::moveNodeSubTree('1', '0', \$con); - - \$setNodePath = 'set' . self::NPATH_PHPNAME; - - // Insert the new root node. - \$obj->\$setNodePath('1'); - \$obj->save(\$con); - - // Move the old root tree as a child of the new root. - $nodePeerClassname::moveNodeSubTree('0', '1' . self::NPATH_SEP . '1', \$con); - - \$con->commit(); - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - } - - return new $nodeObjectClassname(\$obj); - } -"; - } - - /** - * Adds the methods for retrieving nodes. - */ - protected function addRetrieveMethods(&$script) - { - $this->addRetrieveNodes($script); - $this->addRetrieveNodeByPK($script); - $this->addRetrieveNodeByNP($script); - $this->addRetrieveRootNode($script); - - } - - protected function addRetrieveNodes(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - - $script .= " - /** - * Retrieves an array of tree nodes based on specified criteria. Optionally - * includes all parent and/or child nodes of the matching nodes. - * - * @param Criteria Criteria to use. - * @param boolean True if ancestors should also be retrieved. - * @param boolean True if descendants should also be retrieved. - * @param PropelPDO Connection to use. - * @return array Array of root nodes. - */ - public static function retrieveNodes(\$criteria, \$ancestors = false, \$descendants = false, PropelPDO \$con = null) - { - \$criteria = $nodePeerClassname::buildFamilyCriteria(\$criteria, \$ancestors, \$descendants); - \$stmt = ".$this->getStubPeerBuilder()->getClassname()."::doSelectStmt(\$criteria, \$con); - return self::populateNodes(\$stmt, \$criteria); - } -"; - } - - protected function addRetrieveNodeByPK(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Retrieves a tree node based on a primary key. Optionally includes all - * parent and/or child nodes of the matching node. - * - * @param mixed $objectClassname primary key (array for composite keys) - * @param boolean True if ancestors should also be retrieved. - * @param boolean True if descendants should also be retrieved. - * @param PropelPDO Connection to use. - * @return $nodeObjectClassname - */ - public static function retrieveNodeByPK(\$pk, \$ancestors = false, \$descendants = false, PropelPDO \$con = null) - { - throw new PropelException('retrieveNodeByPK() not implemented yet.'); - } -"; - } - - protected function addRetrieveNodeByNP(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Retrieves a tree node based on a node path. Optionally includes all - * parent and/or child nodes of the matching node. - * - * @param string Node path to retrieve. - * @param boolean True if ancestors should also be retrieved. - * @param boolean True if descendants should also be retrieved. - * @param PropelPDO Connection to use. - * @return $objectClassname - */ - public static function retrieveNodeByNP(\$np, \$ancestors = false, \$descendants = false, PropelPDO \$con = null) - { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - \$criteria->add(self::NPATH_COLNAME, \$np, Criteria::EQUAL); - \$criteria = self::buildFamilyCriteria(\$criteria, \$ancestors, \$descendants); - \$stmt = $peerClassname::doSelectStmt(\$criteria, \$con); - \$nodes = self::populateNodes(\$stmt, \$criteria); - return (count(\$nodes) == 1 ? \$nodes[0] : null); - } -"; - } - - protected function addRetrieveRootNode(&$script) - { - $script .= " - /** - * Retrieves the root node. - * - * @param string Node path to retrieve. - * @param boolean True if descendants should also be retrieved. - * @param PropelPDO Connection to use. - * @return ".$this->getStubNodeBuilder()->getClassname()." - */ - public static function retrieveRootNode(\$descendants = false, PropelPDO \$con = null) - { - return self::retrieveNodeByNP('1', false, \$descendants, \$con); - } -"; - } - - protected function addMoveNodeSubTree(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Moves the node subtree at srcpath to the dstpath. This method is intended - * for internal use by the BaseNode object. Note that it does not check for - * preexisting nodes at the dstpath. It also does not update the node path - * of any Node objects that might currently be in memory. - * - * Use at your own risk! - * - * @param string Source node path to move (root of the src subtree). - * @param string Destination node path to move to (root of the dst subtree). - * @param PropelPDO Connection to use. - * @return void - * @throws PropelException - * @todo This is currently broken for simulated 'onCascadeDelete's. - * @todo Need to abstract the SQL better. The CONCAT sql function doesn't - * seem to be standardized (i.e. mssql), so maybe it needs to be moved - * to DBAdapter. - */ - public static function moveNodeSubTree(\$srcPath, \$dstPath, PropelPDO \$con = null) - { - if (substr(\$dstPath, 0, strlen(\$srcPath)) == \$srcPath) - throw new PropelException('Cannot move a node subtree within itself.'); - - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - - /** - * Example: - * UPDATE table - * SET npath = CONCAT('1.3', SUBSTRING(npath, 6, 74)) - * WHERE npath = '1.2.2' OR npath LIKE '1.2.2.%' - */ - - \$npath = $nodePeerClassname::NPATH_COLNAME; - //the following dot isn`t mean`t a nodeKeySeperator - \$setcol = substr(\$npath, strrpos(\$npath, '.')+1); - \$setcollen = $nodePeerClassname::NPATH_LEN; - \$db = Propel::getDb($peerClassname::DATABASE_NAME); - - // - if ($nodePeerClassname::isCodeBase(\$con)) - { - // This is a hack to get CodeBase working. It will eventually be removed. - // It is a workaround for the following CodeBase bug: - // -Prepared statement parameters cannot be embedded in SQL functions (i.e. CONCAT) - \$sql = \"UPDATE \" . $peerClassname::TABLE_NAME . \" \" . - \"SET \$setcol=\" . \$db->concatString(\"'\$dstPath'\", \$db->subString(\$npath, strlen(\$srcPath)+1, \$setcollen)) . \" \" . - \"WHERE \$npath = '\$srcPath' OR \$npath LIKE '\" . \$srcPath . $nodePeerClassname::NPATH_SEP . \"%'\"; - - \$con->executeUpdate(\$sql); - } - else - { - // - \$sql = \"UPDATE \" . $peerClassname::TABLE_NAME . \" \" . - \"SET \$setcol=\" . \$db->concatString('?', \$db->subString(\$npath, '?', '?')) . \" \" . - \"WHERE \$npath = ? OR \$npath LIKE ?\"; - - \$stmt = \$con->prepare(\$sql); - \$stmt->bindValue(1, \$dstPath); // string - \$srcPathPlus1 = strlen(\$srcPath)+1; - \$stmt->bindValue(2, \$srcPathPlus1); // int - \$stmt->bindValue(3, \$setcollen);// int - \$stmt->bindValue(4, \$srcPath);// string - \$srcPathWC = \$srcPath . $nodePeerClassname::NPATH_SEP . '%'; - \$stmt->bindValue(5, \$srcPathWC); // string - \$stmt->execute(); - // - } - } -"; - } - - protected function addDeleteNodeSubTree(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Deletes the node subtree at the specified node path from the database. - * - * @param string Node path to delete - * @param PropelPDO Connection to use. - * @return void - * @throws PropelException - * @todo This is currently broken for simulated 'onCascadeDelete's. - */ - public static function deleteNodeSubTree(\$nodePath, PropelPDO \$con = null) - { - if (\$con === null) - \$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE); - - /** - * DELETE FROM table - * WHERE npath = '1.2.2' OR npath LIKE '1.2.2.%' - */ - - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - \$criteria->add($nodePeerClassname::NPATH_COLNAME, \$nodePath, Criteria::EQUAL); - \$criteria->addOr($nodePeerClassname::NPATH_COLNAME, \$nodePath . self::NPATH_SEP . '%', Criteria::LIKE); - {$this->basePeerClassname}::doDelete(\$criteria, \$con); - } -"; - } - - protected function addBuildFamilyCriteria(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Builds the criteria needed to retrieve node ancestors and/or descendants. - * - * @param Criteria Criteria to start with - * @param boolean True if ancestors should be retrieved. - * @param boolean True if descendants should be retrieved. - * @return Criteria - */ - public static function buildFamilyCriteria(\$criteria, \$ancestors = false, \$descendants = false) - { - /* - Example SQL to retrieve nodepath '1.2.3' with both ancestors and descendants: - - SELECT L.NPATH, L.LABEL, test.NPATH, UCASE(L.NPATH) - FROM test L, test - WHERE test.NPATH='1.2.3' AND - (L.NPATH=SUBSTRING(test.NPATH, 1, LENGTH(L.NPATH)) OR - test.NPATH=SUBSTRING(L.NPATH, 1, LENGTH(test.NPATH))) - ORDER BY UCASE(L.NPATH) ASC - */ - - if (\$criteria === null) - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - - if (!\$criteria->getSelectColumns()) - $peerClassname::addSelectColumns(\$criteria); - - \$db = Propel::getDb(\$criteria->getDbName()); - - if ((\$ancestors || \$descendants) && \$criteria->size()) - { - // If we are retrieving ancestors/descendants, we need to do a - // self-join to locate them. The exception to this is if no search - // criteria is specified. In this case we're retrieving all nodes - // anyway, so there is no need to do a self-join. - - // The left-side of the self-join will contain the columns we'll - // use to build node objects (target node records along with their - // ancestors and/or descendants). The right-side of the join will - // contain the target node records specified by the initial criteria. - // These are used to match the appropriate ancestor/descendant on - // the left. - - // Specify an alias for the left-side table to use. - \$criteria->addAlias('L', $peerClassname::TABLE_NAME); - - // Make sure we have select columns to begin with. - if (!\$criteria->getSelectColumns()) - $peerClassname::addSelectColumns(\$criteria); - - // Replace any existing columns for the right-side table with the - // left-side alias. - \$selectColumns = \$criteria->getSelectColumns(); - \$criteria->clearSelectColumns(); - foreach (\$selectColumns as \$colName) - \$criteria->addSelectColumn(str_replace($peerClassname::TABLE_NAME, 'L', \$colName)); - - \$a = null; - \$d = null; - - \$npathL = $peerClassname::alias('L', $nodePeerClassname::NPATH_COLNAME); - \$npathR = $nodePeerClassname::NPATH_COLNAME; - \$npath_len = $nodePeerClassname::NPATH_LEN; - - if (\$ancestors) - { - // For ancestors, match left-side node paths which are contained - // by right-side node paths. - \$a = \$criteria->getNewCriterion(\$npathL, - \"\$npathL=\" . \$db->subString(\$npathR, 1, \$db->strLength(\$npathL), \$npath_len), - Criteria::CUSTOM); - } - - if (\$descendants) - { - // For descendants, match left-side node paths which contain - // right-side node paths. - \$d = \$criteria->getNewCriterion(\$npathR, - \"\$npathR=\" . \$db->subString(\$npathL, 1, \$db->strLength(\$npathR), \$npath_len), - Criteria::CUSTOM); - } - - if (\$a) - { - if (\$d) \$a->addOr(\$d); - \$criteria->addAnd(\$a); - } - else if (\$d) - { - \$criteria->addAnd(\$d); - } - - // Add the target node path column. This is used by populateNodes(). - \$criteria->addSelectColumn(\$npathR); - - // Sort by node path to speed up tree construction in populateNodes() - \$criteria->addAsColumn('npathlen', \$db->strLength(\$npathL)); - \$criteria->addAscendingOrderByColumn('npathlen'); - \$criteria->addAscendingOrderByColumn(\$npathL); - } - else - { - // Add the target node path column. This is used by populateNodes(). - \$criteria->addSelectColumn($nodePeerClassname::NPATH_COLNAME); - - // Sort by node path to speed up tree construction in populateNodes() - \$criteria->addAsColumn('npathlen', \$db->strLength($nodePeerClassname::NPATH_COLNAME)); - \$criteria->addAscendingOrderByColumn('npathlen'); - \$criteria->addAscendingOrderByColumn($nodePeerClassname::NPATH_COLNAME); - } - - return \$criteria; - } -"; - } - - protected function addBuildTree(&$script) - { - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * This method reconstructs as much of the tree structure as possible from - * the given array of objects. Depending on how you execute your query, it - * is possible for the ResultSet to contain multiple tree fragments (i.e. - * subtrees). The array returned by this method will contain one entry - * for each subtree root node it finds. The remaining subtree nodes are - * accessible from the $nodeObjectClassname methods of the - * subtree root nodes. - * - * @param array Array of $nodeObjectClassname objects - * @return array Array of $nodeObjectClassname objects - */ - public static function buildTree(\$nodes) - { - // Subtree root nodes to return - \$rootNodes = array(); - - // Build the tree relations - foreach (\$nodes as \$node) - { - \$sep = strrpos(\$node->getNodePath(), $nodePeerClassname::NPATH_SEP); - \$parentPath = (\$sep !== false ? substr(\$node->getNodePath(), 0, \$sep) : ''); - \$parentNode = null; - - // Scan other nodes for parent. - foreach (\$nodes as \$pnode) - { - if (\$pnode->getNodePath() === \$parentPath) - { - \$parentNode = \$pnode; - break; - } - } - - // If parent was found, attach as child, otherwise its a subtree root - if (\$parentNode) - \$parentNode->attachChildNode(\$node); - else - \$rootNodes[] = \$node; - } - - return \$rootNodes; - } -"; - } - - protected function addPopulateNodes(&$script) - { - $table = $this->getTable(); - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $objectClassname = $this->getStubObjectBuilder()->getClassname(); - - $nodePeerClassname = $this->getStubNodePeerBuilder()->getClassname(); - $nodeObjectClassname = $this->getStubNodeBuilder()->getClassname(); - - $script .= " - /** - * Populates the $objectClassname objects from the - * specified ResultSet, wraps them in $nodeObjectClassname - * objects and build the appropriate node relationships. - * The array returned by this method will only include the initial targets - * of the query, even if ancestors/descendants were also requested. - * The ancestors/descendants will be cached in memory and are accessible via - * the getNode() methods. - * - * @param PDOStatement \$stmt Executed PDOStatement - * @param Criteria - * @return array Array of $nodeObjectClassname objects. - */ - public static function populateNodes(PDOStatement \$stmt, \$criteria) - { - \$nodes = array(); - \$targets = array(); - \$targetfld = count(\$criteria->getSelectColumns()); -"; - - if (!$table->getChildrenColumn()) { - $script .= " - // set the class once to avoid overhead in the loop - \$cls = $peerClassname::getOMClass(); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - // populate the object(s) - foreach(\$stmt->fetchAll() AS \$row) - { - if (!isset(\$nodes[\$row[0]])) - { -"; - if ($table->getChildrenColumn()) { - $script .= " - // class must be set each time from the record row - \$cls = $peerClassname::getOMClass(\$row, 1); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj', '$cls') . " - \$obj->hydrate(\$row); - - \$nodes[\$row[0]] = new $nodeObjectClassname(\$obj); - } - - \$node = \$nodes[\$row[0]]; - - if (\$node->getNodePath() === \$row[\$targetfld]) - \$targets[\$node->getNodePath()] = \$node; - } - - $nodePeerClassname::buildTree(\$nodes); - - return array_values(\$targets); - } -"; - } - -} // PHP5NodePeerBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectBuilder.php deleted file mode 100644 index e77e547b8..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectBuilder.php +++ /dev/null @@ -1,4250 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5ObjectBuilder extends ObjectBuilder -{ - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - public function getNamespace() - { - if ($namespace = parent::getNamespace()) { - if ($this->getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceOm')) { - return $namespace . '\\' . $omns; - } else { - return $namespace; - } - } - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubObjectBuilder()->getUnprefixedClassname(); - } - - /** - * Validates the current table to make sure that it won't - * result in generated code that will not parse. - * - * This method may emit warnings for code which may cause problems - * and will throw exceptions for errors that will definitely cause - * problems. - */ - protected function validateModel() - { - parent::validateModel(); - - $table = $this->getTable(); - - // Check to see whether any generated foreign key names - // will conflict with column names. - - $colPhpNames = array(); - $fkPhpNames = array(); - - foreach ($table->getColumns() as $col) { - $colPhpNames[] = $col->getPhpName(); - } - - foreach ($table->getForeignKeys() as $fk) { - $fkPhpNames[] = $this->getFKPhpNameAffix($fk, $plural = false); - } - - $intersect = array_intersect($colPhpNames, $fkPhpNames); - if (!empty($intersect)) { - throw new EngineException("One or more of your column names for [" . $table->getName() . "] table conflict with foreign key names (" . implode(", ", $intersect) . ")"); - } - - // Check foreign keys to see if there are any foreign keys that - // are also matched with an inversed referencing foreign key - // (this is currently unsupported behavior) - // see: http://propel.phpdb.org/trac/ticket/549 - - foreach ($table->getForeignKeys() as $fk) { - if ($fk->isMatchedByInverseFK()) { - throw new EngineException("The 1:1 relationship expressed by foreign key " . $fk->getName() . " is defined in both directions; Propel does not currently support this (if you must have both foreign key constraints, consider adding this constraint with a custom SQL file.)" ); - } - } - } - - /** - * Returns the appropriate formatter (from platform) for a date/time column. - * @param Column $col - * @return string - */ - protected function getTemporalFormatter(Column $col) - { - $fmt = null; - if ($col->getType() === PropelTypes::DATE) { - $fmt = $this->getPlatform()->getDateFormatter(); - } elseif ($col->getType() === PropelTypes::TIME) { - $fmt = $this->getPlatform()->getTimeFormatter(); - } elseif ($col->getType() === PropelTypes::TIMESTAMP) { - $fmt = $this->getPlatform()->getTimestampFormatter(); - } - return $fmt; - } - - /** - * Returns the type-casted and stringified default value for the specified Column. - * This only works for scalar default values currently. - * @return string The default value or 'NULL' if there is none. - */ - protected function getDefaultValueString(Column $col) - { - $defaultValue = var_export(null, true); - if (($val = $col->getPhpDefaultValue()) !== null) { - if ($col->isTemporalType()) { - $fmt = $this->getTemporalFormatter($col); - try { - if (!($this->getPlatform() instanceof MysqlPlatform && - ($val === '0000-00-00 00:00:00' || $val === '0000-00-00'))) { - // while technically this is not a default value of NULL, - // this seems to be closest in meaning. - $defDt = new DateTime($val); - $defaultValue = var_export($defDt->format($fmt), true); - } - } catch (Exception $x) { - // prevent endless loop when timezone is undefined - date_default_timezone_set('America/Los_Angeles'); - throw new EngineException("Unable to parse default temporal value for " . $col->getFullyQualifiedName() . ": " .$this->getDefaultValueString($col), $x); - } - } else { - if ($col->isPhpPrimitiveType()) { - settype($val, $col->getPhpType()); - $defaultValue = var_export($val, true); - } elseif ($col->isPhpObjectType()) { - $defaultValue = 'new '.$col->getPhpType().'(' . var_export($val, true) . ')'; - } else { - throw new EngineException("Cannot get default value string for " . $col->getFullyQualifiedName()); - } - } - } - return $defaultValue; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - $interface = $this->getInterface(); - $parentClass = $this->getBehaviorContent('parentClass'); - $parentClass = (null !== $parentClass) ? $parentClass : ClassTools::classname($this->getBaseClass()); - $script .= " -/** - * Base class that represents a row from the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." extends ".$parentClass." "; - - $interface = ClassTools::getInterface($table); - if ($interface) { - $script .= " implements " . ClassTools::classname($interface); - } - if ($this->getTable()->getInterface()) { - $this->declareClassFromBuilder($this->getInterfaceBuilder()); - } - - $script .= " -{ -"; - } - - /** - * Specifies the methods that are added as part of the basic OM class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $this->declareClassFromBuilder($this->getStubPeerBuilder()); - $this->declareClassFromBuilder($this->getStubQueryBuilder()); - $this->declareClasses('Propel', 'PropelException', 'PDO', 'PropelPDO', 'Criteria', 'BaseObject', 'Persistent', 'BasePeer', 'PropelObjectcollection'); - - $table = $this->getTable(); - if (!$table->isAlias()) { - $this->addConstants($script); - $this->addAttributes($script); - } - - if ($this->hasDefaultValues()) { - $this->addApplyDefaultValues($script); - $this->addConstructor($script); - } - - $this->addColumnAccessorMethods($script); - $this->addColumnMutatorMethods($script); - - $this->addHasOnlyDefaultValues($script); - - $this->addHydrate($script); - $this->addEnsureConsistency($script); - - if (!$table->isReadOnly()) { - $this->addManipulationMethods($script); - } - - if ($this->isAddValidateMethod()) { - $this->addValidationMethods($script); - } - - if ($this->isAddGenericAccessors()) { - $this->addGetByName($script); - $this->addGetByPosition($script); - $this->addToArray($script); - } - - if ($this->isAddGenericMutators()) { - $this->addSetByName($script); - $this->addSetByPosition($script); - $this->addFromArray($script); - } - - $this->addBuildCriteria($script); - $this->addBuildPkeyCriteria($script); - $this->addGetPrimaryKey($script); - $this->addSetPrimaryKey($script); - $this->addIsPrimaryKeyNull($script); - - $this->addCopy($script); - - if (!$table->isAlias()) { - $this->addGetPeer($script); - } - - $this->addFKMethods($script); - $this->addRefFKMethods($script); - $this->addCrossFKMethods($script); - $this->addClear($script); - $this->addClearAllReferences($script); - - $this->addPrimaryString($script); - - // apply behaviors - $this->applyBehaviorModifier('objectMethods', $script, " "); - - $this->addMagicCall($script); - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('objectFilter', $script, ""); - } - - /** - * Adds any constants to the class. - * @param string &$script The script will be modified in this method. - */ - protected function addConstants(&$script) - { - $script .= " - /** - * Peer class name - */ - const PEER = '" . addslashes($this->getStubPeerBuilder()->getFullyQualifiedClassname()) . "'; -"; - } - - /** - * Adds class attributes. - * @param string &$script The script will be modified in this method. - */ - protected function addAttributes(&$script) - { - $table = $this->getTable(); - - $script .= " - /** - * The Peer class. - * Instance provides a convenient way of calling static methods on a class - * that calling code may not be able to identify. - * @var ".$this->getPeerClassname()." - */ - protected static \$peer; -"; - if (!$table->isAlias()) { - $this->addColumnAttributes($script); - } - - foreach ($table->getForeignKeys() as $fk) { - $this->addFKAttributes($script, $fk); - } - - foreach ($table->getReferrers() as $refFK) { - $this->addRefFKAttributes($script, $refFK); - } - - // many-to-many relationships - foreach ($table->getCrossFks() as $fkList) { - $crossFK = $fkList[1]; - $this->addCrossFKAttributes($script, $crossFK); - } - - - $this->addAlreadyInSaveAttribute($script); - $this->addAlreadyInValidationAttribute($script); - - // apply behaviors - $this->applyBehaviorModifier('objectAttributes', $script, " "); - } - - /** - * Adds variables that store column values. - * @param string &$script The script will be modified in this method. - * @see addColumnNameConstants() - */ - protected function addColumnAttributes(&$script) - { - - $table = $this->getTable(); - - foreach ($table->getColumns() as $col) { - $this->addColumnAttributeComment($script, $col); - $this->addColumnAttributeDeclaration($script, $col); - if ($col->isLazyLoad() ) { - $this->addColumnAttributeLoaderComment($script, $col); - $this->addColumnAttributeLoaderDeclaration($script, $col); - } - } - } - - /** - * Add comment about the attribute (variable) that stores column values - * @param string &$script The script will be modified in this method. - * @param Column $col - **/ - protected function addColumnAttributeComment(&$script, Column $col) - { - $cptype = $col->getPhpType(); - $clo = strtolower($col->getName()); - - $script .= " - /** - * The value for the $clo field."; - if ($col->getDefaultValue()) { - if ($col->getDefaultValue()->isExpression()) { - $script .= " - * Note: this column has a database default value of: (expression) ".$col->getDefaultValue()->getValue(); - } else { - $script .= " - * Note: this column has a database default value of: ". $this->getDefaultValueString($col); - } - } - $script .= " - * @var $cptype - */"; - } - - /** - * Adds the declaration of a column value storage attribute - * @param string &$script The script will be modified in this method. - * @param Column $col - **/ - protected function addColumnAttributeDeclaration(&$script, Column $col) - { - $clo = strtolower($col->getName()); - $script .= " - protected \$" . $clo . "; -"; - } - - /** - * Adds the comment about the attribute keeping track if an attribute value has been loaded - * @param string &$script The script will be modified in this method. - * @param Column $col - **/ - protected function addColumnAttributeLoaderComment(&$script, Column $col) - { - $clo = strtolower($col->getName()); - $script .= " - /** - * Whether the lazy-loaded \$$clo value has been loaded from database. - * This is necessary to avoid repeated lookups if \$$clo column is NULL in the db. - * @var boolean - */"; - } - - /** - * Adds the declaration of the attribute keeping track of an attribute's loaded state - * @param string &$script The script will be modified in this method. - * @param Column $col - **/ - protected function addColumnAttributeLoaderDeclaration(&$script, Column $col) - { - $clo = strtolower($col->getName()); - $script .= " - protected \$".$clo."_isLoaded = false; -"; - } - - /** - * Adds the getPeer() method. - * This is a convenient, non introspective way of getting the Peer class for a particular object. - * @param string &$script The script will be modified in this method. - */ - protected function addGetPeer(&$script) - { - $this->addGetPeerComment($script); - $this->addGetPeerFunctionOpen($script); - $this->addGetPeerFunctionBody($script); - $this->addGetPeerFunctionClose($script); - } - - /** - * Add the comment for the getPeer method - * @param string &$script The script will be modified in this method. - **/ - protected function addGetPeerComment(&$script) { - $script .= " - /** - * Returns a peer instance associated with this om. - * - * Since Peer classes are not to have any instance attributes, this method returns the - * same instance for all member of this class. The method could therefore - * be static, but this would prevent one from overriding the behavior. - * - * @return ".$this->getPeerClassname()." - */"; - } - - /** - * Adds the function declaration (function opening) for the getPeer method - * @param string &$script The script will be modified in this method. - **/ - protected function addGetPeerFunctionOpen(&$script) { - $script .= " - public function getPeer() - {"; - } - - /** - * Adds the body of the getPeer method - * @param string &$script The script will be modified in this method. - **/ - protected function addGetPeerFunctionBody(&$script) { - $script .= " - if (self::\$peer === null) { - " . $this->buildObjectInstanceCreationCode('self::$peer', $this->getPeerClassname()) . " - } - return self::\$peer;"; - } - - /** - * Add the function close for the getPeer method - * Note: this is just a } and the body ends with a return statement, so it's quite useless. But it's here anyway for consisency, cause there's a close function for all functions and in some other instances, they are useful - * @param string &$script The script will be modified in this method. - **/ - protected function addGetPeerFunctionClose(&$script) { - $script .= " - } -"; - } - - /** - * Adds the constructor for this object. - * @param string &$script The script will be modified in this method. - * @see addConstructor() - */ - protected function addConstructor(&$script) - { - $this->addConstructorComment($script); - $this->addConstructorOpen($script); - $this->addConstructorBody($script); - $this->addConstructorClose($script); - } - - /** - * Adds the comment for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorComment(&$script) { - $script .= " - /** - * Initializes internal state of ".$this->getClassname()." object. - * @see applyDefaults() - */"; - } - - /** - * Adds the function declaration for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorOpen(&$script) { - $script .= " - public function __construct() - {"; - } - - /** - * Adds the function body for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorBody(&$script) { - $script .= " - parent::__construct(); - \$this->applyDefaultValues();"; - } - - /** - * Adds the function close for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorClose(&$script) { - $script .= " - } -"; - } - - /** - * Adds the applyDefaults() method, which is called from the constructor. - * @param string &$script The script will be modified in this method. - * @see addConstructor() - */ - protected function addApplyDefaultValues(&$script) - { - $this->addApplyDefaultValuesComment($script); - $this->addApplyDefaultValuesOpen($script); - $this->addApplyDefaultValuesBody($script); - $this->addApplyDefaultValuesClose($script); - } - - /** - * Adds the comment for the applyDefaults method - * @param string &$script The script will be modified in this method. - * @see addApplyDefaultValues() - **/ - protected function addApplyDefaultValuesComment(&$script) { - $script .= " - /** - * Applies default values to this object. - * This method should be called from the object's constructor (or - * equivalent initialization method). - * @see __construct() - */"; - } - - /** - * Adds the function declaration for the applyDefaults method - * @param string &$script The script will be modified in this method. - * @see addApplyDefaultValues() - **/ - protected function addApplyDefaultValuesOpen(&$script) { - $script .= " - public function applyDefaultValues() - {"; - } - - /** - * Adds the function body of the applyDefault method - * @param string &$script The script will be modified in this method. - * @see addApplyDefaultValues() - **/ - protected function addApplyDefaultValuesBody(&$script) { - $table = $this->getTable(); - // FIXME - Apply support for PHP default expressions here - // see: http://propel.phpdb.org/trac/ticket/378 - - $colsWithDefaults = array(); - foreach ($table->getColumns() as $col) { - $def = $col->getDefaultValue(); - if ($def !== null && !$def->isExpression()) { - $colsWithDefaults[] = $col; - } - } - - $colconsts = array(); - foreach ($colsWithDefaults as $col) { - $clo = strtolower($col->getName()); - $script .= " - \$this->".$clo." = ".$this->getDefaultValueString($col).";"; - - } - } - - - /** - * Adds the function close for the applyDefaults method - * @param string &$script The script will be modified in this method. - * @see addApplyDefaultValues() - **/ - protected function addApplyDefaultValuesClose(&$script) { - $script .= " - } -"; - } - - // -------------------------------------------------------------- - // - // A C C E S S O R M E T H O D S - // - // -------------------------------------------------------------- - - /** - * Adds a date/time/timestamp getter method. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnAccessors() - */ - protected function addTemporalAccessor(&$script, Column $col) - { - $this->addTemporalAccessorComment($script, $col); - $this->addTemporalAccessorOpen($script, $col); - $this->addTemporalAccessorBody($script, $col); - $this->addTemporalAccessorClose($script, $col); - } // addTemporalAccessor - - - /** - * Adds the comment for a temporal accessor - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addTemporalAccessor - **/ - protected function addTemporalAccessorComment(&$script, Column $col) { - $clo = strtolower($col->getName()); - $useDateTime = $this->getBuildProperty('useDateTimeClass'); - - $dateTimeClass = $this->getBuildProperty('dateTimeClass'); - if (!$dateTimeClass) { - $dateTimeClass = 'DateTime'; - } - - $handleMysqlDate = false; - if ($this->getPlatform() instanceof MysqlPlatform) { - if ($col->getType() === PropelTypes::TIMESTAMP) { - $handleMysqlDate = true; - $mysqlInvalidDateString = '0000-00-00 00:00:00'; - } elseif ($col->getType() === PropelTypes::DATE) { - $handleMysqlDate = true; - $mysqlInvalidDateString = '0000-00-00'; - } - // 00:00:00 is a valid time, so no need to check for that. - } - - $script .= " - /** - * Get the [optionally formatted] temporal [$clo] column value. - * ".$col->getDescription(); - if (!$useDateTime) { - $script .= " - * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass - * option in order to avoid converstions to integers (which are limited in the dates they can express)."; - } - $script .= " - * - * @param string \$format The date/time format string (either date()-style or strftime()-style). - * If format is NULL, then the raw ".($useDateTime ? 'DateTime object' : 'unix timestamp integer')." will be returned."; - if ($useDateTime) { - $script .= " - * @return mixed Formatted date/time value as string or $dateTimeClass object (if format is NULL), NULL if column is NULL" .($handleMysqlDate ? ', and 0 if column value is ' . $mysqlInvalidDateString : ''); - } else { - $script .= " - * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL".($handleMysqlDate ? ', and 0 if column value is ' . $mysqlInvalidDateString : ''); - } - $script .= " - * @throws PropelException - if unable to parse/validate the date/time value. - */"; - } - - - /** - * Adds the function declaration for a temporal accessor - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addTemporalAccessor - **/ - protected function addTemporalAccessorOpen(&$script, Column $col) { - $cfc = $col->getPhpName(); - - $defaultfmt = null; - $visibility = $col->getAccessorVisibility(); - - // Default date/time formatter strings are specified in build.properties - if ($col->getType() === PropelTypes::DATE) { - $defaultfmt = $this->getBuildProperty('defaultDateFormat'); - } elseif ($col->getType() === PropelTypes::TIME) { - $defaultfmt = $this->getBuildProperty('defaultTimeFormat'); - } elseif ($col->getType() === PropelTypes::TIMESTAMP) { - $defaultfmt = $this->getBuildProperty('defaultTimeStampFormat'); - } - if (empty($defaultfmt)) { $defaultfmt = null; } - - $script .= " - ".$visibility." function get$cfc(\$format = ".var_export($defaultfmt, true).""; - if ($col->isLazyLoad()) $script .= ", \$con = null"; - $script .= ") - {"; - } - - /** - * Adds the body of the temporal accessor - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addTemporalAccessor - **/ - protected function addTemporalAccessorBody(&$script, Column $col) { - $cfc = $col->getPhpName(); - $clo = strtolower($col->getName()); - - $useDateTime = $this->getBuildProperty('useDateTimeClass'); - - $dateTimeClass = $this->getBuildProperty('dateTimeClass'); - if (!$dateTimeClass) { - $dateTimeClass = 'DateTime'; - } - - $defaultfmt = null; - - // Default date/time formatter strings are specified in build.properties - if ($col->getType() === PropelTypes::DATE) { - $defaultfmt = $this->getBuildProperty('defaultDateFormat'); - } elseif ($col->getType() === PropelTypes::TIME) { - $defaultfmt = $this->getBuildProperty('defaultTimeFormat'); - } elseif ($col->getType() === PropelTypes::TIMESTAMP) { - $defaultfmt = $this->getBuildProperty('defaultTimeStampFormat'); - } - if (empty($defaultfmt)) { $defaultfmt = null; } - - $handleMysqlDate = false; - if ($this->getPlatform() instanceof MysqlPlatform) { - if ($col->getType() === PropelTypes::TIMESTAMP) { - $handleMysqlDate = true; - $mysqlInvalidDateString = '0000-00-00 00:00:00'; - } elseif ($col->getType() === PropelTypes::DATE) { - $handleMysqlDate = true; - $mysqlInvalidDateString = '0000-00-00'; - } - // 00:00:00 is a valid time, so no need to check for that. - } - - if ($col->isLazyLoad()) { - $script .= " - if (!\$this->".$clo."_isLoaded && \$this->$clo === null && !\$this->isNew()) { - \$this->load$cfc(\$con); - } -"; - } - $script .= " - if (\$this->$clo === null) { - return null; - } - -"; - if ($handleMysqlDate) { - $script .= " - if (\$this->$clo === '$mysqlInvalidDateString') { - // while technically this is not a default value of NULL, - // this seems to be closest in meaning. - return null; - } else { - try { - \$dt = new $dateTimeClass(\$this->$clo); - } catch (Exception \$x) { - throw new PropelException(\"Internally stored date/time/timestamp value could not be converted to $dateTimeClass: \" . var_export(\$this->$clo, true), \$x); - } - } -"; - } else { - $script .= " - - try { - \$dt = new $dateTimeClass(\$this->$clo); - } catch (Exception \$x) { - throw new PropelException(\"Internally stored date/time/timestamp value could not be converted to $dateTimeClass: \" . var_export(\$this->$clo, true), \$x); - } -"; - } // if handleMyqlDate - - $script .= " - if (\$format === null) {"; - if ($useDateTime) { - $script .= " - // Because propel.useDateTimeClass is TRUE, we return a $dateTimeClass object. - return \$dt;"; - } else { - $script .= " - // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. - return (int) \$dt->format('U');"; - } - $script .= " - } elseif (strpos(\$format, '%') !== false) { - return strftime(\$format, \$dt->format('U')); - } else { - return \$dt->format(\$format); - }"; - } - - - /** - * Adds the body of the temporal accessor - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addTemporalAccessorClose - **/ - protected function addTemporalAccessorClose(&$script, Column $col) { - $script .= " - } -"; - } - - /** - * Adds a normal (non-temporal) getter method. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnAccessors() - */ - protected function addDefaultAccessor(&$script, Column $col) - { - $this->addDefaultAccessorComment($script, $col); - $this->addDefaultAccessorOpen($script, $col); - $this->addDefaultAccessorBody($script, $col); - $this->addDefaultAccessorClose($script, $col); - } - - /** - * Add the comment for a default accessor method (a getter) - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addDefaultAccessor() - **/ - protected function addDefaultAccessorComment(&$script, Column $col) { - $clo=strtolower($col->getName()); - - $script .= " - /** - * Get the [$clo] column value. - * ".$col->getDescription(); - if ($col->isLazyLoad()) { - $script .= " - * @param PropelPDO An optional PropelPDO connection to use for fetching this lazy-loaded column."; - } - $script .= " - * @return ".$col->getPhpType()." - */"; - } - - /** - * Adds the function declaration for a default accessor - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addDefaultAccessor() - **/ - protected function addDefaultAccessorOpen(&$script, Column $col) { - $cfc = $col->getPhpName(); - $visibility = $col->getAccessorVisibility(); - - $script .= " - ".$visibility." function get$cfc("; - if ($col->isLazyLoad()) $script .= "PropelPDO \$con = null"; - $script .= ") - {"; - } - - /** - * Adds the function body for a default accessor method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addDefaultAccessor() - **/ - protected function addDefaultAccessorBody(&$script, Column $col) { - $cfc = $col->getPhpName(); - $clo = strtolower($col->getName()); - if ($col->isLazyLoad()) { - $script .= " - if (!\$this->".$clo."_isLoaded && \$this->$clo === null && !\$this->isNew()) { - \$this->load$cfc(\$con); - } -"; - } - - $script .= " - return \$this->$clo;"; - } - - /** - * Adds the function close for a default accessor method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addDefaultAccessor() - **/ - protected function addDefaultAccessorClose(&$script, Column $col) { - $script .= " - } -"; - } - - /** - * Adds the lazy loader method. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnAccessors() - */ - protected function addLazyLoader(&$script, Column $col) - { - $this->addLazyLoaderComment($script, $col); - $this->addLazyLoaderOpen($script, $col); - $this->addLazyLoaderBody($script, $col); - $this->addLazyLoaderClose($script, $col); - } - - /** - * Adds the comment for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderComment(&$script, Column $col) { - $clo = strtolower($col->getName()); - - $script .= " - /** - * Load the value for the lazy-loaded [$clo] column. - * - * This method performs an additional query to return the value for - * the [$clo] column, since it is not populated by - * the hydrate() method. - * - * @param \$con PropelPDO (optional) The PropelPDO connection to use. - * @return void - * @throws PropelException - any underlying error will be wrapped and re-thrown. - */"; - } - - /** - * Adds the function declaration for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderOpen(&$script, Column $col) { - $cfc = $col->getPhpName(); - $script .= " - protected function load$cfc(PropelPDO \$con = null) - {"; - } - - /** - * Adds the function body for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderBody(&$script, Column $col) { - $platform = $this->getPlatform(); - $clo = strtolower($col->getName()); - - $script .= " - \$c = \$this->buildPkeyCriteria(); - \$c->addSelectColumn(".$this->getColumnConstant($col)."); - try { - \$stmt = ".$this->getPeerClassname()."::doSelectStmt(\$c, \$con); - \$row = \$stmt->fetch(PDO::FETCH_NUM); - \$stmt->closeCursor();"; - - if ($col->getType() === PropelTypes::CLOB && $this->getPlatform() instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[0]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { - $script .= " - if (\$row[0] !== null) { - \$this->$clo = fopen('php://memory', 'r+'); - fwrite(\$this->$clo, \$row[0]); - rewind(\$this->$clo); - } else { - \$this->$clo = null; - }"; - } elseif ($col->isPhpPrimitiveType()) { - $script .= " - \$this->$clo = (\$row[0] !== null) ? (".$col->getPhpType().") \$row[0] : null;"; - } elseif ($col->isPhpObjectType()) { - $script .= " - \$this->$clo = (\$row[0] !== null) ? new ".$col->getPhpType()."(\$row[0]) : null;"; - } else { - $script .= " - \$this->$clo = \$row[0];"; - } - - $script .= " - \$this->".$clo."_isLoaded = true; - } catch (Exception \$e) { - throw new PropelException(\"Error loading value for [$clo] column on demand.\", \$e); - }"; - } - - /** - * Adds the function close for the lazy loader - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderClose(&$script, Column $col) { - $script .= " - }"; - } // addLazyLoader() - - // -------------------------------------------------------------- - // - // M U T A T O R M E T H O D S - // - // -------------------------------------------------------------- - - /** - * Adds the open of the mutator (setter) method for a column. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - */ - protected function addMutatorOpen(&$script, Column $col) - { - $this->addMutatorComment($script, $col); - $this->addMutatorOpenOpen($script, $col); - $this->addMutatorOpenBody($script, $col); - } - - /** - * Adds the comment for a mutator - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addMutatorOpen() - **/ - protected function addMutatorComment(&$script, Column $col) { - $clo = strtolower($col->getName()); - $script .= " - /** - * Set the value of [$clo] column. - * ".$col->getDescription()." - * @param ".$col->getPhpType()." \$v new value - * @return ".$this->getObjectClassname()." The current object (for fluent API support) - */"; - } - - /** - * Adds the mutator function declaration - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addMutatorOpen() - **/ - protected function addMutatorOpenOpen(&$script, Column $col) { - $cfc = $col->getPhpName(); - $visibility = $col->getMutatorVisibility(); - - $script .= " - ".$visibility." function set$cfc(\$v) - {"; - } - - /** - * Adds the mutator open body part - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addMutatorOpen() - **/ - protected function addMutatorOpenBody(&$script, Column $col) { - $clo = strtolower($col->getName()); - $cfc = $col->getPhpName(); - if ($col->isLazyLoad()) { - $script .= " - // explicitly set the is-loaded flag to true for this lazy load col; - // it doesn't matter if the value is actually set or not (logic below) as - // any attempt to set the value means that no db lookup should be performed - // when the get$cfc() method is called. - \$this->".$clo."_isLoaded = true; -"; - } - } - - /** - * Adds the close of the mutator (setter) method for a column. - * - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - */ - protected function addMutatorClose(&$script, Column $col) - { - $this->addMutatorCloseBody($script, $col); - $this->addMutatorCloseClose($script, $col); - } - - /** - * Adds the body of the close part of a mutator - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addMutatorClose() - **/ - protected function addMutatorCloseBody(&$script, Column $col) { - $table = $this->getTable(); - $cfc = $col->getPhpName(); - $clo = strtolower($col->getName()); - - if ($col->isForeignKey()) { - - foreach ($col->getForeignKeys() as $fk) { - - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - $colFK = $tblFK->getColumn($fk->getMappedForeignColumn($col->getName())); - - $varName = $this->getFKVarName($fk); - - $script .= " - if (\$this->$varName !== null && \$this->".$varName."->get".$colFK->getPhpName()."() !== \$v) { - \$this->$varName = null; - } -"; - } // foreach fk - } /* if col is foreign key */ - - foreach ($col->getReferrers() as $refFK) { - - $tblFK = $this->getDatabase()->getTable($refFK->getForeignTableName()); - - if ( $tblFK->getName() != $table->getName() ) { - - foreach ($col->getForeignKeys() as $fk) { - - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - $colFK = $tblFK->getColumn($fk->getMappedForeignColumn($col->getName())); - - if ($refFK->isLocalPrimaryKey()) { - $varName = $this->getPKRefFKVarName($refFK); - $script .= " - // update associated ".$tblFK->getPhpName()." - if (\$this->$varName !== null) { - \$this->{$varName}->set".$colFK->getPhpName()."(\$v); - } -"; - } else { - $collName = $this->getRefFKCollVarName($refFK); - $script .= " - - // update associated ".$tblFK->getPhpName()." - if (\$this->$collName !== null) { - foreach (\$this->$collName as \$referrerObject) { - \$referrerObject->set".$colFK->getPhpName()."(\$v); - } - } -"; - } // if (isLocalPrimaryKey - } // foreach col->getPrimaryKeys() - } // if tablFk != table - - } // foreach - } - - /** - * Adds the close for the mutator close - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addMutatorClose() - **/ - protected function addMutatorCloseClose(&$script, Column $col) { - $cfc = $col->getPhpName(); - $script .= " - return \$this; - } // set$cfc() -"; - } - - /** - * Adds a setter for BLOB columns. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnMutators() - */ - protected function addLobMutator(&$script, Column $col) - { - $this->addMutatorOpen($script, $col); - $clo = strtolower($col->getName()); - $script .= " - // Because BLOB columns are streams in PDO we have to assume that they are - // always modified when a new value is passed in. For example, the contents - // of the stream itself may have changed externally. - if (!is_resource(\$v) && \$v !== null) { - \$this->$clo = fopen('php://memory', 'r+'); - fwrite(\$this->$clo, \$v); - rewind(\$this->$clo); - } else { // it's already a stream - \$this->$clo = \$v; - } - \$this->modifiedColumns[] = ".$this->getColumnConstant($col)."; -"; - $this->addMutatorClose($script, $col); - } // addLobMutatorSnippet - - /** - * Adds a setter method for date/time/timestamp columns. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnMutators() - */ - protected function addTemporalMutator(&$script, Column $col) - { - $cfc = $col->getPhpName(); - $clo = strtolower($col->getName()); - $visibility = $col->getMutatorVisibility(); - - $dateTimeClass = $this->getBuildProperty('dateTimeClass'); - if (!$dateTimeClass) { - $dateTimeClass = 'DateTime'; - } - - $script .= " - /** - * Sets the value of [$clo] column to a normalized version of the date/time value specified. - * ".$col->getDescription()." - * @param mixed \$v string, integer (timestamp), or DateTime value. Empty string will - * be treated as NULL for temporal objects. - * @return ".$this->getObjectClassname()." The current object (for fluent API support) - */ - ".$visibility." function set$cfc(\$v) - {"; - if ($col->isLazyLoad()) { - $script .= " - // explicitly set the is-loaded flag to true for this lazy load col; - // it doesn't matter if the value is actually set or not (logic below) as - // any attempt to set the value means that no db lookup should be performed - // when the get$cfc() method is called. - \$this->".$clo."_isLoaded = true; -"; - } - - $fmt = var_export($this->getTemporalFormatter($col), true); - - $script .= " - // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') - // -- which is unexpected, to say the least. - if (\$v === null || \$v === '') { - \$dt = null; - } elseif (\$v instanceof DateTime) { - \$dt = \$v; - } else { - // some string/numeric value passed; we normalize that so that we can - // validate it. - try { - if (is_numeric(\$v)) { // if it's a unix timestamp - \$dt = new $dateTimeClass('@'.\$v, new DateTimeZone('UTC')); - // We have to explicitly specify and then change the time zone because of a - // DateTime bug: http://bugs.php.net/bug.php?id=43003 - \$dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); - } else { - \$dt = new $dateTimeClass(\$v); - } - } catch (Exception \$x) { - throw new PropelException('Error parsing date/time value: ' . var_export(\$v, true), \$x); - } - } - - if ( \$this->$clo !== null || \$dt !== null ) { - // (nested ifs are a little easier to read in this case) - - \$currNorm = (\$this->$clo !== null && \$tmpDt = new $dateTimeClass(\$this->$clo)) ? \$tmpDt->format($fmt) : null; - \$newNorm = (\$dt !== null) ? \$dt->format($fmt) : null; - - if ( (\$currNorm !== \$newNorm) // normalized values don't match "; - - if (($def = $col->getDefaultValue()) !== null && !$def->isExpression()) { - $defaultValue = $this->getDefaultValueString($col); - $script .= " - || (\$dt->format($fmt) === $defaultValue) // or the entered value matches the default"; - } - - $script .= " - ) - { - \$this->$clo = (\$dt ? \$dt->format($fmt) : null); - \$this->modifiedColumns[] = ".$this->getColumnConstant($col)."; - } - } // if either are not null -"; - $this->addMutatorClose($script, $col); - } - - /** - * Adds setter method for "normal" columns. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnMutators() - */ - protected function addDefaultMutator(&$script, Column $col) - { - $clo = strtolower($col->getName()); - - $this->addMutatorOpen($script, $col); - - // Perform type-casting to ensure that we can use type-sensitive - // checking in mutators. - if ($col->isPhpPrimitiveType()) { - $script .= " - if (\$v !== null) { - \$v = (".$col->getPhpType().") \$v; - } -"; - } - - $script .= " - if (\$this->$clo !== \$v"; - if (($def = $col->getDefaultValue()) !== null && !$def->isExpression()) { - $script .= " || \$this->isNew()"; - } - $script .= ") { - \$this->$clo = \$v; - \$this->modifiedColumns[] = ".$this->getColumnConstant($col)."; - } -"; - $this->addMutatorClose($script, $col); - } - - /** - * Adds the hasOnlyDefaultValues() method. - * @param string &$script The script will be modified in this method. - */ - protected function addHasOnlyDefaultValues(&$script) - { - $this->addHasOnlyDefaultValuesComment($script); - $this->addHasOnlyDefaultValuesOpen($script); - $this->addHasOnlyDefaultValuesBody($script); - $this->addHasOnlyDefaultValuesClose($script); - } - - /** - * Adds the comment for the hasOnlyDefaultValues method - * @param string &$script The script will be modified in this method. - * @see addHasOnlyDefaultValues - **/ - protected function addHasOnlyDefaultValuesComment(&$script) { - $script .= " - /** - * Indicates whether the columns in this object are only set to default values. - * - * This method can be used in conjunction with isModified() to indicate whether an object is both - * modified _and_ has some values set which are non-default. - * - * @return boolean Whether the columns in this object are only been set with default values. - */"; - } - - /** - * Adds the function declaration for the hasOnlyDefaultValues method - * @param string &$script The script will be modified in this method. - * @see addHasOnlyDefaultValues - **/ - protected function addHasOnlyDefaultValuesOpen(&$script) { - $script .= " - public function hasOnlyDefaultValues() - {"; - } - - /** - * Adds the function body for the hasOnlyDefaultValues method - * @param string &$script The script will be modified in this method. - * @see addHasOnlyDefaultValues - **/ - protected function addHasOnlyDefaultValuesBody(&$script) { - $table = $this->getTable(); - $colsWithDefaults = array(); - foreach ($table->getColumns() as $col) { - $def = $col->getDefaultValue(); - if ($def !== null && !$def->isExpression()) { - $colsWithDefaults[] = $col; - } - } - - foreach ($colsWithDefaults as $col) { - - $clo = strtolower($col->getName()); - $def = $col->getDefaultValue(); - - $script .= " - if (\$this->$clo !== " . $this->getDefaultValueString($col).") { - return false; - } -"; - } - } - - /** - * Adds the function close for the hasOnlyDefaultValues method - * @param string &$script The script will be modified in this method. - * @see addHasOnlyDefaultValues - **/ - protected function addHasOnlyDefaultValuesClose(&$script) { - $script .= " - // otherwise, everything was equal, so return TRUE - return true;"; - $script .= " - } // hasOnlyDefaultValues() -"; - } - - /** - * Adds the hydrate() method, which sets attributes of the object based on a ResultSet. - * @param string &$script The script will be modified in this method. - */ - protected function addHydrate(&$script) - { - $this->addHydrateComment($script); - $this->addHydrateOpen($script); - $this->addHydrateBody($script); - $this->addHydrateClose($script); - } - - /** - * Adds the comment for the hydrate method - * @param string &$script The script will be modified in this method. - * @see addHydrate() - */ - protected function addHydrateComment(&$script) { - $script .= " - /** - * Hydrates (populates) the object variables with values from the database resultset. - * - * An offset (0-based \"start column\") is specified so that objects can be hydrated - * with a subset of the columns in the resultset rows. This is needed, for example, - * for results of JOIN queries where the resultset row includes columns from two or - * more tables. - * - * @param array \$row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) - * @param int \$startcol 0-based offset column which indicates which restultset column to start with. - * @param boolean \$rehydrate Whether this object is being re-hydrated from the database. - * @return int next starting column - * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. - */"; - } - - /** - * Adds the function declaration for the hydrate method - * @param string &$script The script will be modified in this method. - * @see addHydrate() - */ - protected function addHydrateOpen(&$script) { - $script .= " - public function hydrate(\$row, \$startcol = 0, \$rehydrate = false) - {"; - } - - /** - * Adds the function body for the hydrate method - * @param string &$script The script will be modified in this method. - * @see addHydrate() - */ - protected function addHydrateBody(&$script) { - $table = $this->getTable(); - $platform = $this->getPlatform(); - $script .= " - try { -"; - $n = 0; - foreach ($table->getColumns() as $col) { - if (!$col->isLazyLoad()) { - $clo = strtolower($col->getName()); - if ($col->getType() === PropelTypes::CLOB_EMU && $this->getPlatform() instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[\$startcol + $n]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { - $script .= " - if (\$row[\$startcol + $n] !== null) { - \$this->$clo = fopen('php://memory', 'r+'); - fwrite(\$this->$clo, \$row[\$startcol + $n]); - rewind(\$this->$clo); - } else { - \$this->$clo = null; - }"; - } elseif ($col->isPhpPrimitiveType()) { - $script .= " - \$this->$clo = (\$row[\$startcol + $n] !== null) ? (".$col->getPhpType().") \$row[\$startcol + $n] : null;"; - } elseif ($col->isPhpObjectType()) { - $script .= " - \$this->$clo = (\$row[\$startcol + $n] !== null) ? new ".$col->getPhpType()."(\$row[\$startcol + $n]) : null;"; - } else { - $script .= " - \$this->$clo = \$row[\$startcol + $n];"; - } - $n++; - } // if col->isLazyLoad() - } /* foreach */ - - if ($this->getBuildProperty("addSaveMethod")) { - $script .= " - \$this->resetModified(); -"; - } - - $script .= " - \$this->setNew(false); - - if (\$rehydrate) { - \$this->ensureConsistency(); - } - - return \$startcol + $n; // $n = ".$this->getPeerClassname()."::NUM_COLUMNS - ".$this->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS). - - } catch (Exception \$e) { - throw new PropelException(\"Error populating ".$this->getStubObjectBuilder()->getClassname()." object\", \$e); - }"; - } - - /** - * Adds the function close for the hydrate method - * @param string &$script The script will be modified in this method. - * @see addHydrate() - */ - protected function addHydrateClose(&$script) { - $script .= " - } -"; - } - - /** - * Adds the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - **/ - protected function addBuildPkeyCriteria(&$script) { - $this->addBuildPkeyCriteriaComment($script); - $this->addBuildPkeyCriteriaOpen($script); - $this->addBuildPkeyCriteriaBody($script); - $this->addBuildPkeyCriteriaClose($script); - } - - /** - * Adds the comment for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaComment(&$script) { - $script .= " - /** - * Builds a Criteria object containing the primary key for this object. - * - * Unlike buildCriteria() this method includes the primary key values regardless - * of whether or not they have been modified. - * - * @return Criteria The Criteria object containing value(s) for primary key(s). - */"; - } - - /** - * Adds the function declaration for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaOpen(&$script) { - $script .= " - public function buildPkeyCriteria() - {"; - } - - /** - * Adds the function body for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaBody(&$script) { - $script .= " - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME);"; - foreach ($this->getTable()->getPrimaryKey() as $col) { - $clo = strtolower($col->getName()); - $script .= " - \$criteria->add(".$this->getColumnConstant($col).", \$this->$clo);"; - } - } - - /** - * Adds the function close for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaClose(&$script) { - $script .= " - - return \$criteria; - } -"; - } - - /** - * Adds the buildCriteria method - * @param string &$script The script will be modified in this method. - **/ - protected function addBuildCriteria(&$script) - { - $this->addBuildCriteriaComment($script); - $this->addBuildCriteriaOpen($script); - $this->addBuildCriteriaBody($script); - $this->addBuildCriteriaClose($script); - } - - /** - * Adds comment for the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaComment(&$script) { - $script .= " - /** - * Build a Criteria object containing the values of all modified columns in this object. - * - * @return Criteria The Criteria object containing all modified values. - */"; - } - - /** - * Adds the function declaration of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaOpen(&$script) { - $script .= " - public function buildCriteria() - {"; - } - - /** - * Adds the function body of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaBody(&$script) { - $script .= " - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME); -"; - foreach ($this->getTable()->getColumns() as $col) { - $clo = strtolower($col->getName()); - $script .= " - if (\$this->isColumnModified(".$this->getColumnConstant($col).")) \$criteria->add(".$this->getColumnConstant($col).", \$this->$clo);"; - } - } - - /** - * Adds the function close of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaClose(&$script) { - $script .= " - - return \$criteria; - } -"; - } - - /** - * Adds the toArray method - * @param string &$script The script will be modified in this method. - **/ - protected function addToArray(&$script) - { - $fks = $this->getTable()->getForeignKeys(); - $hasFks = count($fks) > 0; - $script .= " - /** - * Exports the object as an array. - * - * You can specify the key type of the array by passing one of the class - * type constants. - * - * @param string \$keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. - * Defaults to BasePeer::TYPE_PHPNAME. - * @param boolean \$includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE."; - if ($hasFks) { - $script .= " - * @param boolean \$includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE."; - } - $script .= " - * - * @return array an associative array containing the field names (as keys) and field values - */ - public function toArray(\$keyType = BasePeer::TYPE_PHPNAME, \$includeLazyLoadColumns = true" . ($hasFks ? ", \$includeForeignObjects = false" : '') . ") - { - \$keys = ".$this->getPeerClassname()."::getFieldNames(\$keyType); - \$result = array("; - foreach ($this->getTable()->getColumns() as $num => $col) { - if ($col->isLazyLoad()) { - $script .= " - \$keys[$num] => (\$includeLazyLoadColumns) ? \$this->get".$col->getPhpName()."() : null,"; - } else { - $script .= " - \$keys[$num] => \$this->get".$col->getPhpName()."(),"; - } - } - $script .= " - );"; - if ($hasFks) { - $script .= " - if (\$includeForeignObjects) {"; - foreach ($fks as $fk) { - $script .= " - if (null !== \$this->" . $this->getFKVarName($fk) . ") { - \$result['" . $this->getFKPhpNameAffix($fk, $plural = false) . "'] = \$this->" . $this->getFKVarName($fk) . "->toArray(\$keyType, \$includeLazyLoadColumns, true); - }"; - } - $script .= " - }"; - } - $script .= " - return \$result; - } -"; - } // addToArray() - - /** - * Adds the getByName method - * @param string &$script The script will be modified in this method. - **/ - protected function addGetByName(&$script) - { - $this->addGetByNameComment($script); - $this->addGetByNameOpen($script); - $this->addGetByNameBody($script); - $this->addGetByNameClose($script); - } - - /** - * Adds the comment for the getByName method - * @param string &$script The script will be modified in this method. - * @see addGetByName - **/ - protected function addGetByNameComment(&$script) { - $script .= " - /** - * Retrieves a field from the object by name passed in as a string. - * - * @param string \$name name - * @param string \$type The type of fieldname the \$name is of: - * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return mixed Value of field. - */"; - } - - /** - * Adds the function declaration for the getByName method - * @param string &$script The script will be modified in this method. - * @see addGetByName - **/ - protected function addGetByNameOpen(&$script) { - $script .= " - public function getByName(\$name, \$type = BasePeer::TYPE_PHPNAME) - {"; - } - - /** - * Adds the function body for the getByName method - * @param string &$script The script will be modified in this method. - * @see addGetByName - **/ - protected function addGetByNameBody(&$script) { - $script .= " - \$pos = ".$this->getPeerClassname()."::translateFieldName(\$name, \$type, BasePeer::TYPE_NUM); - \$field = \$this->getByPosition(\$pos);"; - } - - /** - * Adds the function close for the getByName method - * @param string &$script The script will be modified in this method. - * @see addGetByName - **/ - protected function addGetByNameClose(&$script) { - $script .= " - return \$field; - } -"; - } - - /** - * Adds the getByPosition method - * @param string &$script The script will be modified in this method. - **/ - protected function addGetByPosition(&$script) - { - $this->addGetByPositionComment($script); - $this->addGetByPositionOpen($script); - $this->addGetByPositionBody($script); - $this->addGetByPositionClose($script); - } - - /** - * Adds comment for the getByPosition method - * @param string &$script The script will be modified in this method. - * @see addGetByPosition - **/ - protected function addGetByPositionComment(&$script) { - $script .= " - /** - * Retrieves a field from the object by Position as specified in the xml schema. - * Zero-based. - * - * @param int \$pos position in xml schema - * @return mixed Value of field at \$pos - */"; - } - - /** - * Adds the function declaration for the getByPosition method - * @param string &$script The script will be modified in this method. - * @see addGetByPosition - **/ - protected function addGetByPositionOpen(&$script) { - $script .= " - public function getByPosition(\$pos) - {"; - } - - /** - * Adds the function body for the getByPosition method - * @param string &$script The script will be modified in this method. - * @see addGetByPosition - **/ - protected function addGetByPositionBody(&$script) { - $table = $this->getTable(); - $script .= " - switch(\$pos) {"; - $i = 0; - foreach ($table->getColumns() as $col) { - $cfc = $col->getPhpName(); - $script .= " - case $i: - return \$this->get$cfc(); - break;"; - $i++; - } /* foreach */ - $script .= " - default: - return null; - break; - } // switch()"; - } - - /** - * Adds the function close for the getByPosition method - * @param string &$script The script will be modified in this method. - * @see addGetByPosition - **/ - protected function addGetByPositionClose(&$script) { - $script .= " - } -"; - } - - protected function addSetByName(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Sets a field from the object by name passed in as a string. - * - * @param string \$name peer name - * @param mixed \$value field value - * @param string \$type The type of fieldname the \$name is of: - * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return void - */ - public function setByName(\$name, \$value, \$type = BasePeer::TYPE_PHPNAME) - { - \$pos = ".$this->getPeerClassname()."::translateFieldName(\$name, \$type, BasePeer::TYPE_NUM); - return \$this->setByPosition(\$pos, \$value); - } -"; - } - - protected function addSetByPosition(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Sets a field from the object by Position as specified in the xml schema. - * Zero-based. - * - * @param int \$pos position in xml schema - * @param mixed \$value field value - * @return void - */ - public function setByPosition(\$pos, \$value) - { - switch(\$pos) {"; - $i = 0; - foreach ($table->getColumns() as $col) { - $cfc = $col->getPhpName(); - $cptype = $col->getPhpType(); - $script .= " - case $i: - \$this->set$cfc(\$value); - break;"; - $i++; - } /* foreach */ - $script .= " - } // switch() - } -"; - } // addSetByPosition() - - protected function addFromArray(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Populates the object using an array. - * - * This is particularly useful when populating an object from one of the - * request arrays (e.g. \$_POST). This method goes through the column - * names, checking to see whether a matching key exists in populated - * array. If so the setByName() method is called for that column. - * - * You can specify the key type of the array by additionally passing one - * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. - * The default key type is the column's phpname (e.g. 'AuthorId') - * - * @param array \$arr An array to populate the object from. - * @param string \$keyType The type of keys the array uses. - * @return void - */ - public function fromArray(\$arr, \$keyType = BasePeer::TYPE_PHPNAME) - { - \$keys = ".$this->getPeerClassname()."::getFieldNames(\$keyType); -"; - foreach ($table->getColumns() as $num => $col) { - $cfc = $col->getPhpName(); - $cptype = $col->getPhpType(); - $script .= " - if (array_key_exists(\$keys[$num], \$arr)) \$this->set$cfc(\$arr[\$keys[$num]]);"; - } /* foreach */ - $script .= " - } -"; - } // addFromArray - - /** - * Adds a delete() method to remove the object form the datastore. - * @param string &$script The script will be modified in this method. - */ - protected function addDelete(&$script) - { - $this->addDeleteComment($script); - $this->addDeleteOpen($script); - $this->addDeleteBody($script); - $this->addDeleteClose($script); - } - - /** - * Adds the comment for the delete function - * @param string &$script The script will be modified in this method. - * @see addDelete() - **/ - protected function addDeleteComment(&$script) { - $script .= " - /** - * Removes this object from datastore and sets delete attribute. - * - * @param PropelPDO \$con - * @return void - * @throws PropelException - * @see BaseObject::setDeleted() - * @see BaseObject::isDeleted() - */"; - } - - /** - * Adds the function declaration for the delete function - * @param string &$script The script will be modified in this method. - * @see addDelete() - **/ - protected function addDeleteOpen(&$script) { - $script .= " - public function delete(PropelPDO \$con = null) - {"; - } - - /** - * Adds the function body for the delete function - * @param string &$script The script will be modified in this method. - * @see addDelete() - **/ - protected function addDeleteBody(&$script) { - $script .= " - if (\$this->isDeleted()) { - throw new PropelException(\"This object has already been deleted.\"); - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$con->beginTransaction(); - try {"; - if($this->getGeneratorConfig()->getBuildProperty('addHooks')) { - $script .= " - \$ret = \$this->preDelete(\$con);"; - // apply behaviors - $this->applyBehaviorModifier('preDelete', $script, " "); - $script .= " - if (\$ret) { - ".$this->getQueryClassname()."::create() - ->filterByPrimaryKey(\$this->getPrimaryKey()) - ->delete(\$con); - \$this->postDelete(\$con);"; - // apply behaviors - $this->applyBehaviorModifier('postDelete', $script, " "); - $script .= " - \$con->commit(); - \$this->setDeleted(true); - } else { - \$con->commit(); - }"; - } else { - // apply behaviors - $this->applyBehaviorModifier('preDelete', $script, " "); - $script .= " - ".$this->getPeerClassname()."::doDelete(\$this, \$con);"; - // apply behaviors - $this->applyBehaviorModifier('postDelete', $script, " "); - $script .= " - \$con->commit(); - \$this->setDeleted(true);"; - } - - $script .= " - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - }"; - } - - /** - * Adds the function close for the delete function - * @param string &$script The script will be modified in this method. - * @see addDelete() - **/ - protected function addDeleteClose(&$script) { - $script .= " - } -"; - } // addDelete() - - /** - * Adds a reload() method to re-fetch the data for this object from the database. - * @param string &$script The script will be modified in this method. - */ - protected function addReload(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. - * - * This will only work if the object has been saved and has a valid primary key set. - * - * @param boolean \$deep (optional) Whether to also de-associated any related objects. - * @param PropelPDO \$con (optional) The PropelPDO connection to use. - * @return void - * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db - */ - public function reload(\$deep = false, PropelPDO \$con = null) - { - if (\$this->isDeleted()) { - throw new PropelException(\"Cannot reload a deleted object.\"); - } - - if (\$this->isNew()) { - throw new PropelException(\"Cannot reload an unsaved object.\"); - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - // We don't need to alter the object instance pool; we're just modifying this instance - // already in the pool. - - \$stmt = ".$this->getPeerClassname()."::doSelectStmt(\$this->buildPkeyCriteria(), \$con); - \$row = \$stmt->fetch(PDO::FETCH_NUM); - \$stmt->closeCursor(); - if (!\$row) { - throw new PropelException('Cannot find matching row in the database to reload object values.'); - } - \$this->hydrate(\$row, 0, true); // rehydrate -"; - - // support for lazy load columns - foreach ($table->getColumns() as $col) { - if ($col->isLazyLoad()) { - $clo = strtolower($col->getName()); - $script .= " - // Reset the $clo lazy-load column - \$this->" . $clo . " = null; - \$this->".$clo."_isLoaded = false; -"; - } - } - - $script .= " - if (\$deep) { // also de-associate any related objects? -"; - - foreach ($table->getForeignKeys() as $fk) { - $varName = $this->getFKVarName($fk); - $script .= " - \$this->".$varName." = null;"; - } - - foreach ($table->getReferrers() as $refFK) { - if ($refFK->isLocalPrimaryKey()) { - $script .= " - \$this->".$this->getPKRefFKVarName($refFK)." = null; -"; - } else { - $script .= " - \$this->".$this->getRefFKCollVarName($refFK)." = null; -"; - } - } - - $script .= " - } // if (deep) - } -"; - } // addReload() - - /** - * Adds the methods related to refreshing, saving and deleting the object. - * @param string &$script The script will be modified in this method. - */ - protected function addManipulationMethods(&$script) - { - $this->addReload($script); - $this->addDelete($script); - $this->addSave($script); - $this->addDoSave($script); - } - - /** - * Adds the methods related to validationg the object. - * @param string &$script The script will be modified in this method. - */ - protected function addValidationMethods(&$script) - { - $this->addValidationFailuresAttribute($script); - $this->addGetValidationFailures($script); - $this->addValidate($script); - $this->addDoValidate($script); - } - - /** - * Adds the $validationFailures attribute to store ValidationFailed objects. - * @param string &$script The script will be modified in this method. - */ - protected function addValidationFailuresAttribute(&$script) - { - $script .= " - /** - * Array of ValidationFailed objects. - * @var array ValidationFailed[] - */ - protected \$validationFailures = array(); -"; - } - - /** - * Adds the getValidationFailures() method. - * @param string &$script The script will be modified in this method. - */ - protected function addGetValidationFailures(&$script) - { - $script .= " - /** - * Gets any ValidationFailed objects that resulted from last call to validate(). - * - * - * @return array ValidationFailed[] - * @see validate() - */ - public function getValidationFailures() - { - return \$this->validationFailures; - } -"; - } // addGetValidationFailures() - - /** - * Adds the correct getPrimaryKey() method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addGetPrimaryKey(&$script) - { - $pkeys = $this->getTable()->getPrimaryKey(); - if (count($pkeys) == 1) { - $this->addGetPrimaryKey_SinglePK($script); - } elseif (count($pkeys) > 1) { - $this->addGetPrimaryKey_MultiPK($script); - } else { - // no primary key -- this is deprecated, since we don't *need* this method anymore - $this->addGetPrimaryKey_NoPK($script); - } - } - - /** - * Adds the getPrimaryKey() method for tables that contain a single-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addGetPrimaryKey_SinglePK(&$script) - { - $table = $this->getTable(); - $pkeys = $table->getPrimaryKey(); - $cptype = $pkeys[0]->getPhpType(); - - $script .= " - /** - * Returns the primary key for this object (row). - * @return $cptype - */ - public function getPrimaryKey() - { - return \$this->get".$pkeys[0]->getPhpName()."(); - } -"; - } // addetPrimaryKey_SingleFK - - /** - * Adds the setPrimaryKey() method for tables that contain a multi-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addGetPrimaryKey_MultiPK(&$script) - { - - $script .= " - /** - * Returns the composite primary key for this object. - * The array elements will be in same order as specified in XML. - * @return array - */ - public function getPrimaryKey() - { - \$pks = array();"; - $i = 0; - foreach ($this->getTable()->getPrimaryKey() as $pk) { - $script .= " - \$pks[$i] = \$this->get".$pk->getPhpName()."();"; - $i++; - } /* foreach */ - $script .= " - - return \$pks; - } -"; - } // addGetPrimaryKey_MultiFK() - - /** - * Adds the getPrimaryKey() method for objects that have no primary key. - * This "feature" is dreprecated, since the getPrimaryKey() method is not required - * by the Persistent interface (or used by the templates). Hence, this method is also - * deprecated. - * @param string &$script The script will be modified in this method. - * @deprecated - */ - protected function addGetPrimaryKey_NoPK(&$script) - { - $script .= " - /** - * Returns NULL since this table doesn't have a primary key. - * This method exists only for BC and is deprecated! - * @return null - */ - public function getPrimaryKey() - { - return null; - } -"; - } - /** - * Adds the correct setPrimaryKey() method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addSetPrimaryKey(&$script) - { - $pkeys = $this->getTable()->getPrimaryKey(); - if (count($pkeys) == 1) { - $this->addSetPrimaryKey_SinglePK($script); - } elseif (count($pkeys) > 1) { - $this->addSetPrimaryKey_MultiPK($script); - } else { - // no primary key -- this is deprecated, since we don't *need* this method anymore - $this->addSetPrimaryKey_NoPK($script); - } - } - - /** - * Adds the setPrimaryKey() method for tables that contain a single-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addSetPrimaryKey_SinglePK(&$script) - { - - $pkeys = $this->getTable()->getPrimaryKey(); - $col = $pkeys[0]; - $clo=strtolower($col->getName()); - $ctype = $col->getPhpType(); - - $script .= " - /** - * Generic method to set the primary key ($clo column). - * - * @param $ctype \$key Primary key. - * @return void - */ - public function setPrimaryKey(\$key) - { - \$this->set".$col->getPhpName()."(\$key); - } -"; - } // addSetPrimaryKey_SinglePK - - /** - * Adds the setPrimaryKey() method for tables that contain a multi-columnprimary key. - * @param string &$script The script will be modified in this method. - */ - protected function addSetPrimaryKey_MultiPK(&$script) - { - - $script .=" - /** - * Set the [composite] primary key. - * - * @param array \$keys The elements of the composite key (order must match the order in XML file). - * @return void - */ - public function setPrimaryKey(\$keys) - {"; - $i = 0; - foreach ($this->getTable()->getPrimaryKey() as $pk) { - $pktype = $pk->getPhpType(); - $script .= " - \$this->set".$pk->getPhpName()."(\$keys[$i]);"; - $i++; - } /* foreach ($table->getPrimaryKey() */ - $script .= " - } -"; - } // addSetPrimaryKey_MultiPK - - /** - * Adds the setPrimaryKey() method for objects that have no primary key. - * This "feature" is dreprecated, since the setPrimaryKey() method is not required - * by the Persistent interface (or used by the templates). Hence, this method is also - * deprecated. - * @param string &$script The script will be modified in this method. - * @deprecated - */ - protected function addSetPrimaryKey_NoPK(&$script) - { - $script .=" - /** - * Dummy primary key setter. - * - * This function only exists to preserve backwards compatibility. It is no longer - * needed or required by the Persistent interface. It will be removed in next BC-breaking - * release of Propel. - * - * @deprecated - */ - public function setPrimaryKey(\$pk) - { - // do nothing, because this object doesn't have any primary keys - } -"; - } - - /** - * Adds the isPrimaryKeyNull() method - * @param string &$script The script will be modified in this method. - */ - protected function addIsPrimaryKeyNull(&$script) - { - $table = $this->getTable(); - $pkeys = $table->getPrimaryKey(); - - $script .= " - /** - * Returns true if the primary key for this object is null. - * @return boolean - */ - public function isPrimaryKeyNull() - {"; - if (count($pkeys) == 1) { - $script .= " - return null === \$this->get" . $pkeys[0]->getPhpName() . "();"; - } else { - $tests = array(); - foreach ($pkeys as $pkey) { - $tests[]= "(null === \$this->get" . $pkey->getPhpName() . "())"; - } - $script .= " - return " . join(' && ', $tests) . ";"; - } - $script .= " - } -"; - } // addetPrimaryKey_SingleFK - - // -------------------------------------------------------------------- - // Complex OM Methods - // -------------------------------------------------------------------- - - /** - * Constructs variable name for fkey-related objects. - * @param ForeignKey $fk - * @return string - */ - protected function getFKVarName(ForeignKey $fk) - { - return 'a' . $this->getFKPhpNameAffix($fk, $plural = false); - } - - /** - * Constructs variable name for objects which referencing current table by specified foreign key. - * @param ForeignKey $fk - * @return string - */ - protected function getRefFKCollVarName(ForeignKey $fk) - { - return 'coll' . $this->getRefFKPhpNameAffix($fk, $plural = true); - } - - /** - * Constructs variable name for single object which references current table by specified foreign key - * which is ALSO a primary key (hence one-to-one relationship). - * @param ForeignKey $fk - * @return string - */ - protected function getPKRefFKVarName(ForeignKey $fk) - { - return 'single' . $this->getRefFKPhpNameAffix($fk, $plural = false); - } - - // ---------------------------------------------------------------- - // - // F K M E T H O D S - // - // ---------------------------------------------------------------- - - /** - * Adds the methods that get & set objects related by foreign key to the current object. - * @param string &$script The script will be modified in this method. - */ - protected function addFKMethods(&$script) - { - foreach ($this->getTable()->getForeignKeys() as $fk) { - $this->declareClassFromBuilder($this->getNewStubObjectBuilder($fk->getForeignTable())); - $this->declareClassFromBuilder($this->getNewStubQueryBuilder($fk->getForeignTable())); - $this->addFKMutator($script, $fk); - $this->addFKAccessor($script, $fk); - } // foreach fk - } - - /** - * Adds the class attributes that are needed to store fkey related objects. - * @param string &$script The script will be modified in this method. - */ - protected function addFKAttributes(&$script, ForeignKey $fk) - { - $className = $this->getForeignTable($fk)->getPhpName(); - $varName = $this->getFKVarName($fk); - - $script .= " - /** - * @var $className - */ - protected $".$varName."; -"; - } - - /** - * Adds the mutator (setter) method for setting an fkey related object. - * @param string &$script The script will be modified in this method. - */ - protected function addFKMutator(&$script, ForeignKey $fk) - { - $table = $this->getTable(); - $tblFK = $this->getForeignTable($fk); - - $joinTableObjectBuilder = $this->getNewObjectBuilder($tblFK); - $className = $joinTableObjectBuilder->getObjectClassname(); - - $varName = $this->getFKVarName($fk); - - $script .= " - /** - * Declares an association between this object and a $className object. - * - * @param $className \$v - * @return ".$this->getObjectClassname()." The current object (for fluent API support) - * @throws PropelException - */ - public function set".$this->getFKPhpNameAffix($fk, $plural = false)."($className \$v = null) - {"; - foreach ($fk->getLocalColumns() as $columnName) { - $column = $table->getColumn($columnName); - $lfmap = $fk->getLocalForeignMapping(); - $colFKName = $lfmap[$columnName]; - $colFK = $tblFK->getColumn($colFKName); - $script .= " - if (\$v === null) { - \$this->set".$column->getPhpName()."(".$this->getDefaultValueString($column)."); - } else { - \$this->set".$column->getPhpName()."(\$v->get".$colFK->getPhpName()."()); - } -"; - - } /* foreach local col */ - - $script .= " - \$this->$varName = \$v; -"; - - // Now add bi-directional relationship binding, taking into account whether this is - // a one-to-one relationship. - - if ($fk->isLocalPrimaryKey()) { - $script .= " - // Add binding for other direction of this 1:1 relationship. - if (\$v !== null) { - \$v->set".$this->getRefFKPhpNameAffix($fk, $plural = false)."(\$this); - } -"; - } else { - $script .= " - // Add binding for other direction of this n:n relationship. - // If this object has already been added to the $className object, it will not be re-added. - if (\$v !== null) { - \$v->add".$this->getRefFKPhpNameAffix($fk, $plural = false)."(\$this); - } -"; - - } - - $script .= " - return \$this; - } -"; - } - - /** - * Adds the accessor (getter) method for getting an fkey related object. - * @param string &$script The script will be modified in this method. - */ - protected function addFKAccessor(&$script, ForeignKey $fk) - { - $table = $this->getTable(); - - $varName = $this->getFKVarName($fk); - $pCollName = $this->getFKPhpNameAffix($fk, $plural = true); - - $fkPeerBuilder = $this->getNewPeerBuilder($this->getForeignTable($fk)); - $fkQueryBuilder = $this->getNewStubQueryBuilder($this->getForeignTable($fk)); - $fkObjectBuilder = $this->getNewObjectBuilder($this->getForeignTable($fk))->getStubObjectBuilder(); - $className = $fkObjectBuilder->getClassname(); // get the Classname that has maybe a prefix - - $and = ""; - $comma = ""; - $conditional = ""; - $argmap = array(); // foreign -> local mapping - $argsize = 0; - foreach ($fk->getLocalColumns() as $columnName) { - - $lfmap = $fk->getLocalForeignMapping(); - - $localColumn = $table->getColumn($columnName); - $foreignColumn = $fk->getForeignTable()->getColumn($lfmap[$columnName]); - - $column = $table->getColumn($columnName); - $cptype = $column->getPhpType(); - $clo = strtolower($column->getName()); - - if ($cptype == "integer" || $cptype == "float" || $cptype == "double") { - $conditional .= $and . "\$this->". $clo ." != 0"; - } elseif ($cptype == "string") { - $conditional .= $and . "(\$this->" . $clo ." !== \"\" && \$this->".$clo." !== null)"; - } else { - $conditional .= $and . "\$this->" . $clo ." !== null"; - } - - $argmap[] = array('foreign' => $foreignColumn, 'local' => $localColumn); - $and = " && "; - $comma = ", "; - $argsize = $argsize + 1; - } - - // If the related column is a primary kay and if it's a simple association, - // The use retrieveByPk() instead of doSelect() to take advantage of instance pooling - $useRetrieveByPk = count($argmap) == 1 && $argmap[0]['foreign']->isPrimaryKey(); - - $script .= " - - /** - * Get the associated $className object - * - * @param PropelPDO Optional Connection object. - * @return $className The associated $className object. - * @throws PropelException - */ - public function get".$this->getFKPhpNameAffix($fk, $plural = false)."(PropelPDO \$con = null) - {"; - $script .= " - if (\$this->$varName === null && ($conditional)) {"; - if ($useRetrieveByPk) { - $script .= " - \$this->$varName = ".$fkQueryBuilder->getClassname()."::create()->findPk(\$this->$clo, \$con);"; - } else { - $script .= " - \$this->$varName = ".$fkQueryBuilder->getClassname()."::create() - ->filterBy" . $this->getRefFKPhpNameAffix($fk, $plural = false) . "(\$this) // here - ->findOne(\$con);"; - } - if ($fk->isLocalPrimaryKey()) { - $script .= " - // Because this foreign key represents a one-to-one relationship, we will create a bi-directional association. - \$this->{$varName}->set".$this->getRefFKPhpNameAffix($fk, $plural = false)."(\$this);"; - } else { - $script .= " - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - \$this->{$varName}->add".$this->getRefFKPhpNameAffix($fk, $plural = true)."(\$this); - */"; - } - - $script .= " - } - return \$this->$varName; - } -"; - - } // addFKAccessor - - /** - * Adds a convenience method for setting a related object by specifying the primary key. - * This can be used in conjunction with the getPrimaryKey() for systems where nothing is known - * about the actual objects being related. - * @param string &$script The script will be modified in this method. - */ - protected function addFKByKeyMutator(&$script, ForeignKey $fk) - { - $table = $this->getTable(); - - #$className = $this->getForeignTable($fk)->getPhpName(); - $methodAffix = $this->getFKPhpNameAffix($fk); - #$varName = $this->getFKVarName($fk); - - $script .= " - /** - * Provides convenient way to set a relationship based on a - * key. e.g. - * \$bar->setFooKey(\$foo->getPrimaryKey()) - *"; - if (count($fk->getLocalColumns()) > 1) { - $script .= " - * Note: It is important that the xml schema used to create this class - * maintains consistency in the order of related columns between - * ".$table->getName()." and ". $tblFK->getName().". - * If for some reason this is impossible, this method should be - * overridden in ".$table->getPhpName()."."; - } - $script .= " - * @return ".$this->getObjectClassname()." The current object (for fluent API support) - * @throws PropelException - */ - public function set".$methodAffix."Key(\$key) - { -"; - if (count($fk->getLocalColumns()) > 1) { - $i = 0; - foreach ($fk->getLocalColumns() as $colName) { - $col = $table->getColumn($colName); - $fktype = $col->getPhpType(); - $script .= " - \$this->set".$col->getPhpName()."( ($fktype) \$key[$i] ); -"; - $i++; - } /* foreach */ - } else { - $lcols = $fk->getLocalColumns(); - $colName = $lcols[0]; - $col = $table->getColumn($colName); - $fktype = $col->getPhpType(); - $script .= " - \$this->set".$col->getPhpName()."( ($fktype) \$key); -"; - } - $script .= " - return \$this; - } -"; - } // addFKByKeyMutator() - - /** - * Adds the method that fetches fkey-related (referencing) objects but also joins in data from another table. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKGetJoinMethods(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - $join_behavior = $this->getGeneratorConfig()->getBuildProperty('useLeftJoinsInDoJoinMethods') ? 'Criteria::LEFT_JOIN' : 'Criteria::INNER_JOIN'; - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural=true); - $collName = $this->getRefFKCollVarName($refFK); - - $fkPeerBuilder = $this->getNewPeerBuilder($tblFK); - $className = $fkPeerBuilder->getObjectClassname(); - - $lastTable = ""; - foreach ($tblFK->getForeignKeys() as $fk2) { - - $tblFK2 = $this->getForeignTable($fk2); - $doJoinGet = !$tblFK2->isForReferenceOnly(); - - // it doesn't make sense to join in rows from the curent table, since we are fetching - // objects related to *this* table (i.e. the joined rows will all be the same row as current object) - if ($this->getTable()->getPhpName() == $tblFK2->getPhpName()) { - $doJoinGet = false; - } - - $relCol2 = $this->getFKPhpNameAffix($fk2, $plural = false); - - if ( $this->getRelatedBySuffix($refFK) != "" && - ($this->getRelatedBySuffix($refFK) == $this->getRelatedBySuffix($fk2))) { - $doJoinGet = false; - } - - if ($doJoinGet) { - $script .= " - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this ".$table->getPhpName()." is new, it will return - * an empty collection; or if this ".$table->getPhpName()." has previously - * been saved, it will retrieve related $relCol from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in ".$table->getPhpName().". - * - * @param Criteria \$criteria optional Criteria object to narrow the query - * @param PropelPDO \$con optional connection object - * @param string \$join_behavior optional join type to use (defaults to $join_behavior) - * @return PropelCollection|array {$className}[] List of $className objects - */ - public function get".$relCol."Join".$relCol2."(\$criteria = null, \$con = null, \$join_behavior = $join_behavior) - {"; - $script .= " - \$query = $fkQueryClassname::create(null, \$criteria); - \$query->joinWith('" . $this->getFKPhpNameAffix($fk2, $plural=false) . "', \$join_behavior); - - return \$this->get". $relCol . "(\$query, \$con); - } -"; - } /* end if ($doJoinGet) */ - - } /* end foreach ($tblFK->getForeignKeys() as $fk2) { */ - - } // function - - - // ---------------------------------------------------------------- - // - // R E F E R R E R F K M E T H O D S - // - // ---------------------------------------------------------------- - - /** - * Adds the attributes used to store objects that have referrer fkey relationships to this object. - * protected collVarName; - * private lastVarNameCriteria = null; - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKAttributes(&$script, ForeignKey $refFK) - { - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - if ($refFK->isLocalPrimaryKey()) { - $script .= " - /** - * @var $className one-to-one related $className object - */ - protected $".$this->getPKRefFKVarName($refFK)."; -"; - } else { - $script .= " - /** - * @var array {$className}[] Collection to store aggregation of $className objects. - */ - protected $".$this->getRefFKCollVarName($refFK)."; -"; - } - } - - /** - * Adds the methods for retrieving, initializing, adding objects that are related to this one by foreign keys. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKMethods(&$script) - { - foreach ($this->getTable()->getReferrers() as $refFK) { - $this->declareClassFromBuilder($this->getNewStubObjectBuilder($refFK->getTable())); - $this->declareClassFromBuilder($this->getNewStubQueryBuilder($refFK->getTable())); - if ($refFK->isLocalPrimaryKey()) { - $this->addPKRefFKGet($script, $refFK); - $this->addPKRefFKSet($script, $refFK); - } else { - $this->addRefFKClear($script, $refFK); - $this->addRefFKInit($script, $refFK); - $this->addRefFKGet($script, $refFK); - $this->addRefFKCount($script, $refFK); - $this->addRefFKAdd($script, $refFK); - $this->addRefFKGetJoinMethods($script, $refFK); - } - } - } - - /** - * Adds the method that clears the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKClear(&$script, ForeignKey $refFK) { - - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - $collName = $this->getRefFKCollVarName($refFK); - - $script .= " - /** - * Clears out the $collName collection - * - * This does not modify the database; however, it will remove any associated objects, causing - * them to be refetched by subsequent calls to accessor method. - * - * @return void - * @see add$relCol() - */ - public function clear$relCol() - { - \$this->$collName = null; // important to set this to NULL since that means it is uninitialized - } -"; - } // addRefererClear() - - /** - * Adds the method that initializes the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKInit(&$script, ForeignKey $refFK) { - - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - $collName = $this->getRefFKCollVarName($refFK); - - $script .= " - /** - * Initializes the $collName collection. - * - * By default this just sets the $collName collection to an empty array (like clear$collName()); - * however, you may wish to override this method in your stub class to provide setting appropriate - * to your application -- for example, setting the initial array to the values stored in database. - * - * @return void - */ - public function init$relCol() - { - \$this->$collName = new PropelObjectCollection(); - \$this->{$collName}->setModel('" . $this->getNewStubObjectBuilder($refFK->getTable())->getClassname() . "'); - } -"; - } // addRefererInit() - - /** - * Adds the method that adds an object into the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKAdd(&$script, ForeignKey $refFK) - { - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $collName = $this->getRefFKCollVarName($refFK); - - $script .= " - /** - * Method called to associate a $className object to this object - * through the $className foreign key attribute. - * - * @param $className \$l $className - * @return void - * @throws PropelException - */ - public function add".$this->getRefFKPhpNameAffix($refFK, $plural = false)."($className \$l) - { - if (\$this->$collName === null) { - \$this->init".$this->getRefFKPhpNameAffix($refFK, $plural = true)."(); - } - if (!\$this->{$collName}->contains(\$l)) { // only add it if the **same** object is not already associated - \$this->{$collName}[]= \$l; - \$l->set".$this->getFKPhpNameAffix($refFK, $plural = false)."(\$this); - } - } -"; - } // addRefererAdd - - /** - * Adds the method that returns the size of the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKCount(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - - $collName = $this->getRefFKCollVarName($refFK); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $script .= " - /** - * Returns the number of related $className objects. - * - * @param Criteria \$criteria - * @param boolean \$distinct - * @param PropelPDO \$con - * @return int Count of related $className objects. - * @throws PropelException - */ - public function count$relCol(Criteria \$criteria = null, \$distinct = false, PropelPDO \$con = null) - { - if(null === \$this->$collName || null !== \$criteria) { - if (\$this->isNew() && null === \$this->$collName) { - return 0; - } else { - \$query = $fkQueryClassname::create(null, \$criteria); - if(\$distinct) { - \$query->distinct(); - } - return \$query - ->filterBy" . $this->getFKPhpNameAffix($refFK) . "(\$this) - ->count(\$con); - } - } else { - return count(\$this->$collName); - } - } -"; - } // addRefererCount - - /** - * Adds the method that returns the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKGet(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - - $collName = $this->getRefFKCollVarName($refFK); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $script .= " - /** - * Gets an array of $className objects which contain a foreign key that references this object. - * - * If the \$criteria is not null, it is used to always fetch the results from the database. - * Otherwise the results are fetched from the database the first time, then cached. - * Next time the same method is called without \$criteria, the cached collection is returned. - * If this ".$this->getObjectClassname()." is new, it will return - * an empty collection or the current collection; the criteria is ignored on a new object. - * - * @param Criteria \$criteria optional Criteria object to narrow the query - * @param PropelPDO \$con optional connection object - * @return PropelCollection|array {$className}[] List of $className objects - * @throws PropelException - */ - public function get$relCol(\$criteria = null, PropelPDO \$con = null) - { - if(null === \$this->$collName || null !== \$criteria) { - if (\$this->isNew() && null === \$this->$collName) { - // return empty collection - \$this->init".$this->getRefFKPhpNameAffix($refFK, $plural = true)."(); - } else { - \$$collName = $fkQueryClassname::create(null, \$criteria) - ->filterBy" . $this->getFKPhpNameAffix($refFK) . "(\$this) - ->find(\$con); - if (null !== \$criteria) { - return \$$collName; - } - \$this->$collName = \$$collName; - } - } - return \$this->$collName; - } -"; - } // addRefererGet() - - /** - * Adds the method that gets a one-to-one related referrer fkey. - * This is for one-to-one relationship special case. - * @param string &$script The script will be modified in this method. - */ - protected function addPKRefFKGet(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $queryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); - - $varName = $this->getPKRefFKVarName($refFK); - - $script .= " - /** - * Gets a single $className object, which is related to this object by a one-to-one relationship. - * - * @param PropelPDO \$con optional connection object - * @return $className - * @throws PropelException - */ - public function get".$this->getRefFKPhpNameAffix($refFK, $plural = false)."(PropelPDO \$con = null) - { -"; - $script .= " - if (\$this->$varName === null && !\$this->isNew()) { - \$this->$varName = $queryClassname::create()->findPk(\$this->getPrimaryKey(), \$con); - } - - return \$this->$varName; - } -"; - } // addPKRefFKGet() - - /** - * Adds the method that sets a one-to-one related referrer fkey. - * This is for one-to-one relationships special case. - * @param string &$script The script will be modified in this method. - * @param ForeignKey $refFK The referencing foreign key. - */ - protected function addPKRefFKSet(&$script, ForeignKey $refFK) - { - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $varName = $this->getPKRefFKVarName($refFK); - - $script .= " - /** - * Sets a single $className object as related to this object by a one-to-one relationship. - * - * @param $className \$v $className - * @return ".$this->getObjectClassname()." The current object (for fluent API support) - * @throws PropelException - */ - public function set".$this->getRefFKPhpNameAffix($refFK, $plural = false)."($className \$v = null) - { - \$this->$varName = \$v; - - // Make sure that that the passed-in $className isn't already associated with this object - if (\$v !== null && \$v->get".$this->getFKPhpNameAffix($refFK, $plural = false)."() === null) { - \$v->set".$this->getFKPhpNameAffix($refFK, $plural = false)."(\$this); - } - - return \$this; - } -"; - } // addPKRefFKSet - - protected function addCrossFKAttributes(&$script, ForeignKey $crossFK) - { - $joinedTableObjectBuilder = $this->getNewObjectBuilder($crossFK->getForeignTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - $script .= " - /** - * @var array {$className}[] Collection to store aggregation of $className objects. - */ - protected $" . $this->getCrossFKVarName($crossFK) . "; -"; - } - - protected function getCrossFKVarName(ForeignKey $crossFK) - { - return 'coll' . $this->getFKPhpNameAffix($crossFK, $plural = true); - } - - protected function addCrossFKMethods(&$script) - { - foreach ($this->getTable()->getCrossFks() as $fkList) { - list($refFK, $crossFK) = $fkList; - $this->declareClassFromBuilder($this->getNewStubObjectBuilder($crossFK->getForeignTable())); - $this->declareClassFromBuilder($this->getNewStubQueryBuilder($crossFK->getForeignTable())); - - $this->addCrossFKClear($script, $crossFK); - $this->addCrossFKInit($script, $crossFK); - $this->addCrossFKGet($script, $refFK, $crossFK); - $this->addCrossFKCount($script, $refFK, $crossFK); - $this->addCrossFKAdd($script, $refFK, $crossFK); - } - } - - /** - * Adds the method that clears the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addCrossFKClear(&$script, ForeignKey $crossFK) { - - $relCol = $this->getFKPhpNameAffix($crossFK, $plural = true); - $collName = $this->getCrossFKVarName($crossFK); - - $script .= " - /** - * Clears out the $collName collection - * - * This does not modify the database; however, it will remove any associated objects, causing - * them to be refetched by subsequent calls to accessor method. - * - * @return void - * @see add$relCol() - */ - public function clear$relCol() - { - \$this->$collName = null; // important to set this to NULL since that means it is uninitialized - } -"; - } // addRefererClear() - - /** - * Adds the method that initializes the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addCrossFKInit(&$script, ForeignKey $crossFK) { - - $relCol = $this->getFKPhpNameAffix($crossFK, $plural = true); - $collName = $this->getCrossFKVarName($crossFK); - $relatedObjectClassName = $this->getNewStubObjectBuilder($crossFK->getForeignTable())->getClassname(); - - $script .= " - /** - * Initializes the $collName collection. - * - * By default this just sets the $collName collection to an empty collection (like clear$relCol()); - * however, you may wish to override this method in your stub class to provide setting appropriate - * to your application -- for example, setting the initial array to the values stored in database. - * - * @return void - */ - public function init$relCol() - { - \$this->$collName = new PropelObjectCollection(); - \$this->{$collName}->setModel('$relatedObjectClassName'); - } -"; - } - - protected function addCrossFKGet(&$script, $refFK, $crossFK) - { - $relatedName = $this->getFKPhpNameAffix($crossFK, $plural = true); - $relatedObjectClassName = $this->getNewStubObjectBuilder($crossFK->getForeignTable())->getClassname(); - $selfRelationName = $this->getFKPhpNameAffix($refFK, $plural = false); - $relatedQueryClassName = $this->getNewStubQueryBuilder($crossFK->getForeignTable())->getClassname(); - $crossRefTableName = $crossFK->getTableName(); - $collName = $this->getCrossFKVarName($crossFK); - $script .= " - /** - * Gets a collection of $relatedObjectClassName objects related by a many-to-many relationship - * to the current object by way of the $crossRefTableName cross-reference table. - * - * If the \$criteria is not null, it is used to always fetch the results from the database. - * Otherwise the results are fetched from the database the first time, then cached. - * Next time the same method is called without \$criteria, the cached collection is returned. - * If this ".$this->getObjectClassname()." is new, it will return - * an empty collection or the current collection; the criteria is ignored on a new object. - * - * @param Criteria \$criteria Optional query object to filter the query - * @param PropelPDO \$con Optional connection object - * - * @return PropelCollection|array {$relatedObjectClassName}[] List of {$relatedObjectClassName} objects - */ - public function get{$relatedName}(\$criteria = null, PropelPDO \$con = null) - { - if(null === \$this->$collName || null !== \$criteria) { - if (\$this->isNew() && null === \$this->$collName) { - // return empty collection - \$this->init{$relatedName}(); - } else { - \$$collName = $relatedQueryClassName::create(null, \$criteria) - ->filterBy{$selfRelationName}(\$this) - ->find(\$con); - if (null !== \$criteria) { - return \$$collName; - } - \$this->$collName = \$$collName; - } - } - return \$this->$collName; - } -"; - } - - protected function addCrossFKCount(&$script, $refFK, $crossFK) - { - $relatedName = $this->getFKPhpNameAffix($crossFK, $plural = true); - $relatedObjectClassName = $this->getNewStubObjectBuilder($crossFK->getForeignTable())->getClassname(); - $selfRelationName = $this->getFKPhpNameAffix($refFK, $plural = false); - $relatedQueryClassName = $this->getNewStubQueryBuilder($crossFK->getForeignTable())->getClassname(); - $crossRefTableName = $refFK->getTableName(); - $collName = $this->getCrossFKVarName($crossFK); - $script .= " - /** - * Gets the number of $relatedObjectClassName objects related by a many-to-many relationship - * to the current object by way of the $crossRefTableName cross-reference table. - * - * @param Criteria \$criteria Optional query object to filter the query - * @param boolean \$distinct Set to true to force count distinct - * @param PropelPDO \$con Optional connection object - * - * @return int the number of related $relatedObjectClassName objects - */ - public function count{$relatedName}(\$criteria = null, \$distinct = false, PropelPDO \$con = null) - { - if(null === \$this->$collName || null !== \$criteria) { - if (\$this->isNew() && null === \$this->$collName) { - return 0; - } else { - \$query = $relatedQueryClassName::create(null, \$criteria); - if(\$distinct) { - \$query->distinct(); - } - return \$query - ->filterBy{$selfRelationName}(\$this) - ->count(\$con); - } - } else { - return count(\$this->$collName); - } - } -"; - } - - /** - * Adds the method that adds an object into the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addCrossFKAdd(&$script, ForeignKey $refFK, ForeignKey $crossFK) - { - $relCol = $this->getFKPhpNameAffix($crossFK, $plural = true); - $collName = $this->getCrossFKVarName($crossFK); - - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $foreignObjectName = '$' . $tblFK->getStudlyPhpName(); - $crossObjectName = '$' . $crossFK->getForeignTable()->getStudlyPhpName(); - $crossObjectClassName = $this->getNewObjectBuilder($crossFK->getForeignTable())->getObjectClassname(); - - $script .= " - /** - * Associate a " . $crossObjectClassName . " object to this object - * through the " . $tblFK->getName() . " cross reference table. - * - * @param " . $crossObjectClassName . " " . $crossObjectName . " The $className object to relate - * @return void - */ - public function add" . $this->getFKPhpNameAffix($crossFK, $plural = false) . "(" . $crossObjectName. ") - { - if (\$this->" . $collName . " === null) { - \$this->init" . $relCol . "(); - } - if (!\$this->" . $collName . "->contains(" . $crossObjectName . ")) { // only add it if the **same** object is not already associated - " . $foreignObjectName . " = new " . $className . "(); - " . $foreignObjectName . "->set" . $this->getFKPhpNameAffix($crossFK, $plural = false) . "(" . $crossObjectName . "); - \$this->add" . $this->getRefFKPhpNameAffix($refFK, $plural = false) . "(" . $foreignObjectName . "); - - \$this->" . $collName . "[]= " . $crossObjectName . "; - } - } -"; - } - - // ---------------------------------------------------------------- - // - // M A N I P U L A T I O N M E T H O D S - // - // ---------------------------------------------------------------- - - /** - * Adds the workhourse doSave() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSave(&$script) - { - $table = $this->getTable(); - - $reloadOnUpdate = $table->isReloadOnUpdate(); - $reloadOnInsert = $table->isReloadOnInsert(); - - $script .= " - /** - * Performs the work of inserting or updating the row in the database. - * - * If the object is new, it inserts it; otherwise an update is performed. - * All related objects are also updated in this method. - * - * @param PropelPDO \$con"; - if ($reloadOnUpdate || $reloadOnInsert) { - $script .= " - * @param boolean \$skipReload Whether to skip the reload for this object from database."; - } - $script .= " - * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. - * @throws PropelException - * @see save() - */ - protected function doSave(PropelPDO \$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload = false" : "").") - { - \$affectedRows = 0; // initialize var to track total num of affected rows - if (!\$this->alreadyInSave) { - \$this->alreadyInSave = true; -"; - if ($reloadOnInsert || $reloadOnUpdate) { - $script .= " - \$reloadObject = false; -"; - } - - if (count($table->getForeignKeys())) { - - $script .= " - // We call the save method on the following object(s) if they - // were passed to this object by their coresponding set - // method. This object relates to these object(s) by a - // foreign key reference. -"; - - foreach ($table->getForeignKeys() as $fk) { - $aVarName = $this->getFKVarName($fk); - $script .= " - if (\$this->$aVarName !== null) { - if (\$this->" . $aVarName . "->isModified() || \$this->" . $aVarName . "->isNew()) { - \$affectedRows += \$this->" . $aVarName . "->save(\$con); - } - \$this->set".$this->getFKPhpNameAffix($fk, $plural = false)."(\$this->$aVarName); - } -"; - } // foreach foreign k - } // if (count(foreign keys)) - - if ($table->hasAutoIncrementPrimaryKey() ) { - $script .= " - if (\$this->isNew() ) { - \$this->modifiedColumns[] = " . $this->getColumnConstant($table->getAutoIncrementPrimaryKey() ) . "; - }"; - } - - $script .= " - - // If this object has been modified, then save it to the database. - if (\$this->isModified()) { - if (\$this->isNew()) { - \$criteria = \$this->buildCriteria();"; - - - foreach ($table->getColumns() as $col) { - if ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && !$table->isAllowPkInsert()) { - $colConst = $this->getColumnConstant($col); - $script .= " - if (\$criteria->keyContainsValue(" . $colConst . ") ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('." . $colConst . ".')'); - } -"; - if (!$this->getPlatform()->supportsInsertNullPk()) { - $script .= " - // remove pkey col since this table uses auto-increment and passing a null value for it is not valid - \$criteria->remove(" . $colConst . "); -"; - } - } elseif ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && $table->isAllowPkInsert() && !$this->getPlatform()->supportsInsertNullPk()) { - $script .= " - // remove pkey col if it is null since this table does not accept that - if (\$criteria->containsKey(" . $colConst . ") && !\$criteria->keyContainsValue(" . $colConst . ") ) { - \$criteria->remove(" . $colConst . "); - }"; - } - } - - $script .= " - \$pk = " . $this->getNewPeerBuilder($table)->getBasePeerClassname() . "::doInsert(\$criteria, \$con);"; - if ($reloadOnInsert) { - $script .= " - if (!\$skipReload) { - \$reloadObject = true; - }"; - } - $operator = count($table->getForeignKeys()) ? '+=' : '='; - $script .= " - \$affectedRows " . $operator . " 1;"; - if ($table->getIdMethod() != IDMethod::NO_ID_METHOD) { - - if (count($pks = $table->getPrimaryKey())) { - foreach ($pks as $pk) { - if ($pk->isAutoIncrement()) { - if ($table->isAllowPkInsert()) { - $script .= " - if (\$pk !== null) { - \$this->set".$pk->getPhpName()."(\$pk); //[IMV] update autoincrement primary key - }"; - } else { - $script .= " - \$this->set".$pk->getPhpName()."(\$pk); //[IMV] update autoincrement primary key"; - } - } - } - } - } // if (id method != "none") - - $script .= " - \$this->setNew(false); - } else {"; - if ($reloadOnUpdate) { - $script .= " - if (!\$skipReload) { - \$reloadObject = true; - }"; - } - $operator = count($table->getForeignKeys()) ? '+=' : '='; - $script .= " - \$affectedRows " . $operator . " ".$this->getPeerClassname()."::doUpdate(\$this, \$con); - } -"; - - // We need to rewind any LOB columns - foreach ($table->getColumns() as $col) { - $clo = strtolower($col->getName()); - if ($col->isLobType()) { - $script .= " - // Rewind the $clo LOB column, since PDO does not rewind after inserting value. - if (\$this->$clo !== null && is_resource(\$this->$clo)) { - rewind(\$this->$clo); - } -"; - } - } - - $script .= " - \$this->resetModified(); // [HL] After being saved an object is no longer 'modified' - } -"; - - foreach ($table->getReferrers() as $refFK) { - - if ($refFK->isLocalPrimaryKey()) { - $varName = $this->getPKRefFKVarName($refFK); - $script .= " - if (\$this->$varName !== null) { - if (!\$this->{$varName}->isDeleted()) { - \$affectedRows += \$this->{$varName}->save(\$con); - } - } -"; - } else { - $collName = $this->getRefFKCollVarName($refFK); - $script .= " - if (\$this->$collName !== null) { - foreach (\$this->$collName as \$referrerFK) { - if (!\$referrerFK->isDeleted()) { - \$affectedRows += \$referrerFK->save(\$con); - } - } - } -"; - } // if refFK->isLocalPrimaryKey() - - } /* foreach getReferrers() */ - $script .= " - \$this->alreadyInSave = false; -"; - if ($reloadOnInsert || $reloadOnUpdate) { - $script .= " - if (\$reloadObject) { - \$this->reload(\$con); - } -"; - } - $script .= " - } - return \$affectedRows; - } // doSave() -"; - - } - - /** - * Adds the $alreadyInSave attribute, which prevents attempting to re-save the same object. - * @param string &$script The script will be modified in this method. - */ - protected function addAlreadyInSaveAttribute(&$script) - { - $script .= " - /** - * Flag to prevent endless save loop, if this object is referenced - * by another object which falls in this transaction. - * @var boolean - */ - protected \$alreadyInSave = false; -"; - } - - /** - * Adds the save() method. - * @param string &$script The script will be modified in this method. - */ - protected function addSave(&$script) - { - $this->addSaveComment($script); - $this->addSaveOpen($script); - $this->addSaveBody($script); - $this->addSaveClose($script); - } - - /** - * Adds the comment for the save method - * @param string &$script The script will be modified in this method. - * @see addSave() - **/ - protected function addSaveComment(&$script) { - $table = $this->getTable(); - $reloadOnUpdate = $table->isReloadOnUpdate(); - $reloadOnInsert = $table->isReloadOnInsert(); - - $script .= " - /** - * Persists this object to the database. - * - * If the object is new, it inserts it; otherwise an update is performed. - * All modified related objects will also be persisted in the doSave() - * method. This method wraps all precipitate database operations in a - * single transaction."; - if ($reloadOnUpdate) { - $script .= " - * - * Since this table was configured to reload rows on update, the object will - * be reloaded from the database if an UPDATE operation is performed (unless - * the \$skipReload parameter is TRUE)."; - } - if ($reloadOnInsert) { - $script .= " - * - * Since this table was configured to reload rows on insert, the object will - * be reloaded from the database if an INSERT operation is performed (unless - * the \$skipReload parameter is TRUE)."; - } - $script .= " - * - * @param PropelPDO \$con"; - if ($reloadOnUpdate || $reloadOnInsert) { - $script .= " - * @param boolean \$skipReload Whether to skip the reload for this object from database."; - } - $script .= " - * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. - * @throws PropelException - * @see doSave() - */"; - } - - /** - * Adds the function declaration for the save method - * @param string &$script The script will be modified in this method. - * @see addSave() - **/ - protected function addSaveOpen(&$script) { - $table = $this->getTable(); - $reloadOnUpdate = $table->isReloadOnUpdate(); - $reloadOnInsert = $table->isReloadOnInsert(); - $script .= " - public function save(PropelPDO \$con = null".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload = false" : "").") - {"; - } - - /** - * Adds the function body for the save method - * @param string &$script The script will be modified in this method. - * @see addSave() - **/ - protected function addSaveBody(&$script) { - $table = $this->getTable(); - $reloadOnUpdate = $table->isReloadOnUpdate(); - $reloadOnInsert = $table->isReloadOnInsert(); - - $script .= " - if (\$this->isDeleted()) { - throw new PropelException(\"You cannot save an object that has been deleted.\"); - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$con->beginTransaction(); - \$isInsert = \$this->isNew(); - try {"; - - if($this->getGeneratorConfig()->getBuildProperty('addHooks')) { - // save with runtime hools - $script .= " - \$ret = \$this->preSave(\$con);"; - $this->applyBehaviorModifier('preSave', $script, " "); - $script .= " - if (\$isInsert) { - \$ret = \$ret && \$this->preInsert(\$con);"; - $this->applyBehaviorModifier('preInsert', $script, " "); - $script .= " - } else { - \$ret = \$ret && \$this->preUpdate(\$con);"; - $this->applyBehaviorModifier('preUpdate', $script, " "); - $script .= " - } - if (\$ret) { - \$affectedRows = \$this->doSave(\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "")."); - if (\$isInsert) { - \$this->postInsert(\$con);"; - $this->applyBehaviorModifier('postInsert', $script, " "); - $script .= " - } else { - \$this->postUpdate(\$con);"; - $this->applyBehaviorModifier('postUpdate', $script, " "); - $script .= " - } - \$this->postSave(\$con);"; - $this->applyBehaviorModifier('postSave', $script, " "); - $script .= " - ".$this->getPeerClassname()."::addInstanceToPool(\$this); - } else { - \$affectedRows = 0; - } - \$con->commit(); - return \$affectedRows;"; - } else { - // save without runtime hooks - $this->applyBehaviorModifier('preSave', $script, " "); - if ($this->hasBehaviorModifier('preUpdate')) - { - $script .= " - if(!\$isInsert) {"; - $this->applyBehaviorModifier('preUpdate', $script, " "); - $script .= " - }"; - } - if ($this->hasBehaviorModifier('preInsert')) - { - $script .= " - if(\$isInsert) {"; - $this->applyBehaviorModifier('preInsert', $script, " "); - $script .= " - }"; - } - $script .= " - \$affectedRows = \$this->doSave(\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "").");"; - $this->applyBehaviorModifier('postSave', $script, " "); - if ($this->hasBehaviorModifier('postUpdate')) - { - $script .= " - if(!\$isInsert) {"; - $this->applyBehaviorModifier('postUpdate', $script, " "); - $script .= " - }"; - } - if ($this->hasBehaviorModifier('postInsert')) - { - $script .= " - if(\$isInsert) {"; - $this->applyBehaviorModifier('postInsert', $script, " "); - $script .= " - }"; - } - $script .= " - \$con->commit(); - ".$this->getPeerClassname()."::addInstanceToPool(\$this); - return \$affectedRows;"; - } - - $script .= " - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - }"; - } - - /** - * Adds the function close for the save method - * @param string &$script The script will be modified in this method. - * @see addSave() - **/ - protected function addSaveClose(&$script) { - $script .= " - } -"; - } - - /** - * Adds the $alreadyInValidation attribute, which prevents attempting to re-validate the same object. - * @param string &$script The script will be modified in this method. - */ - protected function addAlreadyInValidationAttribute(&$script) - { - $script .= " - /** - * Flag to prevent endless validation loop, if this object is referenced - * by another object which falls in this transaction. - * @var boolean - */ - protected \$alreadyInValidation = false; -"; - } - - /** - * Adds the validate() method. - * @param string &$script The script will be modified in this method. - */ - protected function addValidate(&$script) - { - $script .= " - /** - * Validates the objects modified field values and all objects related to this table. - * - * If \$columns is either a column name or an array of column names - * only those columns are validated. - * - * @param mixed \$columns Column name or an array of column names. - * @return boolean Whether all columns pass validation. - * @see doValidate() - * @see getValidationFailures() - */ - public function validate(\$columns = null) - { - \$res = \$this->doValidate(\$columns); - if (\$res === true) { - \$this->validationFailures = array(); - return true; - } else { - \$this->validationFailures = \$res; - return false; - } - } -"; - } // addValidate() - - /** - * Adds the workhourse doValidate() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoValidate(&$script) - { - $table = $this->getTable(); - - $script .= " - /** - * This function performs the validation work for complex object models. - * - * In addition to checking the current object, all related objects will - * also be validated. If all pass then true is returned; otherwise - * an aggreagated array of ValidationFailed objects will be returned. - * - * @param array \$columns Array of column names to validate. - * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. - */ - protected function doValidate(\$columns = null) - { - if (!\$this->alreadyInValidation) { - \$this->alreadyInValidation = true; - \$retval = null; - - \$failureMap = array(); -"; - if (count($table->getForeignKeys()) != 0) { - $script .= " - - // We call the validate method on the following object(s) if they - // were passed to this object by their coresponding set - // method. This object relates to these object(s) by a - // foreign key reference. -"; - foreach ($table->getForeignKeys() as $fk) { - $aVarName = $this->getFKVarName($fk); - $script .= " - if (\$this->".$aVarName." !== null) { - if (!\$this->".$aVarName."->validate(\$columns)) { - \$failureMap = array_merge(\$failureMap, \$this->".$aVarName."->getValidationFailures()); - } - } -"; - } /* for () */ - } /* if count(fkeys) */ - - $script .= " - - if ((\$retval = ".$this->getPeerClassname()."::doValidate(\$this, \$columns)) !== true) { - \$failureMap = array_merge(\$failureMap, \$retval); - } - -"; - - foreach ($table->getReferrers() as $refFK) { - if ($refFK->isLocalPrimaryKey()) { - $varName = $this->getPKRefFKVarName($refFK); - $script .= " - if (\$this->$varName !== null) { - if (!\$this->".$varName."->validate(\$columns)) { - \$failureMap = array_merge(\$failureMap, \$this->".$varName."->getValidationFailures()); - } - } -"; - } else { - $collName = $this->getRefFKCollVarName($refFK); - $script .= " - if (\$this->$collName !== null) { - foreach (\$this->$collName as \$referrerFK) { - if (!\$referrerFK->validate(\$columns)) { - \$failureMap = array_merge(\$failureMap, \$referrerFK->getValidationFailures()); - } - } - } -"; - } - } /* foreach getReferrers() */ - - $script .= " - - \$this->alreadyInValidation = false; - } - - return (!empty(\$failureMap) ? \$failureMap : true); - } -"; - } // addDoValidate() - - /** - * Adds the ensureConsistency() method to ensure that internal state is correct. - * @param string &$script The script will be modified in this method. - */ - protected function addEnsureConsistency(&$script) - { - $table = $this->getTable(); - - $script .= " - /** - * Checks and repairs the internal consistency of the object. - * - * This method is executed after an already-instantiated object is re-hydrated - * from the database. It exists to check any foreign keys to make sure that - * the objects related to the current object are correct based on foreign key. - * - * You can override this method in the stub class, but you should always invoke - * the base method from the overridden method (i.e. parent::ensureConsistency()), - * in case your model changes. - * - * @throws PropelException - */ - public function ensureConsistency() - { -"; - foreach ($table->getColumns() as $col) { - - $clo=strtolower($col->getName()); - - if ($col->isForeignKey()) { - foreach ($col->getForeignKeys() as $fk) { - - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - $colFK = $tblFK->getColumn($fk->getMappedForeignColumn($col->getName())); - $varName = $this->getFKVarName($fk); - - $script .= " - if (\$this->".$varName." !== null && \$this->$clo !== \$this->".$varName."->get".$colFK->getPhpName()."()) { - \$this->$varName = null; - }"; - } // foraech - } /* if col is foreign key */ - - } // foreach - - $script .= " - } // ensureConsistency -"; - } // addCheckRelConsistency - - /** - * Adds the copy() method, which (in complex OM) includes the $deepCopy param for making copies of related objects. - * @param string &$script The script will be modified in this method. - */ - protected function addCopy(&$script) - { - $this->addCopyInto($script); - - $table = $this->getTable(); - - $script .= " - /** - * Makes a copy of this object that will be inserted as a new row in table when saved. - * It creates a new object filling in the simple attributes, but skipping any primary - * keys that are defined for the table. - * - * If desired, this method can also make copies of all associated (fkey referrers) - * objects. - * - * @param boolean \$deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @return ".$this->getObjectClassname()." Clone of current object. - * @throws PropelException - */ - public function copy(\$deepCopy = false) - { - // we use get_class(), because this might be a subclass - \$clazz = get_class(\$this); - " . $this->buildObjectInstanceCreationCode('$copyObj', '$clazz') . " - \$this->copyInto(\$copyObj, \$deepCopy); - return \$copyObj; - } -"; - } // addCopy() - - /** - * Adds the copyInto() method, which takes an object and sets contents to match current object. - * In complex OM this method includes the $deepCopy param for making copies of related objects. - * @param string &$script The script will be modified in this method. - */ - protected function addCopyInto(&$script) - { - $table = $this->getTable(); - - $script .= " - /** - * Sets contents of passed object to values from current object. - * - * If desired, this method can also make copies of all associated (fkey referrers) - * objects. - * - * @param object \$copyObj An object of ".$this->getObjectClassname()." (or compatible) type. - * @param boolean \$deepCopy Whether to also copy all rows that refer (by fkey) to the current row. - * @throws PropelException - */ - public function copyInto(\$copyObj, \$deepCopy = false) - {"; - - $autoIncCols = array(); - foreach ($table->getColumns() as $col) { - /* @var $col Column */ - if ($col->isAutoIncrement()) { - $autoIncCols[] = $col; - } - } - - foreach ($table->getColumns() as $col) { - if (!in_array($col, $autoIncCols, true)) { - $script .= " - \$copyObj->set".$col->getPhpName()."(\$this->".strtolower($col->getName()).");"; - } - } // foreach - - // Avoid useless code by checking to see if there are any referrers - // to this table: - if (count($table->getReferrers()) > 0) { - $script .= " - - if (\$deepCopy) { - // important: temporarily setNew(false) because this affects the behavior of - // the getter/setter methods for fkey referrer objects. - \$copyObj->setNew(false); -"; - foreach ($table->getReferrers() as $fk) { - //HL: commenting out self-referrential check below - // it seems to work as expected and is probably desireable to have those referrers from same table deep-copied. - //if ( $fk->getTable()->getName() != $table->getName() ) { - - if ($fk->isLocalPrimaryKey()) { - - $afx = $this->getRefFKPhpNameAffix($fk, $plural = false); - $script .= " - \$relObj = \$this->get$afx(); - if (\$relObj) { - \$copyObj->set$afx(\$relObj->copy(\$deepCopy)); - } -"; - } else { - - $script .= " - foreach (\$this->get".$this->getRefFKPhpNameAffix($fk, true)."() as \$relObj) { - if (\$relObj !== \$this) { // ensure that we don't try to copy a reference to ourselves - \$copyObj->add".$this->getRefFKPhpNameAffix($fk)."(\$relObj->copy(\$deepCopy)); - } - } -"; - } - // HL: commenting out close of self-referential check - // } /* if tblFK != table */ - } /* foreach */ - $script .= " - } // if (\$deepCopy) -"; - } /* if (count referrers > 0 ) */ - - $script .= " - - \$copyObj->setNew(true);"; - - // Note: we're no longer resetting non-autoincrement primary keys to default values - // due to: http://propel.phpdb.org/trac/ticket/618 - foreach ($autoIncCols as $col) { - $coldefval = $col->getPhpDefaultValue(); - $coldefval = var_export($coldefval, true); - $script .= " - \$copyObj->set".$col->getPhpName() ."($coldefval); // this is a auto-increment column, so set to default value"; - } // foreach - $script .= " - } -"; - } // addCopyInto() - - /** - * Adds clear method - * @param string &$script The script will be modified in this method. - */ - protected function addClear(&$script) - { - $table = $this->getTable(); - - $script .= " - /** - * Clears the current object and sets all attributes to their default values - */ - public function clear() - {"; - foreach ($table->getColumns() as $col) { - $script .= " - \$this->" . strtolower($col->getName()) . " = null;"; - } - - $script .= " - \$this->alreadyInSave = false; - \$this->alreadyInValidation = false; - \$this->clearAllReferences();"; - - if ($this->hasDefaultValues()) { - $script .= " - \$this->applyDefaultValues();"; - } - - $script .= " - \$this->resetModified(); - \$this->setNew(true); - \$this->setDeleted(false); - } -"; - } - - - /** - * Adds clearAllReferencers() method which resets all the collections of referencing - * fk objects. - * @param string &$script The script will be modified in this method. - */ - protected function addClearAllReferences(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Resets all collections of referencing foreign keys. - * - * This method is a user-space workaround for PHP's inability to garbage collect objects - * with circular references. This is currently necessary when using Propel in certain - * daemon or large-volumne/high-memory operations. - * - * @param boolean \$deep Whether to also clear the references on all associated objects. - */ - public function clearAllReferences(\$deep = false) - { - if (\$deep) {"; - $vars = array(); - foreach ($this->getTable()->getReferrers() as $refFK) { - if ($refFK->isLocalPrimaryKey()) { - $varName = $this->getPKRefFKVarName($refFK); - $vars[] = $varName; - $script .= " - if (\$this->$varName) { - \$this->{$varName}->clearAllReferences(\$deep); - }"; - } else { - $varName = $this->getRefFKCollVarName($refFK); - $vars[] = $varName; - $script .= " - if (\$this->$varName) { - foreach ((array) \$this->$varName as \$o) { - \$o->clearAllReferences(\$deep); - } - }"; - } - } - - $script .= " - } // if (\$deep) -"; - - $this->applyBehaviorModifier('objectClearReferences', $script, " "); - - foreach ($vars as $varName) { - $script .= " - \$this->$varName = null;"; - } - - foreach ($table->getForeignKeys() as $fk) { - $className = $this->getForeignTable($fk)->getPhpName(); - $varName = $this->getFKVarName($fk); - $script .= " - \$this->$varName = null;"; - } - - $script .= " - } -"; - } - - /** - * Adds a magic __toString() method if a string column was defined as primary string - * @param string &$script The script will be modified in this method. - */ - protected function addPrimaryString(&$script) - { - foreach ($this->getTable()->getColumns() as $column) { - if ($column->isPrimaryString()) { - $script .= " - /** - * Return the string representation of this object - * - * @return string The value of the '{$column->getName()}' column - */ - public function __toString() - { - return (string) \$this->get{$column->getPhpName()}(); - } -"; - break; - } - } - } - - /** - * Adds a magic __call() method - * @param string &$script The script will be modified in this method. - */ - protected function addMagicCall(&$script) - { - $script .= " - /** - * Catches calls to virtual methods - */ - public function __call(\$name, \$params) - {"; - $this->applyBehaviorModifier('objectCall', $script, " "); - $script .= " - if (preg_match('/get(\w+)/', \$name, \$matches)) { - \$virtualColumn = \$matches[1]; - if (\$this->hasVirtualColumn(\$virtualColumn)) { - return \$this->getVirtualColumn(\$virtualColumn); - } - // no lcfirst in php<5.3... - \$virtualColumn[0] = strtolower(\$virtualColumn[0]); - if (\$this->hasVirtualColumn(\$virtualColumn)) { - return \$this->getVirtualColumn(\$virtualColumn); - } - } - throw new PropelException('Call to undefined method: ' . \$name); - } -"; - } -} // PHP5ObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php deleted file mode 100644 index 8b96998a9..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php +++ /dev/null @@ -1,962 +0,0 @@ - - * propel.builder.object.class = builder.om.PHP5ObjectNoCollectionBuilder - * - * - * @deprecated Since Propel 1.5 - * @author Hans Lellelid - * @package propel.generator.builder.om - */ -class PHP5ObjectNoCollectionBuilder extends PHP5ObjectBuilder -{ - - /** - * Adds the lazy loader method. - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see parent::addColumnAccessors() - */ - protected function addLazyLoader(&$script, Column $col) - { - $this->addLazyLoaderComment($script, $col); - $this->addLazyLoaderOpen($script, $col); - $this->addLazyLoaderBody($script, $col); - $this->addLazyLoaderClose($script, $col); - } - - /** - * Adds the comment for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderComment(&$script, Column $col) { - $clo = strtolower($col->getName()); - - $script .= " - /** - * Load the value for the lazy-loaded [$clo] column. - * - * This method performs an additional query to return the value for - * the [$clo] column, since it is not populated by - * the hydrate() method. - * - * @param \$con PropelPDO (optional) The PropelPDO connection to use. - * @return void - * @throws PropelException - any underlying error will be wrapped and re-thrown. - */"; - } - - /** - * Adds the function declaration for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderOpen(&$script, Column $col) { - $cfc = $col->getPhpName(); - $script .= " - protected function load$cfc(PropelPDO \$con = null) - {"; - } - - /** - * Adds the function body for the lazy loader method - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderBody(&$script, Column $col) { - $platform = $this->getPlatform(); - $clo = strtolower($col->getName()); - - $script .= " - \$c = \$this->buildPkeyCriteria(); - \$c->addSelectColumn(".$this->getColumnConstant($col)."); - try { - \$stmt = ".$this->getPeerClassname()."::doSelectStmt(\$c, \$con); - \$row = \$stmt->fetch(PDO::FETCH_NUM); - \$stmt->closeCursor();"; - - if ($col->getType() === PropelTypes::CLOB && $this->getPlatform() instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[0]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { - $script .= " - if (\$row[0] !== null) { - \$this->$clo = fopen('php://memory', 'r+'); - fwrite(\$this->$clo, \$row[0]); - rewind(\$this->$clo); - } else { - \$this->$clo = null; - }"; - } elseif ($col->isPhpPrimitiveType()) { - $script .= " - \$this->$clo = (\$row[0] !== null) ? (".$col->getPhpType().") \$row[0] : null;"; - } elseif ($col->isPhpObjectType()) { - $script .= " - \$this->$clo = (\$row[0] !== null) ? new ".$col->getPhpType()."(\$row[0]) : null;"; - } else { - $script .= " - \$this->$clo = \$row[0];"; - } - - $script .= " - \$this->".$clo."_isLoaded = true; - } catch (Exception \$e) { - throw new PropelException(\"Error loading value for [$clo] column on demand.\", \$e); - }"; - } - - /** - * Adds the function close for the lazy loader - * @param string &$script The script will be modified in this method. - * @param Column $col The current column. - * @see addLazyLoader() - **/ - protected function addLazyLoaderClose(&$script, Column $col) { - $script .= " - }"; - } // addLazyLoader() - - /** - * Adds the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - **/ - protected function addBuildPkeyCriteria(&$script) { - $this->addBuildPkeyCriteriaComment($script); - $this->addBuildPkeyCriteriaOpen($script); - $this->addBuildPkeyCriteriaBody($script); - $this->addBuildPkeyCriteriaClose($script); - } - - /** - * Adds the comment for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaComment(&$script) { - $script .= " - /** - * Builds a Criteria object containing the primary key for this object. - * - * Unlike buildCriteria() this method includes the primary key values regardless - * of whether or not they have been modified. - * - * @return Criteria The Criteria object containing value(s) for primary key(s). - */"; - } - - /** - * Adds the function declaration for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaOpen(&$script) { - $script .= " - public function buildPkeyCriteria() - {"; - } - - /** - * Adds the function body for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaBody(&$script) { - $script .= " - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME);"; - foreach ($this->getTable()->getColumns() as $col) { - $clo = strtolower($col->getName()); - if ($col->isPrimaryKey()) { - $script .= " - \$criteria->add(".$this->getColumnConstant($col).", \$this->$clo);"; - } - } - } - - /** - * Adds the function close for the buildPkeyCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildPkeyCriteria() - **/ - protected function addBuildPkeyCriteriaClose(&$script) { - $script .= " - - return \$criteria; - } -"; - } - - /** - * Adds the buildCriteria method - * @param string &$script The script will be modified in this method. - **/ - protected function addBuildCriteria(&$script) - { - $this->addBuildCriteriaComment($script); - $this->addBuildCriteriaOpen($script); - $this->addBuildCriteriaBody($script); - $this->addBuildCriteriaClose($script); - } - - /** - * Adds comment for the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaComment(&$script) { - $script .= " - /** - * Build a Criteria object containing the values of all modified columns in this object. - * - * @return Criteria The Criteria object containing all modified values. - */"; - } - - /** - * Adds the function declaration of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaOpen(&$script) { - $script .= " - public function buildCriteria() - {"; - } - - /** - * Adds the function body of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaBody(&$script) { - $script .= " - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME); -"; - foreach ($this->getTable()->getColumns() as $col) { - $clo = strtolower($col->getName()); - $script .= " - if (\$this->isColumnModified(".$this->getColumnConstant($col).")) \$criteria->add(".$this->getColumnConstant($col).", \$this->$clo);"; - } - } - - /** - * Adds the function close of the buildCriteria method - * @param string &$script The script will be modified in this method. - * @see addBuildCriteria() - **/ - protected function addBuildCriteriaClose(&$script) { - $script .= " - - return \$criteria; - } -"; - } - - /** - * Adds the function body for the delete function - * @param string &$script The script will be modified in this method. - * @see addDelete() - **/ - protected function addDeleteBody(&$script) { - $script .= " - if (\$this->isDeleted()) { - throw new PropelException(\"This object has already been deleted.\"); - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$con->beginTransaction(); - try {"; - if($this->getGeneratorConfig()->getBuildProperty('addHooks')) { - $script .= " - \$ret = \$this->preDelete(\$con);"; - // apply behaviors - $this->applyBehaviorModifier('preDelete', $script, " "); - $script .= " - if (\$ret) { - ".$this->getPeerClassname()."::doDelete(\$this, \$con); - \$this->postDelete(\$con);"; - // apply behaviors - $this->applyBehaviorModifier('postDelete', $script, " "); - $script .= " - \$con->commit(); - \$this->setDeleted(true); - } else { - \$con->commit(); - }"; - } else { - // apply behaviors - $this->applyBehaviorModifier('preDelete', $script, " "); - $script .= " - ".$this->getPeerClassname()."::doDelete(\$this, \$con);"; - // apply behaviors - $this->applyBehaviorModifier('postDelete', $script, " "); - $script .= " - \$con->commit(); - \$this->setDeleted(true);"; - } - - $script .= " - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - }"; - } - - /** - * Adds a reload() method to re-fetch the data for this object from the database. - * @param string &$script The script will be modified in this method. - */ - protected function addReload(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. - * - * This will only work if the object has been saved and has a valid primary key set. - * - * @param boolean \$deep (optional) Whether to also de-associated any related objects. - * @param PropelPDO \$con (optional) The PropelPDO connection to use. - * @return void - * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db - */ - public function reload(\$deep = false, PropelPDO \$con = null) - { - if (\$this->isDeleted()) { - throw new PropelException(\"Cannot reload a deleted object.\"); - } - - if (\$this->isNew()) { - throw new PropelException(\"Cannot reload an unsaved object.\"); - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - // We don't need to alter the object instance pool; we're just modifying this instance - // already in the pool. - - \$stmt = ".$this->getPeerClassname()."::doSelectStmt(\$this->buildPkeyCriteria(), \$con); - \$row = \$stmt->fetch(PDO::FETCH_NUM); - \$stmt->closeCursor(); - if (!\$row) { - throw new PropelException('Cannot find matching row in the database to reload object values.'); - } - \$this->hydrate(\$row, 0, true); // rehydrate -"; - - // support for lazy load columns - foreach ($table->getColumns() as $col) { - if ($col->isLazyLoad()) { - $clo = strtolower($col->getName()); - $script .= " - // Reset the $clo lazy-load column - \$this->" . $clo . " = null; - \$this->".$clo."_isLoaded = false; -"; - } - } - - $script .= " - if (\$deep) { // also de-associate any related objects? -"; - - foreach ($table->getForeignKeys() as $fk) { - $varName = $this->getFKVarName($fk); - $script .= " - \$this->".$varName." = null;"; - } - - foreach ($table->getReferrers() as $refFK) { - if ($refFK->isLocalPrimaryKey()) { - $script .= " - \$this->".$this->getPKRefFKVarName($refFK)." = null; -"; - } else { - $script .= " - \$this->".$this->getRefFKCollVarName($refFK)." = null; - \$this->".$this->getRefFKLastCriteriaVarName($refFK)." = null; -"; - } - } - - $script .= " - } // if (deep) - } -"; - } // addReload() - - /** - * Gets variable name for the Criteria which was used to fetch the objects which - * referencing current table by specified foreign key. - * @param ForeignKey $fk - * @return string - */ - protected function getRefFKLastCriteriaVarName(ForeignKey $fk) - { - return 'last' . $this->getRefFKPhpNameAffix($fk, $plural = false) . 'Criteria'; - } - - - - /** - * Adds the accessor (getter) method for getting an fkey related object. - * @param string &$script The script will be modified in this method. - */ - protected function addFKAccessor(&$script, ForeignKey $fk) - { - $table = $this->getTable(); - - $varName = $this->getFKVarName($fk); - $pCollName = $this->getFKPhpNameAffix($fk, $plural = true); - - $fkPeerBuilder = $this->getNewPeerBuilder($this->getForeignTable($fk)); - $fkObjectBuilder = $this->getNewObjectBuilder($this->getForeignTable($fk))->getStubObjectBuilder(); - $className = $fkObjectBuilder->getClassname(); // get the Classname that has maybe a prefix - - $and = ""; - $comma = ""; - $conditional = ""; - $argmap = array(); // foreign -> local mapping - $argsize = 0; - foreach ($fk->getLocalColumns() as $columnName) { - - $lfmap = $fk->getLocalForeignMapping(); - - $localColumn = $table->getColumn($columnName); - $foreignColumn = $fk->getForeignTable()->getColumn($lfmap[$columnName]); - - $column = $table->getColumn($columnName); - $cptype = $column->getPhpType(); - $clo = strtolower($column->getName()); - - if ($cptype == "integer" || $cptype == "float" || $cptype == "double") { - $conditional .= $and . "\$this->". $clo ." != 0"; - } elseif ($cptype == "string") { - $conditional .= $and . "(\$this->" . $clo ." !== \"\" && \$this->".$clo." !== null)"; - } else { - $conditional .= $and . "\$this->" . $clo ." !== null"; - } - - $argmap[] = array('foreign' => $foreignColumn, 'local' => $localColumn); - $and = " && "; - $comma = ", "; - $argsize = $argsize + 1; - } - - // If the related column is a primary kay and if it's a simple association, - // The use retrieveByPk() instead of doSelect() to take advantage of instance pooling - $useRetrieveByPk = count($argmap) == 1 && $argmap[0]['foreign']->isPrimaryKey(); - - $script .= " - - /** - * Get the associated $className object - * - * @param PropelPDO Optional Connection object. - * @return $className The associated $className object. - * @throws PropelException - */ - public function get".$this->getFKPhpNameAffix($fk, $plural = false)."(PropelPDO \$con = null) - {"; - $script .= " - if (\$this->$varName === null && ($conditional)) {"; - if ($useRetrieveByPk) { - $script .= " - \$this->$varName = ".$fkPeerBuilder->getPeerClassname()."::retrieveByPk(\$this->$clo);"; - } else { - $script .= " - \$c = new Criteria(".$fkPeerBuilder->getPeerClassname()."::DATABASE_NAME);"; - foreach ($argmap as $el) { - $fcol = $el['foreign']; - $lcol = $el['local']; - $clo = strtolower($lcol->getName()); - $script .= " - \$c->add(".$fkPeerBuilder->getColumnConstant($fcol).", \$this->".$clo.");"; - } - $script .= " - \$this->$varName = ".$fkPeerBuilder->getPeerClassname()."::doSelectOne(\$c, \$con);"; - } - if ($fk->isLocalPrimaryKey()) { - $script .= " - // Because this foreign key represents a one-to-one relationship, we will create a bi-directional association. - \$this->{$varName}->set".$this->getRefFKPhpNameAffix($fk, $plural = false)."(\$this);"; - } else { - $script .= " - /* The following can be used additionally to - guarantee the related object contains a reference - to this object. This level of coupling may, however, be - undesirable since it could result in an only partially populated collection - in the referenced object. - \$this->{$varName}->add".$this->getRefFKPhpNameAffix($fk, $plural = true)."(\$this); - */"; - } - - $script .= " - } - return \$this->$varName; - } -"; - - } // addFKAccessor - - - /** - * Adds the method that fetches fkey-related (referencing) objects but also joins in data from another table. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKGetJoinMethods(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - $join_behavior = $this->getGeneratorConfig()->getBuildProperty('useLeftJoinsInDoJoinMethods') ? 'Criteria::LEFT_JOIN' : 'Criteria::INNER_JOIN'; - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural=true); - $collName = $this->getRefFKCollVarName($refFK); - $lastCriteriaName = $this->getRefFKLastCriteriaVarName($refFK); - - $fkPeerBuilder = $this->getNewPeerBuilder($tblFK); - - $lastTable = ""; - foreach ($tblFK->getForeignKeys() as $fk2) { - - $tblFK2 = $this->getForeignTable($fk2); - $doJoinGet = !$tblFK2->isForReferenceOnly(); - - // it doesn't make sense to join in rows from the curent table, since we are fetching - // objects related to *this* table (i.e. the joined rows will all be the same row as current object) - if ($this->getTable()->getPhpName() == $tblFK2->getPhpName()) { - $doJoinGet = false; - } - - $relCol2 = $this->getFKPhpNameAffix($fk2, $plural = false); - - if ( $this->getRelatedBySuffix($refFK) != "" && - ($this->getRelatedBySuffix($refFK) == $this->getRelatedBySuffix($fk2))) { - $doJoinGet = false; - } - - if ($doJoinGet) { - $script .= " - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this ".$table->getPhpName()." is new, it will return - * an empty collection; or if this ".$table->getPhpName()." has previously - * been saved, it will retrieve related $relCol from storage. - * - * This method is protected by default in order to keep the public - * api reasonable. You can provide public methods for those you - * actually need in ".$table->getPhpName().". - */ - public function get".$relCol."Join".$relCol2."(\$criteria = null, \$con = null, \$join_behavior = $join_behavior) - {"; - $script .= " - if (\$criteria === null) { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - } - elseif (\$criteria instanceof Criteria) - { - \$criteria = clone \$criteria; - } - - if (\$this->$collName === null) { - if (\$this->isNew()) { - \$this->$collName = array(); - } else { -"; - foreach ($refFK->getForeignColumns() as $columnName) { - $column = $table->getColumn($columnName); - $flMap = $refFK->getForeignLocalMapping(); - $colFKName = $flMap[$columnName]; - $colFK = $tblFK->getColumn($colFKName); - if ($colFK === null) { - throw new EngineException("Column $colFKName not found in " . $tblFK->getName()); - } - $clo = strtolower($column->getName()); - $script .= " - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } // end foreach ($fk->getForeignColumns() - - $script .= " - \$this->$collName = ".$fkPeerBuilder->getPeerClassname()."::doSelectJoin$relCol2(\$criteria, \$con, \$join_behavior); - } - } else { - // the following code is to determine if a new query is - // called for. If the criteria is the same as the last - // one, just return the collection. -"; - foreach ($refFK->getForeignColumns() as $columnName) { - $column = $table->getColumn($columnName); - $flMap = $refFK->getForeignLocalMapping(); - $colFKName = $flMap[$columnName]; - $colFK = $tblFK->getColumn($colFKName); - $clo = strtolower($column->getName()); - $script .= " - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } /* end foreach ($fk->getForeignColumns() */ - - $script .= " - if (!isset(\$this->$lastCriteriaName) || !\$this->".$lastCriteriaName."->equals(\$criteria)) { - \$this->$collName = ".$fkPeerBuilder->getPeerClassname()."::doSelectJoin$relCol2(\$criteria, \$con, \$join_behavior); - } - } - \$this->$lastCriteriaName = \$criteria; - - return \$this->$collName; - } -"; - } /* end if ($doJoinGet) */ - - } /* end foreach ($tblFK->getForeignKeys() as $fk2) { */ - - } // function - - /** - * Adds the method that initializes the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKInit(&$script, ForeignKey $refFK) { - - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - $collName = $this->getRefFKCollVarName($refFK); - - $script .= " - /** - * Initializes the $collName collection (array). - * - * By default this just sets the $collName collection to an empty array (like clear$collName()); - * however, you may wish to override this method in your stub class to provide setting appropriate - * to your application -- for example, setting the initial array to the values stored in database. - * - * @return void - */ - public function init$relCol() - { - \$this->$collName = array(); - } -"; - } // addRefererInit() - - /** - * Adds the method that adds an object into the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKAdd(&$script, ForeignKey $refFK) - { - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $collName = $this->getRefFKCollVarName($refFK); - - $script .= " - /** - * Method called to associate a $className object to this object - * through the $className foreign key attribute. - * - * @param $className \$l $className - * @return void - * @throws PropelException - */ - public function add".$this->getRefFKPhpNameAffix($refFK, $plural = false)."($className \$l) - { - if (\$this->$collName === null) { - \$this->init".$this->getRefFKPhpNameAffix($refFK, $plural = true)."(); - } - if (!in_array(\$l, \$this->$collName, true)) { // only add it if the **same** object is not already associated - array_push(\$this->$collName, \$l); - \$l->set".$this->getFKPhpNameAffix($refFK, $plural = false)."(\$this); - } - } -"; - } // addRefererAdd - - /** - * Adds the method that returns the size of the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKCount(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - - $fkPeerBuilder = $this->getNewPeerBuilder($refFK->getTable()); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - - $collName = $this->getRefFKCollVarName($refFK); - $lastCriteriaName = $this->getRefFKLastCriteriaVarName($refFK); - - $className = $fkPeerBuilder->getObjectClassname(); - - $script .= " - /** - * Returns the number of related $className objects. - * - * @param Criteria \$criteria - * @param boolean \$distinct - * @param PropelPDO \$con - * @return int Count of related $className objects. - * @throws PropelException - */ - public function count$relCol(Criteria \$criteria = null, \$distinct = false, PropelPDO \$con = null) - {"; - - $script .= " - if (\$criteria === null) { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - } else { - \$criteria = clone \$criteria; - } - - if (\$distinct) { - \$criteria->setDistinct(); - } - - \$count = null; - - if (\$this->$collName === null) { - if (\$this->isNew()) { - \$count = 0; - } else { -"; - foreach ($refFK->getLocalColumns() as $colFKName) { - // $colFKName is local to the referring table (i.e. foreign to this table) - $lfmap = $refFK->getLocalForeignMapping(); - $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]); - $colFK = $refFK->getTable()->getColumn($colFKName); - $clo = strtolower($localColumn->getName()); - $script .= " - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } // end foreach ($fk->getForeignColumns() - - $script .= " - \$count = ".$fkPeerBuilder->getPeerClassname()."::doCount(\$criteria, false, \$con); - } - } else { - // criteria has no effect for a new object - if (!\$this->isNew()) { - // the following code is to determine if a new query is - // called for. If the criteria is the same as the last - // one, just return count of the collection. -"; - foreach ($refFK->getLocalColumns() as $colFKName) { - // $colFKName is local to the referring table (i.e. foreign to this table) - $lfmap = $refFK->getLocalForeignMapping(); - $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]); - $colFK = $refFK->getTable()->getColumn($colFKName); - $clo = strtolower($localColumn->getName()); - $script .= " - - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } // foreach ($fk->getForeignColumns() - $script .= " - if (!isset(\$this->$lastCriteriaName) || !\$this->".$lastCriteriaName."->equals(\$criteria)) { - \$count = ".$fkPeerBuilder->getPeerClassname()."::doCount(\$criteria, false, \$con); - } else { - \$count = count(\$this->$collName); - } - } else { - \$count = count(\$this->$collName); - } - } - return \$count; - } -"; - } // addRefererCount - - /** - * Adds the method that returns the referrer fkey collection. - * @param string &$script The script will be modified in this method. - */ - protected function addRefFKGet(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $peerClassname = $this->getStubPeerBuilder()->getClassname(); - $fkPeerBuilder = $this->getNewPeerBuilder($refFK->getTable()); - $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); - - $collName = $this->getRefFKCollVarName($refFK); - $lastCriteriaName = $this->getRefFKLastCriteriaVarName($refFK); - - $className = $fkPeerBuilder->getObjectClassname(); - - $script .= " - /** - * Gets an array of $className objects which contain a foreign key that references this object. - * - * If this collection has already been initialized with an identical Criteria, it returns the collection. - * Otherwise if this ".$this->getObjectClassname()." has previously been saved, it will retrieve - * related $relCol from storage. If this ".$this->getObjectClassname()." is new, it will return - * an empty collection or the current collection, the criteria is ignored on a new object. - * - * @param PropelPDO \$con - * @param Criteria \$criteria - * @return array {$className}[] - * @throws PropelException - */ - public function get$relCol(\$criteria = null, PropelPDO \$con = null) - {"; - - $script .= " - if (\$criteria === null) { - \$criteria = new Criteria($peerClassname::DATABASE_NAME); - } - elseif (\$criteria instanceof Criteria) - { - \$criteria = clone \$criteria; - } - - if (\$this->$collName === null) { - if (\$this->isNew()) { - \$this->$collName = array(); - } else { -"; - foreach ($refFK->getLocalColumns() as $colFKName) { - // $colFKName is local to the referring table (i.e. foreign to this table) - $lfmap = $refFK->getLocalForeignMapping(); - $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]); - $colFK = $refFK->getTable()->getColumn($colFKName); - - $clo = strtolower($localColumn->getName()); - - $script .= " - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } // end foreach ($fk->getForeignColumns() - - $script .= " - ".$fkPeerBuilder->getPeerClassname()."::addSelectColumns(\$criteria); - \$this->$collName = ".$fkPeerBuilder->getPeerClassname()."::doSelect(\$criteria, \$con); - } - } else { - // criteria has no effect for a new object - if (!\$this->isNew()) { - // the following code is to determine if a new query is - // called for. If the criteria is the same as the last - // one, just return the collection. -"; - foreach ($refFK->getLocalColumns() as $colFKName) { - // $colFKName is local to the referring table (i.e. foreign to this table) - $lfmap = $refFK->getLocalForeignMapping(); - $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]); - $colFK = $refFK->getTable()->getColumn($colFKName); - $clo = strtolower($localColumn->getName()); - $script .= " - - \$criteria->add(".$fkPeerBuilder->getColumnConstant($colFK).", \$this->$clo); -"; - } // foreach ($fk->getForeignColumns() - $script .= " - ".$fkPeerBuilder->getPeerClassname()."::addSelectColumns(\$criteria); - if (!isset(\$this->$lastCriteriaName) || !\$this->".$lastCriteriaName."->equals(\$criteria)) { - \$this->$collName = ".$fkPeerBuilder->getPeerClassname()."::doSelect(\$criteria, \$con); - } - } - } - \$this->$lastCriteriaName = \$criteria; - return \$this->$collName; - } -"; - } // addRefererGet() - - /** - * Adds the method that gets a one-to-one related referrer fkey. - * This is for one-to-one relationship special case. - * @param string &$script The script will be modified in this method. - */ - protected function addPKRefFKGet(&$script, ForeignKey $refFK) - { - $table = $this->getTable(); - $tblFK = $refFK->getTable(); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $joinedTablePeerBuilder = $this->getNewObjectBuilder($refFK->getTable()); - $className = $joinedTableObjectBuilder->getObjectClassname(); - - $varName = $this->getPKRefFKVarName($refFK); - - $script .= " - /** - * Gets a single $className object, which is related to this object by a one-to-one relationship. - * - * @param PropelPDO \$con - * @return $className - * @throws PropelException - */ - public function get".$this->getRefFKPhpNameAffix($refFK, $plural = false)."(PropelPDO \$con = null) - { -"; - $script .= " - if (\$this->$varName === null && !\$this->isNew()) {"; - - $lfmap = $refFK->getLocalForeignMapping(); - - // remember: this object represents the foreign table, - // so we need foreign columns of the reffk to know the local columns - // that we need to set :) - - $localcols = $refFK->getForeignColumns(); - - // we know that at least every column in the primary key of the foreign table - // is represented in this foreign key - - $params = array(); - foreach ($tblFK->getPrimaryKey() as $col) { - $localColumn = $table->getColumn($lfmap[$col->getName()]); - $clo = strtolower($localColumn->getName()); - $params[] = "\$this->$clo"; - } - - $script .= " - \$this->$varName = ".$joinedTableObjectBuilder->getPeerClassname()."::retrieveByPK(".implode(", ", $params).", \$con); - } - - return \$this->$varName; - } -"; - } // addPKRefFKGet() - -} // PHP5ObjectBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5PeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5PeerBuilder.php deleted file mode 100644 index bcb486b13..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5PeerBuilder.php +++ /dev/null @@ -1,2761 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5PeerBuilder extends PeerBuilder -{ - - /** - * Validates the current table to make sure that it won't - * result in generated code that will not parse. - * - * This method may emit warnings for code which may cause problems - * and will throw exceptions for errors that will definitely cause - * problems. - */ - protected function validateModel() - { - parent::validateModel(); - - $table = $this->getTable(); - - // Check to see if any of the column constants are PHP reserved words. - $colConstants = array(); - - foreach ($table->getColumns() as $col) { - $colConstants[] = $this->getColumnName($col); - } - - $reservedConstants = array_map('strtoupper', ClassTools::getPhpReservedWords()); - - $intersect = array_intersect($reservedConstants, $colConstants); - if (!empty($intersect)) { - throw new EngineException("One or more of your column names for [" . $table->getName() . "] table conflict with a PHP reserved word (" . implode(", ", $intersect) . ")"); - } - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubPeerBuilder()->getUnprefixedClassname(); - } - - /** - * Gets the package for the [base] peer classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - public function getNamespace() - { - if ($namespace = parent::getNamespace()) { - if ($this->getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceOm')) { - return $namespace . '\\' . $omns; - } else { - return $namespace; - } - } - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) { - - $tableName = $this->getTable()->getName(); - $tableDesc = $this->getTable()->getDescription(); - - $script .= " -/** - * Base static class for performing query and update operations on the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - - $extendingPeerClass = ''; - $parentClass = $this->getBehaviorContent('parentClass'); - if (null !== $parentClass) { - $extendingPeerClass = ' extends ' . $parentClass; - } elseif ($this->basePeerClassname !== 'BasePeer') { - $extendingPeerClass = ' extends ' . $this->basePeerClassname; - } - - $script .= " - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname(). $extendingPeerClass . " { -"; - } - - protected function addClassBody(&$script) - { - $this->declareClassFromBuilder($this->getStubPeerBuilder()); - $this->declareClassFromBuilder($this->getStubObjectBuilder()); - parent::addClassBody($script); - $this->declareClasses('Propel', 'PropelException', 'PropelPDO', 'BasePeer', 'Criteria', 'PDO', 'PDOStatement'); - } - - /** - * Closes class. - * Adds closing brace at end of class and the static map builder registration code. - * @param string &$script The script will be modified in this method. - * @see addStaticTableMapRegistration() - */ - protected function addClassClose(&$script) - { - // apply behaviors - $this->applyBehaviorModifier('staticMethods', $script, " "); - - $script .= " -} // " . $this->getClassname() . " -"; - $this->addStaticTableMapRegistration($script); - } - - /** - * Adds the static map builder registration code. - * @param string &$script The script will be modified in this method. - */ - protected function addStaticTableMapRegistration(&$script) - { - $table = $this->getTable(); - - $script .= " -// This is the static code needed to register the TableMap for this table with the main Propel class. -// -".$this->getClassName()."::buildTableMap(); - -"; - $this->applyBehaviorModifier('peerFilter', $script, ""); - } - - public function getTableMapClass() - { - return $this->getTablePhpName() . 'TableMap'; - } - - public function getTablePhpName() - { - return ($this->getTable()->isAbstract() ? '' : $this->getStubObjectBuilder()->getClassname()); - } - - /** - * Adds constant and variable declarations that go at the top of the class. - * @param string &$script The script will be modified in this method. - * @see addColumnNameConstants() - */ - protected function addConstantsAndAttributes(&$script) - { - $dbName = $this->getDatabase()->getName(); - $tableName = $this->getTable()->getName(); - $tablePhpName = $this->getTable()->isAbstract() ? '' : addslashes($this->getStubObjectBuilder()->getFullyQualifiedClassname()); - $script .= " - /** the default database name for this class */ - const DATABASE_NAME = '$dbName'; - - /** the table name for this class */ - const TABLE_NAME = '$tableName'; - - /** the related Propel class for this table */ - const OM_CLASS = '$tablePhpName'; - - /** A class that can be returned by this peer. */ - const CLASS_DEFAULT = '".$this->getStubObjectBuilder()->getClasspath()."'; - - /** the related TableMap class for this table */ - const TM_CLASS = '".$this->getTableMapClass()."'; - - /** The total number of columns. */ - const NUM_COLUMNS = ".$this->getTable()->getNumColumns()."; - - /** The number of lazy-loaded columns. */ - const NUM_LAZY_LOAD_COLUMNS = ".$this->getTable()->getNumLazyLoadColumns()."; -"; - $this->addColumnNameConstants($script); - $this->addInheritanceColumnConstants($script); - - $script .= " - /** - * An identiy map to hold any loaded instances of ".$this->getObjectClassname()." objects. - * This must be public so that other peer classes can access this when hydrating from JOIN - * queries. - * @var array ".$this->getObjectClassname()."[] - */ - public static \$instances = array(); - -"; - - // apply behaviors - $this->applyBehaviorModifier('staticAttributes', $script, " "); - - $this->addFieldNamesAttribute($script); - $this->addFieldKeysAttribute($script); - } - - /** - * Adds the COLUMN_NAME contants to the class definition. - * @param string &$script The script will be modified in this method. - */ - protected function addColumnNameConstants(&$script) - { - foreach ($this->getTable()->getColumns() as $col) { - $script .= " - /** the column name for the ".strtoupper($col->getName()) ." field */ - const ".$this->getColumnName($col) ." = '" . $this->getTable()->getName() . ".".strtoupper($col->getName())."'; -"; - } // foreach - } - - protected function addFieldNamesAttribute(&$script) - { - $table = $this->getTable(); - - $tableColumns = $table->getColumns(); - - $script .= " - /** - * holds an array of fieldnames - * - * first dimension keys are the type constants - * e.g. self::\$fieldNames[self::TYPE_PHPNAME][0] = 'Id' - */ - private static \$fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ("; - foreach ($tableColumns as $col) { - $script .= "'".$col->getPhpName()."', "; - } - $script .= "), - BasePeer::TYPE_STUDLYPHPNAME => array ("; - foreach ($tableColumns as $col) { - $script .= "'".$col->getStudlyPhpName()."', "; - } - $script .= "), - BasePeer::TYPE_COLNAME => array ("; - foreach ($tableColumns as $col) { - $script .= $this->getColumnConstant($col, 'self').", "; - } - $script .= "), - BasePeer::TYPE_RAW_COLNAME => array ("; - foreach ($tableColumns as $col) { - $script .= "'" . $col->getConstantColumnName() . "', "; - } - $script .= "), - BasePeer::TYPE_FIELDNAME => array ("; - foreach ($tableColumns as $col) { - $script .= "'".$col->getName()."', "; - } - $script .= "), - BasePeer::TYPE_NUM => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "$num, "; - } - $script .= ") - ); -"; - } - - protected function addFieldKeysAttribute(&$script) - { - $table = $this->getTable(); - - $tableColumns = $table->getColumns(); - - $script .= " - /** - * holds an array of keys for quick access to the fieldnames array - * - * first dimension keys are the type constants - * e.g. self::\$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 - */ - private static \$fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "'".$col->getPhpName()."' => $num, "; - } - $script .= "), - BasePeer::TYPE_STUDLYPHPNAME => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "'".$col->getStudlyPhpName()."' => $num, "; - } - $script .= "), - BasePeer::TYPE_COLNAME => array ("; - foreach ($tableColumns as $num => $col) { - $script .= $this->getColumnConstant($col, 'self')." => $num, "; - } - $script .= "), - BasePeer::TYPE_RAW_COLNAME => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "'" . $col->getConstantColumnName() . "' => $num, "; - } - $script .= "), - BasePeer::TYPE_FIELDNAME => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "'".$col->getName()."' => $num, "; - } - $script .= "), - BasePeer::TYPE_NUM => array ("; - foreach ($tableColumns as $num => $col) { - $script .= "$num, "; - } - $script .= ") - ); -"; - } // addFielKeysAttribute - - - protected function addGetFieldNames(&$script) - { - $script .= " - /** - * Returns an array of field names. - * - * @param string \$type The type of fieldnames to return: - * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @return array A list of field names - */ - - static public function getFieldNames(\$type = BasePeer::TYPE_PHPNAME) - { - if (!array_key_exists(\$type, self::\$fieldNames)) { - throw new PropelException('Method getFieldNames() expects the parameter \$type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . \$type . ' was given.'); - } - return self::\$fieldNames[\$type]; - } -"; - - } // addGetFieldNames() - - protected function addTranslateFieldName(&$script) - { - $script .= " - /** - * Translates a fieldname to another type - * - * @param string \$name field name - * @param string \$fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME - * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM - * @param string \$toType One of the class type constants - * @return string translated name of the field. - * @throws PropelException - if the specified name could not be found in the fieldname mappings. - */ - static public function translateFieldName(\$name, \$fromType, \$toType) - { - \$toNames = self::getFieldNames(\$toType); - \$key = isset(self::\$fieldKeys[\$fromType][\$name]) ? self::\$fieldKeys[\$fromType][\$name] : null; - if (\$key === null) { - throw new PropelException(\"'\$name' could not be found in the field names of type '\$fromType'. These are: \" . print_r(self::\$fieldKeys[\$fromType], true)); - } - return \$toNames[\$key]; - } -"; - } // addTranslateFieldName() - - /** - * Adds the buildTableMap() method. - * @param string &$script The script will be modified in this method. - */ - protected function addBuildTableMap(&$script) - { - $this->declareClassFromBuilder($this->getTableMapBuilder()); - $script .= " - /** - * Add a TableMap instance to the database for this peer class. - */ - public static function buildTableMap() - { - \$dbMap = Propel::getDatabaseMap(".$this->getClassname()."::DATABASE_NAME); - if (!\$dbMap->hasTable(".$this->getClassname()."::TABLE_NAME)) - { - \$dbMap->addTableObject(new ".$this->getTableMapClass()."()); - } - } -"; - } - - /** - * Adds the CLASSKEY_* and CLASSNAME_* constants used for inheritance. - * @param string &$script The script will be modified in this method. - */ - public function addInheritanceColumnConstants(&$script) - { - if ($this->getTable()->getChildrenColumn()) { - - $col = $this->getTable()->getChildrenColumn(); - $cfc = $col->getPhpName(); - - if ($col->isEnumeratedClasses()) { - - if ($col->isPhpPrimitiveNumericType()) $quote = ""; - else $quote = '"'; - - foreach ($col->getChildren() as $child) { - $childBuilder = $this->getMultiExtendObjectBuilder(); - $childBuilder->setChild($child); - - $script .= " - /** A key representing a particular subclass */ - const CLASSKEY_".strtoupper($child->getKey())." = '" . $child->getKey() . "'; -"; - - if (strtoupper($child->getClassname()) != strtoupper($child->getKey())) { - $script .= " - /** A key representing a particular subclass */ - const CLASSKEY_".strtoupper($child->getClassname())." = '" . $child->getKey() . "'; -"; - } - - $script .= " - /** A class that can be returned by this peer. */ - const CLASSNAME_".strtoupper($child->getKey())." = '". $childBuilder->getClasspath() . "'; -"; - } /* foreach children */ - } /* if col->isenumerated...() */ - } /* if table->getchildrencolumn() */ - - } // - - /** - * Adds the alias() utility method. - * @param string &$script The script will be modified in this method. - */ - protected function addAlias(&$script) - { - $script .= " - /** - * Convenience method which changes table.column to alias.column. - * - * Using this method you can maintain SQL abstraction while using column aliases. - * - * \$c->addAlias(\"alias1\", TablePeer::TABLE_NAME); - * \$c->addJoin(TablePeer::alias(\"alias1\", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); - * - * @param string \$alias The alias for the current table. - * @param string \$column The column name for current table. (i.e. ".$this->getPeerClassname()."::COLUMN_NAME). - * @return string - */ - public static function alias(\$alias, \$column) - { - return str_replace(".$this->getPeerClassname()."::TABLE_NAME.'.', \$alias.'.', \$column); - } -"; - } // addAliasMethod - - /** - * Adds the addSelectColumns() method. - * @param string &$script The script will be modified in this method. - */ - protected function addAddSelectColumns(&$script) - { - $script .= " - /** - * Add all the columns needed to create a new object. - * - * Note: any columns that were marked with lazyLoad=\"true\" in the - * XML schema will not be added to the select list and only loaded - * on demand. - * - * @param Criteria \$criteria object containing the columns to add. - * @param string \$alias optional table alias - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function addSelectColumns(Criteria \$criteria, \$alias = null) - { - if (null === \$alias) {"; - foreach ($this->getTable()->getColumns() as $col) { - if (!$col->isLazyLoad()) { - $script .= " - \$criteria->addSelectColumn(".$this->getPeerClassname()."::".$this->getColumnName($col).");"; - } // if !col->isLazyLoad - } // foreach - $script .= " - } else {"; - foreach ($this->getTable()->getColumns() as $col) { - if (!$col->isLazyLoad()) { - $script .= " - \$criteria->addSelectColumn(\$alias . '." . $col->getConstantColumnName()."');"; - } // if !col->isLazyLoad - } // foreach - $script .= " - }"; - $script .=" - } -"; - } // addAddSelectColumns() - - /** - * Adds the doCount() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoCount(&$script) - { - $script .= " - /** - * Returns the number of rows matching criteria. - * - * @param Criteria \$criteria - * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO \$con - * @return int Number of matching rows. - */ - public static function doCount(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null) - { - // we may modify criteria, so copy it first - \$criteria = clone \$criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - \$criteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME); - - if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) { - \$criteria->setDistinct(); - } - - if (!\$criteria->hasSelectClause()) { - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - } - - \$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - \$criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - }"; - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - // BasePeer returns a PDOStatement - \$stmt = ".$this->basePeerClassname."::doCount(\$criteria, \$con); - - if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$count = (int) \$row[0]; - } else { - \$count = 0; // no rows returned; we infer that means 0 matches. - } - \$stmt->closeCursor(); - return \$count; - }"; - } - - /** - * Adds the doSelectOne() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelectOne(&$script) - { - $script .= " - /** - * Method to select one object from the DB. - * - * @param Criteria \$criteria object used to create the SELECT statement. - * @param PropelPDO \$con - * @return ".$this->getObjectClassname()." - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectOne(Criteria \$criteria, PropelPDO \$con = null) - { - \$critcopy = clone \$criteria; - \$critcopy->setLimit(1); - \$objects = ".$this->getPeerClassname()."::doSelect(\$critcopy, \$con); - if (\$objects) { - return \$objects[0]; - } - return null; - }"; - } - - /** - * Adds the doSelect() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelect(&$script) - { - $script .= " - /** - * Method to do selects. - * - * @param Criteria \$criteria The Criteria object used to build the SELECT statement. - * @param PropelPDO \$con - * @return array Array of selected Objects - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelect(Criteria \$criteria, PropelPDO \$con = null) - { - return ".$this->getPeerClassname()."::populateObjects(".$this->getPeerClassname()."::doSelectStmt(\$criteria, \$con)); - }"; - } - - /** - * Adds the doSelectStmt() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelectStmt(&$script) - { - - $script .= " - /** - * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. - * - * Use this method directly if you want to work with an executed statement durirectly (for example - * to perform your own object hydration). - * - * @param Criteria \$criteria The Criteria object used to build the SELECT statement. - * @param PropelPDO \$con The connection to use - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - * @return PDOStatement The executed PDOStatement object. - * @see ".$this->basePeerClassname."::doSelect() - */ - public static function doSelectStmt(Criteria \$criteria, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - if (!\$criteria->hasSelectClause()) { - \$criteria = clone \$criteria; - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - } - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME);"; - // apply behaviors - if ($this->hasBehaviorModifier('preSelect')) - { - $this->applyBehaviorModifier('preSelect', $script); - } - $script .= " - - // BasePeer returns a PDOStatement - return ".$this->basePeerClassname."::doSelect(\$criteria, \$con); - }"; - } - - /** - * Adds the PHP code to return a instance pool key for the passed-in primary key variable names. - * - * @param array $pkphp An array of PHP var names / method calls representing complete pk. - */ - public function getInstancePoolKeySnippet($pkphp) - { - $pkphp = (array) $pkphp; // make it an array if it is not. - $script = ""; - if (count($pkphp) > 1) { - $script .= "serialize(array("; - $i = 0; - foreach ($pkphp as $pkvar) { - $script .= ($i++ ? ', ' : '') . "(string) $pkvar"; - } - $script .= "))"; - } else { - $script .= "(string) " . $pkphp[0]; - } - return $script; - } - - /** - * Creates a convenience method to add objects to an instance pool. - * @param string &$script The script will be modified in this method. - */ - protected function addAddInstanceToPool(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Adds an object to the instance pool. - * - * Propel keeps cached copies of objects in an instance pool when they are retrieved - * from the database. In some cases -- especially when you override doSelect*() - * methods in your stub classes -- you may need to explicitly add objects - * to the cache in order to ensure that the same objects are always returned by doSelect*() - * and retrieveByPK*() calls. - * - * @param ".$this->getObjectClassname()." \$value A ".$this->getObjectClassname()." object. - * @param string \$key (optional) key to use for instance map (for performance boost if key was already calculated externally). - */ - public static function addInstanceToPool(".$this->getObjectClassname()." \$obj, \$key = null) - { - if (Propel::isInstancePoolingEnabled()) { - if (\$key === null) {"; - - $pks = $this->getTable()->getPrimaryKey(); - - $php = array(); - foreach ($pks as $pk) { - $php[] = '$obj->get' . $pk->getPhpName() . '()'; - } - $script .= " - \$key = ".$this->getInstancePoolKeySnippet($php).";"; - $script .= " - } // if key === null - self::\$instances[\$key] = \$obj; - } - } -"; - } // addAddInstanceToPool() - - /** - * Creates a convenience method to remove objects form an instance pool. - * @param string &$script The script will be modified in this method. - */ - protected function addRemoveInstanceFromPool(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Removes an object from the instance pool. - * - * Propel keeps cached copies of objects in an instance pool when they are retrieved - * from the database. In some cases -- especially when you override doDelete - * methods in your stub classes -- you may need to explicitly remove objects - * from the cache in order to prevent returning objects that no longer exist. - * - * @param mixed \$value A ".$this->getObjectClassname()." object or a primary key value. - */ - public static function removeInstanceFromPool(\$value) - {"; - $script .= " - if (Propel::isInstancePoolingEnabled() && \$value !== null) {"; - $pks = $table->getPrimaryKey(); - - $script .= " - if (is_object(\$value) && \$value instanceof ".$this->getObjectClassname().") {"; - - $php = array(); - foreach ($pks as $pk) { - $php[] = '$value->get' . $pk->getPhpName() . '()'; - } - $script .= " - \$key = ".$this->getInstancePoolKeySnippet($php).";"; - - $script .= " - } elseif (".(count($pks) > 1 ? "is_array(\$value) && count(\$value) === " . count($pks) : "is_scalar(\$value)").") { - // assume we've been passed a primary key"; - - if (count($pks) > 1) { - $php = array(); - for ($i=0; $i < count($pks); $i++) { - $php[] = "\$value[$i]"; - } - } else { - $php = '$value'; - } - $script .= " - \$key = ".$this->getInstancePoolKeySnippet($php).";"; - $script .= " - } else { - \$e = new PropelException(\"Invalid value passed to removeInstanceFromPool(). Expected primary key or ".$this->getObjectClassname()." object; got \" . (is_object(\$value) ? get_class(\$value) . ' object.' : var_export(\$value,true))); - throw \$e; - } - - unset(self::\$instances[\$key]); - } - } // removeInstanceFromPool() -"; - } // addRemoveFromInstancePool() - - /** - * Adds method to clear the instance pool. - * @param string &$script The script will be modified in this method. - */ - protected function addClearInstancePool(&$script) - { - $script .= " - /** - * Clear the instance pool. - * - * @return void - */ - public static function clearInstancePool() - { - self::\$instances = array(); - } - "; - } - - /** - * Adds method to clear the instance pool of related tables. - * @param string &$script The script will be modified in this method. - */ - protected function addClearRelatedInstancePool(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Method to invalidate the instance pool of all tables related to " . $table->getName() . " - * by a foreign key with ON DELETE CASCADE - */ - public static function clearRelatedInstancePool() - {"; - // Handle ON DELETE CASCADE for updating instance pool - - foreach ($table->getReferrers() as $fk) { - - // $fk is the foreign key in the other table, so localTableName will - // actually be the table name of other table - $tblFK = $fk->getTable(); - - $joinedTablePeerBuilder = $this->getNewStubPeerBuilder($tblFK); - $this->declareClassFromBuilder($joinedTablePeerBuilder); - $tblFKPackage = $joinedTablePeerBuilder->getStubPeerBuilder()->getPackage(); - - if (!$tblFK->isForReferenceOnly()) { - // we can't perform operations on tables that are - // not within the schema (i.e. that we have no map for, etc.) - - if ($fk->getOnDelete() == ForeignKey::CASCADE || $fk->getOnDelete() == ForeignKey::SETNULL) { - $script .= " - // Invalidate objects in ".$joinedTablePeerBuilder->getClassname()." instance pool, - // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - ".$joinedTablePeerBuilder->getClassname()."::clearInstancePool();"; - } // if fk is on delete cascade - } // if (! for ref only) - } // foreach - $script .= " - } -"; - } - - /** - * Adds method to get an the instance from the pool, given a key. - * @param string &$script The script will be modified in this method. - */ - protected function addGetInstanceFromPool(&$script) - { - $script .= " - /** - * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. - * - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, a serialize()d version of the primary key will be returned. - * - * @param string \$key The key (@see getPrimaryKeyHash()) for this instance. - * @return ".$this->getObjectClassname()." Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. - * @see getPrimaryKeyHash() - */ - public static function getInstanceFromPool(\$key) - { - if (Propel::isInstancePoolingEnabled()) { - if (isset(self::\$instances[\$key])) { - return self::\$instances[\$key]; - } - } - return null; // just to be explicit - } - "; - } - - /** - * Adds method to get a version of the primary key that can be used as a unique key for identifier map. - * @param string &$script The script will be modified in this method. - */ - protected function addGetPrimaryKeyHash(&$script) - { - $script .= " - /** - * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. - * - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, a serialize()d version of the primary key will be returned. - * - * @param array \$row PropelPDO resultset row. - * @param int \$startcol The 0-based offset for reading from the resultset row. - * @return string A string version of PK or NULL if the components of primary key in result array are all null. - */ - public static function getPrimaryKeyHashFromRow(\$row, \$startcol = 0) - {"; - - // We have to iterate through all the columns so that we know the offset of the primary - // key columns. - $n = 0; - $pk = array(); - $cond = array(); - foreach ($this->getTable()->getColumns() as $col) { - if (!$col->isLazyLoad()) { - if ($col->isPrimaryKey()) { - $part = $n ? "\$row[\$startcol + $n]" : "\$row[\$startcol]"; - $cond[] = $part . " === null"; - $pk[] = $part; - } - $n++; - } - } - - $script .= " - // If the PK cannot be derived from the row, return NULL. - if (".implode(' && ', $cond).") { - return null; - } - return ".$this->getInstancePoolKeySnippet($pk)."; - } -"; - } // addGetPrimaryKeyHash - - /** - * Adds method to get the primary key from a row - * @param string &$script The script will be modified in this method. - */ - protected function addGetPrimaryKeyFromRow(&$script) - { - $script .= " - /** - * Retrieves the primary key from the DB resultset row - * For tables with a single-column primary key, that simple pkey value will be returned. For tables with - * a multi-column primary key, an array of the primary key columns will be returned. - * - * @param array \$row PropelPDO resultset row. - * @param int \$startcol The 0-based offset for reading from the resultset row. - * @return mixed The primary key of the row - */ - public static function getPrimaryKeyFromRow(\$row, \$startcol = 0) - {"; - - // We have to iterate through all the columns so that we know the offset of the primary - // key columns. - $table = $this->getTable(); - $n = 0; - $pks = array(); - foreach ($table->getColumns() as $col) { - if (!$col->isLazyLoad()) { - if ($col->isPrimaryKey()) { - $pk = '(' . $col->getPhpType() . ') ' . ($n ? "\$row[\$startcol + $n]" : "\$row[\$startcol]"); - if ($table->hasCompositePrimaryKey()) { - $pks[] = $pk; - } - } - $n++; - } - } - if ($table->hasCompositePrimaryKey()) { - $script .= " - return array(" . implode($pks, ', '). ");"; - } else { - $script .= " - return " . $pk . ";"; - } - $script .= " - } - "; - } // addGetPrimaryKeyFromRow - - /** - * Adds the populateObjects() method. - * @param string &$script The script will be modified in this method. - */ - protected function addPopulateObjects(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * The returned array will contain objects of the default type or - * objects that inherit from the default. - * - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function populateObjects(PDOStatement \$stmt) - { - \$results = array(); - "; - if (!$table->getChildrenColumn()) { - $script .= " - // set the class once to avoid overhead in the loop - \$cls = ".$this->getPeerClassname()."::getOMClass(false);"; - } - - $script .= " - // populate the object(s) - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(\$key))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // \$obj->hydrate(\$row, 0, true); // rehydrate - \$results[] = \$obj; - } else {"; - if ($table->getChildrenColumn()) { - $script .= " - // class must be set each time from the record row - \$cls = ".$this->getPeerClassname()."::getOMClass(\$row, 0); - \$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1); - " . $this->buildObjectInstanceCreationCode('$obj', '$cls') . " - \$obj->hydrate(\$row); - \$results[] = \$obj; - ".$this->getPeerClassname()."::addInstanceToPool(\$obj, \$key);"; - } else { - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj', '$cls') . " - \$obj->hydrate(\$row); - \$results[] = \$obj; - ".$this->getPeerClassname()."::addInstanceToPool(\$obj, \$key);"; - } - $script .= " - } // if key exists - } - \$stmt->closeCursor(); - return \$results; - }"; - } - - /** - * Adds the populateObject() method. - * @param string &$script The script will be modified in this method. - */ - protected function addPopulateObject(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Populates an object of the default type or an object that inherit from the default. - * - * @param array \$row PropelPDO resultset row. - * @param int \$startcol The 0-based offset for reading from the resultset row. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - * @return array (" . $this->getStubObjectBuilder()->getClassName(). " object, last column rank) - */ - public static function populateObject(\$row, \$startcol = 0) - { - \$key = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, \$startcol); - if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(\$key))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // \$obj->hydrate(\$row, \$startcol, true); // rehydrate - \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_COLUMNS;"; - if ($table->isAbstract()) { - $script .= " - } elseif (null == \$key) { - // empty resultset, probably from a left join - // since this table is abstract, we can't hydrate an empty object - \$obj = null; - \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_COLUMNS;"; - } - $script .= " - } else {"; - if (!$table->getChildrenColumn()) { - $script .= " - \$cls = ".$this->getPeerClassname()."::OM_CLASS;"; - } else { - $script .= " - \$cls = ".$this->getPeerClassname()."::getOMClass(\$row, \$startcol, false);"; - } - $script .= " - \$obj = new \$cls(); - \$col = \$obj->hydrate(\$row, \$startcol); - " . $this->getPeerClassname() . "::addInstanceToPool(\$obj, \$key); - } - return array(\$obj, \$col); - }"; - } - - /** - * Adds a getOMClass() for non-abstract tables that have inheritance. - * @param string &$script The script will be modified in this method. - */ - protected function addGetOMClass_Inheritance(&$script) - { - $col = $this->getTable()->getChildrenColumn(); - $script .= " - /** - * The returned Class will contain objects of the default type or - * objects that inherit from the default. - * - * @param array \$row PropelPDO result row. - * @param int \$colnum Column to examine for OM class information (first is 0). - * @param boolean \$withPrefix Whether or not to return the path with the class name - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function getOMClass(\$row, \$colnum, \$withPrefix = true) - { - try { -"; - if ($col->isEnumeratedClasses()) { - $script .= " - \$omClass = null; - \$classKey = \$row[\$colnum + " . ($col->getPosition() - 1) . "]; - - switch(\$classKey) { -"; - foreach ($col->getChildren() as $child) { - $script .= " - case self::CLASSKEY_".strtoupper($child->getKey()).": - \$omClass = self::CLASSNAME_".strtoupper($child->getKey())."; - break; -"; - } /* foreach */ - $script .= " - default: - \$omClass = self::CLASS_DEFAULT; -"; - $script .= " - } // switch - if (!\$withPrefix) { - \$omClass = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); - } -"; - } else { /* if not enumerated */ - $script .= " - \$omClass = \$row[\$colnum + ".($col->getPosition()-1)."]; - \$omClass = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } - $script .= " - } catch (Exception \$e) { - throw new PropelException('Unable to get OM class.', \$e); - } - return \$omClass; - } -"; - } - - /** - * Adds a getOMClass() for non-abstract tables that do note use inheritance. - * @param string &$script The script will be modified in this method. - */ - protected function addGetOMClass_NoInheritance(&$script) - { - $script .= " - /** - * The class that the Peer will make instances of. - * - * If \$withPrefix is true, the returned path - * uses a dot-path notation which is tranalted into a path - * relative to a location on the PHP include_path. - * (e.g. path.to.MyClass -> 'path/to/MyClass.php') - * - * @param boolean \$withPrefix Whether or not to return the path with the class name - * @return string path.to.ClassName - */ - public static function getOMClass(\$withPrefix = true) - { - return \$withPrefix ? ".$this->getPeerClassname()."::CLASS_DEFAULT : ".$this->getPeerClassname()."::OM_CLASS; - } -"; - } - - /** - * Adds a getOMClass() signature for abstract tables that do not have inheritance. - * @param string &$script The script will be modified in this method. - */ - protected function addGetOMClass_NoInheritance_Abstract(&$script) - { - $script .= " - /** - * The class that the Peer will make instances of. - * - * This method must be overridden by the stub subclass, because - * ".$this->getObjectClassname()." is declared abstract in the schema. - */ - abstract public static function getOMClass(\$withPrefix = true); -"; - } - - /** - * Adds the doInsert() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoInsert(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Method perform an INSERT on the database, given a ".$this->getObjectClassname()." or Criteria object. - * - * @param mixed \$values Criteria or ".$this->getObjectClassname()." object containing data that is used to create the INSERT statement. - * @param PropelPDO \$con the PropelPDO connection to use - * @return mixed The new primary key. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doInsert(\$values, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - if (\$values instanceof Criteria) { - \$criteria = clone \$values; // rename for clarity - } else { - \$criteria = \$values->buildCriteria(); // build Criteria from ".$this->getObjectClassname()." object - } -"; - - foreach ($table->getColumns() as $col) { - $cfc = $col->getPhpName(); - if ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && !$table->isAllowPkInsert()) { - $script .= " - if (\$criteria->containsKey(".$this->getColumnConstant($col).") && \$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.".$this->getColumnConstant($col).".')'); - } -"; - if (!$this->getPlatform()->supportsInsertNullPk()) - { - $script .= " - // remove pkey col since this table uses auto-increment and passing a null value for it is not valid - \$criteria->remove(".$this->getColumnConstant($col)."); -"; - } - } elseif ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && $table->isAllowPkInsert() && !$this->getPlatform()->supportsInsertNullPk()) { - $script .= " - // remove pkey col if it is null since this table does not accept that - if (\$criteria->containsKey(".$this->getColumnConstant($col).") && !\$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) { - \$criteria->remove(".$this->getColumnConstant($col)."); - } -"; - } - } - $script .= " - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - try { - // use transaction because \$criteria could contain info - // for more than one table (I guess, conceivably) - \$con->beginTransaction(); - \$pk = ".$this->basePeerClassname."::doInsert(\$criteria, \$con); - \$con->commit(); - } catch(PropelException \$e) { - \$con->rollBack(); - throw \$e; - } - - return \$pk; - } -"; - } - - /** - * Adds the doUpdate() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoUpdate(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Method perform an UPDATE on the database, given a ".$this->getObjectClassname()." or Criteria object. - * - * @param mixed \$values Criteria or ".$this->getObjectClassname()." object containing data that is used to create the UPDATE statement. - * @param PropelPDO \$con The connection to use (specify PropelPDO connection object to exert more control over transactions). - * @return int The number of affected rows (if supported by underlying database driver). - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doUpdate(\$values, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - \$selectCriteria = new Criteria(self::DATABASE_NAME); - - if (\$values instanceof Criteria) { - \$criteria = clone \$values; // rename for clarity -"; - foreach ($table->getColumns() as $col) { - if ($col->isPrimaryKey()) { - $script .= " - \$comparison = \$criteria->getComparison(".$this->getColumnConstant($col)."); - \$value = \$criteria->remove(".$this->getColumnConstant($col)."); - if (\$value) { - \$selectCriteria->add(".$this->getColumnConstant($col).", \$value, \$comparison); - } else { - \$selectCriteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME); - } -"; - } /* if col is prim key */ - } /* foreach */ - - $script .= " - } else { // \$values is ".$this->getObjectClassname()." object - \$criteria = \$values->buildCriteria(); // gets full criteria - \$selectCriteria = \$values->buildPkeyCriteria(); // gets criteria w/ primary key(s) - } - - // set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - return {$this->basePeerClassname}::doUpdate(\$selectCriteria, \$criteria, \$con); - } -"; - } - - /** - * Adds the doDeleteAll() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoDeleteAll(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Method to DELETE all rows from the ".$table->getName()." table. - * - * @return int The number of affected rows (if supported by underlying database driver). - */ - public static function doDeleteAll(\$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - \$affectedRows = 0; // initialize var to track total num of affected rows - try { - // use transaction because \$criteria could contain info - // for more than one table or we could emulating ON DELETE CASCADE, etc. - \$con->beginTransaction(); - "; - if ($this->isDeleteCascadeEmulationNeeded()) { - $script .="\$affectedRows += ".$this->getPeerClassname()."::doOnDeleteCascade(new Criteria(".$this->getPeerClassname()."::DATABASE_NAME), \$con); - "; - } - if ($this->isDeleteSetNullEmulationNeeded()) { - $script .= $this->getPeerClassname() . "::doOnDeleteSetNull(new Criteria(".$this->getPeerClassname() . "::DATABASE_NAME), \$con); - "; - } - $script .= "\$affectedRows += {$this->basePeerClassname}::doDeleteAll(".$this->getPeerClassname()."::TABLE_NAME, \$con, ".$this->getPeerClassname()."::DATABASE_NAME); - // Because this db requires some delete cascade/set null emulation, we have to - // clear the cached instance *after* the emulation has happened (since - // instances get re-added by the select statement contained therein). - ".$this->getPeerClassname()."::clearInstancePool(); - ".$this->getPeerClassname()."::clearRelatedInstancePool(); - \$con->commit(); - return \$affectedRows; - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - } - } -"; - } - - /** - * Adds the doDelete() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoDelete(&$script) - { - $table = $this->getTable(); - $emulateCascade = $this->isDeleteCascadeEmulationNeeded() || $this->isDeleteSetNullEmulationNeeded(); - $script .= " - /** - * Method perform a DELETE on the database, given a ".$this->getObjectClassname()." or Criteria object OR a primary key value. - * - * @param mixed \$values Criteria or ".$this->getObjectClassname()." object or primary key or array of primary keys - * which is used to create the DELETE statement - * @param PropelPDO \$con the connection to use - * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows - * if supported by native driver or if emulated using Propel. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doDelete(\$values, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_WRITE); - } - - if (\$values instanceof Criteria) {"; - if (!$emulateCascade) { - $script .= " - // invalidate the cache for all objects of this type, since we have no - // way of knowing (without running a query) what objects should be invalidated - // from the cache based on this Criteria. - ".$this->getPeerClassname()."::clearInstancePool();"; - } - $script .= " - // rename for clarity - \$criteria = clone \$values; - } elseif (\$values instanceof ".$this->getObjectClassname().") { // it's a model object"; - if (!$emulateCascade) { - $script .= " - // invalidate the cache for this single object - ".$this->getPeerClassname()."::removeInstanceFromPool(\$values);"; - } - if (count($table->getPrimaryKey()) > 0) { - $script .= " - // create criteria based on pk values - \$criteria = \$values->buildPkeyCriteria();"; - } else { - $script .= " - // create criteria based on pk value - \$criteria = \$values->buildCriteria();"; - } - - $script .= " - } else { // it's a primary key, or an array of pks"; - $script .= " - \$criteria = new Criteria(self::DATABASE_NAME);"; - - if (count($table->getPrimaryKey()) === 1) { - $pkey = $table->getPrimaryKey(); - $col = array_shift($pkey); - $script .= " - \$criteria->add(".$this->getColumnConstant($col).", (array) \$values, Criteria::IN);"; - if (!$emulateCascade) { - $script .= " - // invalidate the cache for this object(s) - foreach ((array) \$values as \$singleval) { - ".$this->getPeerClassname()."::removeInstanceFromPool(\$singleval); - }"; - } - } else { - $script .= " - // primary key is composite; we therefore, expect - // the primary key passed to be an array of pkey values - if (count(\$values) == count(\$values, COUNT_RECURSIVE)) { - // array is not multi-dimensional - \$values = array(\$values); - } - foreach (\$values as \$value) {"; - $i=0; - foreach ($table->getPrimaryKey() as $col) { - if ($i == 0) { - $script .= " - \$criterion = \$criteria->getNewCriterion(".$this->getColumnConstant($col).", \$value[$i]);"; - } else { - $script .= " - \$criterion->addAnd(\$criteria->getNewCriterion(".$this->getColumnConstant($col).", \$value[$i]));"; - } - $i++; - } - $script .= " - \$criteria->addOr(\$criterion);"; - if (!$emulateCascade) { - $script .= " - // we can invalidate the cache for this single PK - ".$this->getPeerClassname()."::removeInstanceFromPool(\$value);"; - } - $script .= " - }"; - } /* if count(table->getPrimaryKeys()) */ - - $script .= " - } - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - \$affectedRows = 0; // initialize var to track total num of affected rows - - try { - // use transaction because \$criteria could contain info - // for more than one table or we could emulating ON DELETE CASCADE, etc. - \$con->beginTransaction(); - "; - - if ($this->isDeleteCascadeEmulationNeeded()) { - $script .= " - // cloning the Criteria in case it's modified by doSelect() or doSelectStmt() - \$c = clone \$criteria; - \$affectedRows += ".$this->getPeerClassname()."::doOnDeleteCascade(\$c, \$con); - "; - } - if ($this->isDeleteSetNullEmulationNeeded()) { - $script .= " - // cloning the Criteria in case it's modified by doSelect() or doSelectStmt() - \$c = clone \$criteria; - " . $this->getPeerClassname() . "::doOnDeleteSetNull(\$c, \$con); - "; - } - - if ($emulateCascade) { - $script .= " - // Because this db requires some delete cascade/set null emulation, we have to - // clear the cached instance *after* the emulation has happened (since - // instances get re-added by the select statement contained therein). - if (\$values instanceof Criteria) { - ".$this->getPeerClassname()."::clearInstancePool(); - } elseif (\$values instanceof ".$this->getObjectClassname().") { // it's a model object - ".$this->getPeerClassname()."::removeInstanceFromPool(\$values); - } else { // it's a primary key, or an array of pks - foreach ((array) \$values as \$singleval) { - ".$this->getPeerClassname()."::removeInstanceFromPool(\$singleval); - } - } - "; - } - - $script .= " - \$affectedRows += {$this->basePeerClassname}::doDelete(\$criteria, \$con); - ".$this->getPeerClassname()."::clearRelatedInstancePool(); - \$con->commit(); - return \$affectedRows; - } catch (PropelException \$e) { - \$con->rollBack(); - throw \$e; - } - } -"; - } - - /** - * Adds the doOnDeleteCascade() method, which provides ON DELETE CASCADE emulation. - * @param string &$script The script will be modified in this method. - */ - protected function addDoOnDeleteCascade(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * This is a method for emulating ON DELETE CASCADE for DBs that don't support this - * feature (like MySQL or SQLite). - * - * This method is not very speedy because it must perform a query first to get - * the implicated records and then perform the deletes by calling those Peer classes. - * - * This method should be used within a transaction if possible. - * - * @param Criteria \$criteria - * @param PropelPDO \$con - * @return int The number of affected rows (if supported by underlying database driver). - */ - protected static function doOnDeleteCascade(Criteria \$criteria, PropelPDO \$con) - { - // initialize var to track total num of affected rows - \$affectedRows = 0; - - // first find the objects that are implicated by the \$criteria - \$objects = ".$this->getPeerClassname()."::doSelect(\$criteria, \$con); - foreach (\$objects as \$obj) { -"; - - foreach ($table->getReferrers() as $fk) { - - // $fk is the foreign key in the other table, so localTableName will - // actually be the table name of other table - $tblFK = $fk->getTable(); - - $joinedTablePeerBuilder = $this->getNewPeerBuilder($tblFK); - $tblFKPackage = $joinedTablePeerBuilder->getStubPeerBuilder()->getPackage(); - - if (!$tblFK->isForReferenceOnly()) { - // we can't perform operations on tables that are - // not within the schema (i.e. that we have no map for, etc.) - - $fkClassName = $joinedTablePeerBuilder->getObjectClassname(); - - if ($fk->getOnDelete() == ForeignKey::CASCADE) { - - // backwards on purpose - $columnNamesF = $fk->getLocalColumns(); - $columnNamesL = $fk->getForeignColumns(); - - $script .= " - - // delete related $fkClassName objects - \$criteria = new Criteria(".$joinedTablePeerBuilder->getPeerClassname()."::DATABASE_NAME); - "; - for ($x=0,$xlen=count($columnNamesF); $x < $xlen; $x++) { - $columnFK = $tblFK->getColumn($columnNamesF[$x]); - $columnL = $table->getColumn($columnNamesL[$x]); - - $script .= " - \$criteria->add(".$joinedTablePeerBuilder->getColumnConstant($columnFK) .", \$obj->get".$columnL->getPhpName()."());"; - } - - $script .= " - \$affectedRows += ".$joinedTablePeerBuilder->getPeerClassname()."::doDelete(\$criteria, \$con);"; - - } // if cascade && fkey table name != curr table name - - } // if not for ref only - } // foreach foreign keys - $script .= " - } - return \$affectedRows; - } -"; - } // end addDoOnDeleteCascade - - /** - * Adds the doOnDeleteSetNull() method, which provides ON DELETE SET NULL emulation. - * @param string &$script The script will be modified in this method. - */ - protected function addDoOnDeleteSetNull(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * This is a method for emulating ON DELETE SET NULL DBs that don't support this - * feature (like MySQL or SQLite). - * - * This method is not very speedy because it must perform a query first to get - * the implicated records and then perform the deletes by calling those Peer classes. - * - * This method should be used within a transaction if possible. - * - * @param Criteria \$criteria - * @param PropelPDO \$con - * @return void - */ - protected static function doOnDeleteSetNull(Criteria \$criteria, PropelPDO \$con) - { - - // first find the objects that are implicated by the \$criteria - \$objects = ".$this->getPeerClassname()."::doSelect(\$criteria, \$con); - foreach (\$objects as \$obj) { -"; - - // This logic is almost exactly the same as that in doOnDeleteCascade() - // it may make sense to refactor this, provided that thigns don't - // get too complicated. - - foreach ($table->getReferrers() as $fk) { - - // $fk is the foreign key in the other table, so localTableName will - // actually be the table name of other table - $tblFK = $fk->getTable(); - $refTablePeerBuilder = $this->getNewPeerBuilder($tblFK); - - if (!$tblFK->isForReferenceOnly()) { - // we can't perform operations on tables that are - // not within the schema (i.e. that we have no map for, etc.) - - $fkClassName = $refTablePeerBuilder->getObjectClassname(); - - if ($fk->getOnDelete() == ForeignKey::SETNULL) { - - // backwards on purpose - $columnNamesF = $fk->getLocalColumns(); - $columnNamesL = $fk->getForeignColumns(); // should be same num as foreign - $script .= " - // set fkey col in related $fkClassName rows to NULL - \$selectCriteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME); - \$updateValues = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME);"; - - for ($x=0,$xlen=count($columnNamesF); $x < $xlen; $x++) { - $columnFK = $tblFK->getColumn($columnNamesF[$x]); - $columnL = $table->getColumn($columnNamesL[$x]); - $script .= " - \$selectCriteria->add(".$refTablePeerBuilder->getColumnConstant($columnFK).", \$obj->get".$columnL->getPhpName()."()); - \$updateValues->add(".$refTablePeerBuilder->getColumnConstant($columnFK).", null); -"; - } - - $script .= " - {$this->basePeerClassname}::doUpdate(\$selectCriteria, \$updateValues, \$con); // use BasePeer because generated Peer doUpdate() methods only update using pkey -"; - } // if setnull && fkey table name != curr table name - } // if not for ref only - } // foreach foreign keys - - $script .= " - } - } -"; - } - - /** - * Adds the doValidate() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoValidate(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Validates all modified columns of given ".$this->getObjectClassname()." object. - * If parameter \$columns is either a single column name or an array of column names - * than only those columns are validated. - * - * NOTICE: This does not apply to primary or foreign keys for now. - * - * @param ".$this->getObjectClassname()." \$obj The object to validate. - * @param mixed \$cols Column name or array of column names. - * - * @return mixed TRUE if all columns are valid or the error message of the first invalid column. - */ - public static function doValidate(".$this->getObjectClassname()." \$obj, \$cols = null) - { - \$columns = array(); - - if (\$cols) { - \$dbMap = Propel::getDatabaseMap(".$this->getPeerClassname()."::DATABASE_NAME); - \$tableMap = \$dbMap->getTable(".$this->getPeerClassname()."::TABLE_NAME); - - if (! is_array(\$cols)) { - \$cols = array(\$cols); - } - - foreach (\$cols as \$colName) { - if (\$tableMap->containsColumn(\$colName)) { - \$get = 'get' . \$tableMap->getColumn(\$colName)->getPhpName(); - \$columns[\$colName] = \$obj->\$get(); - } - } - } else { -"; - foreach ($table->getValidators() as $val) { - $col = $val->getColumn(); - if (!$col->isAutoIncrement()) { - $script .= " - if (\$obj->isNew() || \$obj->isColumnModified(".$this->getColumnConstant($col).")) - \$columns[".$this->getColumnConstant($col)."] = \$obj->get".$col->getPhpName()."(); -"; - } // if - } // foreach - - $script .= " - } - - return {$this->basePeerClassname}::doValidate(".$this->getPeerClassname()."::DATABASE_NAME, ".$this->getPeerClassname()."::TABLE_NAME, \$columns); - } -"; - } // end addDoValidate() - - /** - * Adds the retrieveByPK method for tables with single-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addRetrieveByPK_SinglePK(&$script) - { - $table = $this->getTable(); - $pks = $table->getPrimaryKey(); - $col = $pks[0]; - - $script .= " - /** - * Retrieve a single object by pkey. - * - * @param ".$col->getPhpType()." \$pk the primary key. - * @param PropelPDO \$con the connection to use - * @return " .$this->getObjectClassname(). " - */ - public static function ".$this->getRetrieveMethodName()."(\$pk, PropelPDO \$con = null) - { - - if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(".$this->getInstancePoolKeySnippet('$pk')."))) { - return \$obj; - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME); - \$criteria->add(".$this->getColumnConstant($col).", \$pk); - - \$v = ".$this->getPeerClassname()."::doSelect(\$criteria, \$con); - - return !empty(\$v) > 0 ? \$v[0] : null; - } -"; - } - - /** - * Adds the retrieveByPKs method for tables with single-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addRetrieveByPKs_SinglePK(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Retrieve multiple objects by pkey. - * - * @param array \$pks List of primary keys - * @param PropelPDO \$con the connection to use - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function ".$this->getRetrieveMethodName()."s(\$pks, PropelPDO \$con = null) - { - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - - \$objs = null; - if (empty(\$pks)) { - \$objs = array(); - } else { - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME);"; - $k1 = $table->getPrimaryKey(); - $script .= " - \$criteria->add(".$this->getColumnConstant($k1[0]).", \$pks, Criteria::IN);"; - $script .= " - \$objs = ".$this->getPeerClassname()."::doSelect(\$criteria, \$con); - } - return \$objs; - } -"; - } - - /** - * Adds the retrieveByPK method for tables with multi-column primary key. - * @param string &$script The script will be modified in this method. - */ - protected function addRetrieveByPK_MultiPK(&$script) - { - $table = $this->getTable(); - $script .= " - /** - * Retrieve object using using composite pkey values."; - foreach ($table->getPrimaryKey() as $col) { - $clo = strtolower($col->getName()); - $cptype = $col->getPhpType(); - $script .= " - * @param $cptype $".$clo; - } - $script .= " - * @param PropelPDO \$con - * @return ".$this->getObjectClassname()." - */ - public static function ".$this->getRetrieveMethodName()."("; - - $php = array(); - foreach ($table->getPrimaryKey() as $col) { - $clo = strtolower($col->getName()); - $php[] = '$' . $clo; - } /* foreach */ - - $script .= implode(', ', $php); - - $script .= ", PropelPDO \$con = null) { - \$_instancePoolKey = ".$this->getInstancePoolKeySnippet($php).";"; - $script .= " - if (null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(\$_instancePoolKey))) { - return \$obj; - } - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - \$criteria = new Criteria(".$this->getPeerClassname()."::DATABASE_NAME);"; - foreach ($table->getPrimaryKey() as $col) { - $clo = strtolower($col->getName()); - $script .= " - \$criteria->add(".$this->getColumnConstant($col).", $".$clo.");"; - } - $script .= " - \$v = ".$this->getPeerClassname()."::doSelect(\$criteria, \$con); - - return !empty(\$v) ? \$v[0] : null; - }"; - } - - /** - * Adds the getTableMap() method which is a convenience method for apps to get DB metadata. - * @param string &$script The script will be modified in this method. - */ - protected function addGetTableMap(&$script) - { - $script .= " - /** - * Returns the TableMap related to this peer. - * This method is not needed for general use but a specific application could have a need. - * @return TableMap - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function getTableMap() - { - return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); - } -"; - } - - /** - * Adds the complex OM methods to the base addSelectMethods() function. - * @param string &$script The script will be modified in this method. - * @see PeerBuilder::addSelectMethods() - */ - protected function addSelectMethods(&$script) - { - $table = $this->getTable(); - - parent::addSelectMethods($script); - - $this->addDoCountJoin($script); - $this->addDoSelectJoin($script); - - $countFK = count($table->getForeignKeys()); - - $includeJoinAll = true; - - foreach ($this->getTable()->getForeignKeys() as $fk) { - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - $this->declareClassFromBuilder($this->getNewStubPeerBuilder($tblFK)); - if ($tblFK->isForReferenceOnly()) { - $includeJoinAll = false; - } - } - - if ($includeJoinAll) { - if ($countFK > 0) { - $this->addDoCountJoinAll($script); - $this->addDoSelectJoinAll($script); - } - if ($countFK > 1) { - $this->addDoCountJoinAllExcept($script); - $this->addDoSelectJoinAllExcept($script); - } - } - - } - - /** - * Get the column offsets of the primary key(s) for specified table. - * - * @param Table $tbl - * @return array int[] The column offsets of the primary key(s). - */ - protected function getPrimaryKeyColOffsets(Table $tbl) - { - $offsets = array(); - $idx = 0; - foreach ($tbl->getColumns() as $col) { - if ($col->isPrimaryKey()) { - $offsets[] = $idx; - } - $idx++; - } - return $offsets; - } - - public function addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder) - { - $script = ''; - $lfMap = $fk->getLocalForeignMapping(); - $lftCols = $fk->getLocalColumns(); - if (count($lftCols) == 1) - { - // simple foreign key - $lftCol = $lftCols[0]; - $script .= sprintf(" - \$criteria->addJoin(%s, %s, \$join_behavior);\n", - $this->getColumnConstant($table->getColumn($lftCol) ), - $joinedTablePeerBuilder->getColumnConstant($joinTable->getColumn( $lfMap[$lftCol] ) )); - } - else - { - // composite foreign key - $script .= " - \$criteria->addMultipleJoin(array(\n"; - foreach ($lftCols as $columnName ) { - $script .= sprintf(" array(%s, %s),\n", - $this->getColumnConstant($table->getColumn($columnName) ), - $joinedTablePeerBuilder->getColumnConstant($joinTable->getColumn( $lfMap[$columnName] ) ) - ); - } - $script .= " ), \$join_behavior);\n"; - } - return $script; - } - - /** - * Adds the doSelectJoin*() methods. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelectJoin(&$script) - { - $table = $this->getTable(); - $className = $this->getObjectClassname(); - $countFK = count($table->getForeignKeys()); - $join_behavior = $this->getJoinBehavior(); - - if ($countFK >= 1) { - - foreach ($table->getForeignKeys() as $fk) { - - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - - if (!$joinTable->isForReferenceOnly()) { - - // This condition is necessary because Propel lacks a system for - // aliasing the table if it is the same table. - if ( $fk->getForeignTableName() != $table->getName() ) { - - $thisTableObjectBuilder = $this->getNewObjectBuilder($table); - $joinedTableObjectBuilder = $this->getNewObjectBuilder($joinTable); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - - $joinClassName = $joinedTableObjectBuilder->getObjectClassname(); - - $script .= " - - /** - * Selects a collection of $className objects pre-filled with their $joinClassName objects. - * @param Criteria \$criteria - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return array Array of $className objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoin".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)."(Criteria \$criteria, \$con = null, \$join_behavior = $join_behavior) - { - \$criteria = clone \$criteria; - - // Set the correct dbName if it has not been overridden - if (\$criteria->getDbName() == Propel::getDefaultDB()) { - \$criteria->setDbName(self::DATABASE_NAME); - } - - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - \$startcol = (".$this->getPeerClassname()."::NUM_COLUMNS - ".$this->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS); - ".$joinedTablePeerBuilder->getPeerClassname()."::addSelectColumns(\$criteria); -"; - - $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder); - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - \$stmt = ".$this->basePeerClassname."::doSelect(\$criteria, \$con); - \$results = array(); - - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key1 = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$obj1 = ".$this->getPeerClassname()."::getInstanceFromPool(\$key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // \$obj1->hydrate(\$row, 0, true); // rehydrate - } else { -"; - if ($table->getChildrenColumn()) { - $script .= " - \$omClass = ".$this->getPeerClassname()."::getOMClass(\$row, 0); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$this->getPeerClassname()."::getOMClass(false); -"; - } - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj1', '$cls') . " - \$obj1->hydrate(\$row); - ".$this->getPeerClassname()."::addInstanceToPool(\$obj1, \$key1); - } // if \$obj1 already loaded - - \$key2 = ".$joinedTablePeerBuilder->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, \$startcol); - if (\$key2 !== null) { - \$obj2 = ".$joinedTablePeerBuilder->getPeerClassname()."::getInstanceFromPool(\$key2); - if (!\$obj2) { -"; - if ($joinTable->getChildrenColumn()) { - $script .= " - \$omClass = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(\$row, \$startcol); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(false); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj2', '$cls') . " - \$obj2->hydrate(\$row, \$startcol); - ".$joinedTablePeerBuilder->getPeerClassname()."::addInstanceToPool(\$obj2, \$key2); - } // if obj2 already loaded - - // Add the \$obj1 (".$this->getObjectClassname().") to \$obj2 (".$joinedTablePeerBuilder->getObjectClassname().")"; - if ($fk->isLocalPrimaryKey()) { - $script .= " - // one to one relationship - \$obj1->set" . $joinedTablePeerBuilder->getObjectClassname() . "(\$obj2);"; - } else { - $script .= " - \$obj2->add" . $joinedTableObjectBuilder->getRefFKPhpNameAffix($fk, $plural = false)."(\$obj1);"; - } - $script .= " - - } // if joined row was not null - - \$results[] = \$obj1; - } - \$stmt->closeCursor(); - return \$results; - } -"; - } // if fk table name != this table name - } // if ! is reference only - } // foreach column - } // if count(fk) > 1 - - } // addDoSelectJoin() - - /** - * Adds the doCountJoin*() methods. - * @param string &$script The script will be modified in this method. - */ - protected function addDoCountJoin(&$script) - { - $table = $this->getTable(); - $className = $this->getObjectClassname(); - $countFK = count($table->getForeignKeys()); - $join_behavior = $this->getJoinBehavior(); - - if ($countFK >= 1) { - - foreach ($table->getForeignKeys() as $fk) { - - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - - if (!$joinTable->isForReferenceOnly()) { - - if ( $fk->getForeignTableName() != $table->getName() ) { - - $thisTableObjectBuilder = $this->getNewObjectBuilder($table); - $joinedTableObjectBuilder = $this->getNewObjectBuilder($joinTable); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - - $joinClassName = $joinedTableObjectBuilder->getObjectClassname(); - - $script .= " - - /** - * Returns the number of rows matching criteria, joining the related ".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)." table - * - * @param Criteria \$criteria - * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return int Number of matching rows. - */ - public static function doCountJoin".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)."(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null, \$join_behavior = $join_behavior) - { - // we're going to modify criteria, so copy it first - \$criteria = clone \$criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - \$criteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME); - - if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) { - \$criteria->setDistinct(); - } - - if (!\$criteria->hasSelectClause()) { - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - } - - \$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } -"; - $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder); - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - \$stmt = ".$this->basePeerClassname."::doCount(\$criteria, \$con); - - if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$count = (int) \$row[0]; - } else { - \$count = 0; // no rows returned; we infer that means 0 matches. - } - \$stmt->closeCursor(); - return \$count; - } -"; - } // if fk table name != this table name - } // if ! is reference only - } // foreach column - } // if count(fk) > 1 - - } // addDoCountJoin() - - /** - * Adds the doSelectJoinAll() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelectJoinAll(&$script) - { - $table = $this->getTable(); - $className = $this->getObjectClassname(); - $join_behavior = $this->getJoinBehavior(); - - $script .= " - - /** - * Selects a collection of $className objects pre-filled with all related objects. - * - * @param Criteria \$criteria - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return array Array of $className objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAll(Criteria \$criteria, \$con = null, \$join_behavior = $join_behavior) - { - \$criteria = clone \$criteria; - - // Set the correct dbName if it has not been overridden - if (\$criteria->getDbName() == Propel::getDefaultDB()) { - \$criteria->setDbName(self::DATABASE_NAME); - } - - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - \$startcol2 = (".$this->getPeerClassname()."::NUM_COLUMNS - ".$this->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS); -"; - $index = 2; - foreach ($table->getForeignKeys() as $fk) { - - // Want to cover this case, but the code is not there yet. - // Propel lacks a system for aliasing tables of the same name. - if ( $fk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - $new_index = $index + 1; - - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $joinClassName = $joinedTablePeerBuilder->getObjectClassname(); - - $script .= " - ".$joinedTablePeerBuilder->getPeerClassname()."::addSelectColumns(\$criteria); - \$startcol$new_index = \$startcol$index + (".$joinedTablePeerBuilder->getPeerClassname()."::NUM_COLUMNS - ".$joinedTablePeerBuilder->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS); -"; - $index = $new_index; - - } // if fk->getForeignTableName != table->getName - } // foreach [sub] foreign keys - - foreach ($table->getForeignKeys() as $fk) { - // want to cover this case, but the code is not there yet. - if ( $fk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder); - } - } - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - \$stmt = ".$this->basePeerClassname."::doSelect(\$criteria, \$con); - \$results = array(); - - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key1 = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$obj1 = ".$this->getPeerClassname()."::getInstanceFromPool(\$key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // \$obj1->hydrate(\$row, 0, true); // rehydrate - } else {"; - - if ($table->getChildrenColumn()) { - $script .= " - \$omClass = ".$this->getPeerClassname()."::getOMClass(\$row, 0); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$this->getPeerClassname()."::getOMClass(false); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj1', '$cls') . " - \$obj1->hydrate(\$row); - ".$this->getPeerClassname()."::addInstanceToPool(\$obj1, \$key1); - } // if obj1 already loaded -"; - - $index = 1; - foreach ($table->getForeignKeys() as $fk ) { - // want to cover this case, but the code is not there yet. - // Why not? -because we'd have to alias the tables in the JOIN - if ( $fk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - - $thisTableObjectBuilder = $this->getNewObjectBuilder($table); - $joinedTableObjectBuilder = $this->getNewObjectBuilder($joinTable); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - - - $joinClassName = $joinedTableObjectBuilder->getObjectClassname(); - $interfaceName = $joinClassName; - - if ($joinTable->getInterface()) { - $interfaceName = $this->prefixClassname($joinTable->getInterface()); - } - - $index++; - - $script .= " - // Add objects for joined $joinClassName rows - - \$key$index = ".$joinedTablePeerBuilder->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, \$startcol$index); - if (\$key$index !== null) { - \$obj$index = ".$joinedTablePeerBuilder->getPeerClassname()."::getInstanceFromPool(\$key$index); - if (!\$obj$index) { -"; - if ($joinTable->getChildrenColumn()) { - $script .= " - \$omClass = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(\$row, \$startcol$index); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(false); -"; - } /* $joinTable->getChildrenColumn() */ - - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj' . $index, '$cls') . " - \$obj".$index."->hydrate(\$row, \$startcol$index); - ".$joinedTablePeerBuilder->getPeerClassname()."::addInstanceToPool(\$obj$index, \$key$index); - } // if obj$index loaded - - // Add the \$obj1 (".$this->getObjectClassname().") to the collection in \$obj".$index." (".$joinedTablePeerBuilder->getObjectClassname().")"; - if ($fk->isLocalPrimaryKey()) { - $script .= " - \$obj1->set".$joinedTablePeerBuilder->getObjectClassname()."(\$obj".$index.");"; - } else { - $script .= " - \$obj".$index."->add".$joinedTableObjectBuilder->getRefFKPhpNameAffix($fk, $plural = false)."(\$obj1);"; - } - $script .= " - } // if joined row not null -"; - - } // $fk->getForeignTableName() != $table->getName() - } //foreach foreign key - - $script .= " - \$results[] = \$obj1; - } - \$stmt->closeCursor(); - return \$results; - } -"; - - } // end addDoSelectJoinAll() - - - /** - * Adds the doCountJoinAll() method. - * @param string &$script The script will be modified in this method. - */ - protected function addDoCountJoinAll(&$script) - { - $table = $this->getTable(); - $className = $this->getObjectClassname(); - $join_behavior = $this->getJoinBehavior(); - - $script .= " - - /** - * Returns the number of rows matching criteria, joining all related tables - * - * @param Criteria \$criteria - * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return int Number of matching rows. - */ - public static function doCountJoinAll(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null, \$join_behavior = $join_behavior) - { - // we're going to modify criteria, so copy it first - \$criteria = clone \$criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - \$criteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME); - - if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) { - \$criteria->setDistinct(); - } - - if (!\$criteria->hasSelectClause()) { - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - } - - \$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } -"; - - foreach ($table->getForeignKeys() as $fk) { - // want to cover this case, but the code is not there yet. - if ( $fk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder); - } // if fk->getForeignTableName != table->getName - } // foreach [sub] foreign keys - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - \$stmt = ".$this->basePeerClassname."::doCount(\$criteria, \$con); - - if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$count = (int) \$row[0]; - } else { - \$count = 0; // no rows returned; we infer that means 0 matches. - } - \$stmt->closeCursor(); - return \$count; - }"; - } // end addDoCountJoinAll() - - /** - * Adds the doSelectJoinAllExcept*() methods. - * @param string &$script The script will be modified in this method. - */ - protected function addDoSelectJoinAllExcept(&$script) - { - $table = $this->getTable(); - $join_behavior = $this->getJoinBehavior(); - - // ------------------------------------------------------------------------ - // doSelectJoinAllExcept*() - // ------------------------------------------------------------------------ - - // 2) create a bunch of doSelectJoinAllExcept*() methods - // -- these were existing in original Torque, so we should keep them for compatibility - - $fkeys = $table->getForeignKeys(); // this sep assignment is necessary otherwise sub-loops over - // getForeignKeys() will cause this to only execute one time. - foreach ($fkeys as $fk ) { - - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - - $excludedTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - - $thisTableObjectBuilder = $this->getNewObjectBuilder($table); - $excludedTableObjectBuilder = $this->getNewObjectBuilder($excludedTable); - $excludedTablePeerBuilder = $this->getNewPeerBuilder($excludedTable); - - $excludedClassName = $excludedTableObjectBuilder->getObjectClassname(); - - - $script .= " - - /** - * Selects a collection of ".$this->getObjectClassname()." objects pre-filled with all related objects except ".$thisTableObjectBuilder->getFKPhpNameAffix($fk).". - * - * @param Criteria \$criteria - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return array Array of ".$this->getObjectClassname()." objects. - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function doSelectJoinAllExcept".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)."(Criteria \$criteria, \$con = null, \$join_behavior = $join_behavior) - { - \$criteria = clone \$criteria; - - // Set the correct dbName if it has not been overridden - // \$criteria->getDbName() will return the same object if not set to another value - // so == check is okay and faster - if (\$criteria->getDbName() == Propel::getDefaultDB()) { - \$criteria->setDbName(self::DATABASE_NAME); - } - - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - \$startcol2 = (".$this->getPeerClassname()."::NUM_COLUMNS - ".$this->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS); -"; - $index = 2; - foreach ($table->getForeignKeys() as $subfk) { - // want to cover this case, but the code is not there yet. - // Why not? - because we would have to alias the tables in the join - if ( !($subfk->getForeignTableName() == $table->getName())) { - $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName()); - $joinTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $joinClassName = $joinTablePeerBuilder->getObjectClassname(); - - if ($joinClassName != $excludedClassName) { - $new_index = $index + 1; - $script .= " - ".$joinTablePeerBuilder->getPeerClassname()."::addSelectColumns(\$criteria); - \$startcol$new_index = \$startcol$index + (".$joinTablePeerBuilder->getPeerClassname()."::NUM_COLUMNS - ".$joinTablePeerBuilder->getPeerClassname()."::NUM_LAZY_LOAD_COLUMNS); -"; - $index = $new_index; - } // if joinClassName not excludeClassName - } // if subfk is not curr table - } // foreach [sub] foreign keys - - foreach ($table->getForeignKeys() as $subfk) { - // want to cover this case, but the code is not there yet. - if ( $subfk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName()); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $joinClassName = $joinedTablePeerBuilder->getObjectClassname(); - - if ($joinClassName != $excludedClassName) - { - $script .= $this->addCriteriaJoin($subfk, $table, $joinTable, $joinedTablePeerBuilder); - } - } - } // foreach fkeys - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - - \$stmt = ".$this->basePeerClassname ."::doSelect(\$criteria, \$con); - \$results = array(); - - while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$key1 = ".$this->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, 0); - if (null !== (\$obj1 = ".$this->getPeerClassname()."::getInstanceFromPool(\$key1))) { - // We no longer rehydrate the object, since this can cause data loss. - // See http://www.propelorm.org/ticket/509 - // \$obj1->hydrate(\$row, 0, true); // rehydrate - } else {"; - if ($table->getChildrenColumn()) { - $script .= " - \$omClass = ".$this->getPeerClassname()."::getOMClass(\$row, 0); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$this->getPeerClassname()."::getOMClass(false); -"; - } - - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj1', '$cls') . " - \$obj1->hydrate(\$row); - ".$this->getPeerClassname()."::addInstanceToPool(\$obj1, \$key1); - } // if obj1 already loaded -"; - - $index = 1; - foreach ($table->getForeignKeys() as $subfk ) { - // want to cover this case, but the code is not there yet. - if ( $subfk->getForeignTableName() != $table->getName() ) { - - $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName()); - - $joinedTableObjectBuilder = $this->getNewObjectBuilder($joinTable); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - - $joinClassName = $joinedTableObjectBuilder->getObjectClassname(); - - $interfaceName = $joinClassName; - if ($joinTable->getInterface()) { - $interfaceName = $this->prefixClassname($joinTable->getInterface()); - } - - if ($joinClassName != $excludedClassName) { - - $index++; - - $script .= " - // Add objects for joined $joinClassName rows - - \$key$index = ".$joinedTablePeerBuilder->getPeerClassname()."::getPrimaryKeyHashFromRow(\$row, \$startcol$index); - if (\$key$index !== null) { - \$obj$index = ".$joinedTablePeerBuilder->getPeerClassname()."::getInstanceFromPool(\$key$index); - if (!\$obj$index) { - "; - - if ($joinTable->getChildrenColumn()) { - $script .= " - \$omClass = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(\$row, \$startcol$index); - \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1); -"; - } else { - $script .= " - \$cls = ".$joinedTablePeerBuilder->getPeerClassname()."::getOMClass(false); -"; - } /* $joinTable->getChildrenColumn() */ - $script .= " - " . $this->buildObjectInstanceCreationCode('$obj' . $index, '$cls') . " - \$obj".$index."->hydrate(\$row, \$startcol$index); - ".$joinedTablePeerBuilder->getPeerClassname()."::addInstanceToPool(\$obj$index, \$key$index); - } // if \$obj$index already loaded - - // Add the \$obj1 (".$this->getObjectClassname().") to the collection in \$obj".$index." (".$joinedTablePeerBuilder->getObjectClassname().")"; - if ($subfk->isLocalPrimaryKey()) { - $script .= " - \$obj1->set".$joinedTablePeerBuilder->getObjectClassname()."(\$obj".$index.");"; - } else { - $script .= " - \$obj".$index."->add".$joinedTableObjectBuilder->getRefFKPhpNameAffix($subfk, $plural = false)."(\$obj1);"; - } - $script .= " - - } // if joined row is not null -"; - } // if ($joinClassName != $excludedClassName) { - } // $subfk->getForeignTableName() != $table->getName() - } // foreach - $script .= " - \$results[] = \$obj1; - } - \$stmt->closeCursor(); - return \$results; - } -"; - } // foreach fk - - } // addDoSelectJoinAllExcept - - /** - * Adds the doCountJoinAllExcept*() methods. - * @param string &$script The script will be modified in this method. - */ - protected function addDoCountJoinAllExcept(&$script) - { - $table = $this->getTable(); - $join_behavior = $this->getJoinBehavior(); - - $fkeys = $table->getForeignKeys(); // this sep assignment is necessary otherwise sub-loops over - // getForeignKeys() will cause this to only execute one time. - foreach ($fkeys as $fk ) { - - $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName()); - - $excludedTable = $table->getDatabase()->getTable($fk->getForeignTableName()); - - $thisTableObjectBuilder = $this->getNewObjectBuilder($table); - $excludedTableObjectBuilder = $this->getNewObjectBuilder($excludedTable); - $excludedTablePeerBuilder = $this->getNewPeerBuilder($excludedTable); - - $excludedClassName = $excludedTableObjectBuilder->getObjectClassname(); - - $script .= " - - /** - * Returns the number of rows matching criteria, joining the related ".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)." table - * - * @param Criteria \$criteria - * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. - * @param PropelPDO \$con - * @param String \$join_behavior the type of joins to use, defaults to $join_behavior - * @return int Number of matching rows. - */ - public static function doCountJoinAllExcept".$thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false)."(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null, \$join_behavior = $join_behavior) - { - // we're going to modify criteria, so copy it first - \$criteria = clone \$criteria; - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - \$criteria->setPrimaryTableName(".$this->getPeerClassname()."::TABLE_NAME); - - if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) { - \$criteria->setDistinct(); - } - - if (!\$criteria->hasSelectClause()) { - ".$this->getPeerClassname()."::addSelectColumns(\$criteria); - } - - \$criteria->clearOrderByColumns(); // ORDER BY should not affect count - - // Set the correct dbName - \$criteria->setDbName(self::DATABASE_NAME); - - if (\$con === null) { - \$con = Propel::getConnection(".$this->getPeerClassname()."::DATABASE_NAME, Propel::CONNECTION_READ); - } - "; - - foreach ($table->getForeignKeys() as $subfk) { - // want to cover this case, but the code is not there yet. - if ( $subfk->getForeignTableName() != $table->getName() ) { - $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName()); - $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable); - $joinClassName = $joinedTablePeerBuilder->getObjectClassname(); - - if ($joinClassName != $excludedClassName) - { - $script .= $this->addCriteriaJoin($subfk, $table, $joinTable, $joinedTablePeerBuilder); - } - } - } // foreach fkeys - - // apply behaviors - $this->applyBehaviorModifier('preSelect', $script); - - $script .= " - \$stmt = ".$this->basePeerClassname."::doCount(\$criteria, \$con); - - if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) { - \$count = (int) \$row[0]; - } else { - \$count = 0; // no rows returned; we infer that means 0 matches. - } - \$stmt->closeCursor(); - return \$count; - } -"; - } // foreach fk - - } // addDoCountJoinAllExcept - - /** - * returns the desired join behavior as set in the build properties - * see trac ticket #588, #491 - * - */ - protected function getJoinBehavior() - { - return $this->getGeneratorConfig()->getBuildProperty('useLeftJoinsInDoJoinMethods') ? 'Criteria::LEFT_JOIN' : 'Criteria::INNER_JOIN'; - } - -} // PHP5PeerBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5TableMapBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PHP5TableMapBuilder.php deleted file mode 100644 index a156b29bf..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PHP5TableMapBuilder.php +++ /dev/null @@ -1,354 +0,0 @@ - - * @package propel.generator.builder.om - */ -class PHP5TableMapBuilder extends OMBuilder -{ - - /** - * Gets the package for the map builder classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . '.map'; - } - - public function getNamespace() - { - if ($namespace = parent::getNamespace()) { - if ($this->getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceMap')) { - return $namespace . '\\' . $omns; - } else { - return $namespace; - } - } - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getTable()->getPhpName() . 'TableMap'; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $script .= " - -/** - * This class defines the structure of the '".$table->getName()."' table. - * - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * - * This map class is used by Propel to do runtime db structure discovery. - * For example, the createSelectSql() method checks the type of a given column used in an - * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive - * (i.e. if it's a text column type). - * - * @package propel.generator.".$this->getPackage()." - */ -class ".$this->getClassname()." extends TableMap { -"; - } - - /** - * Specifies the methods that are added as part of the map builder class. - * This can be overridden by subclasses that wish to add more methods. - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $this->declareClasses('TableMap', 'RelationMap'); - $this->addConstants($script); - $this->addAttributes($script); - $this->addInitialize($script); - $this->addBuildRelations($script); - $this->addGetBehaviors($script); - } - - /** - * Adds any constants needed for this TableMap class. - * @param string &$script The script will be modified in this method. - */ - protected function addConstants(&$script) - { - $script .= " - /** - * The (dot-path) name of this class - */ - const CLASS_NAME = '".$this->getClasspath()."'; -"; - } - - /** - * Adds any attributes needed for this TableMap class. - * @param string &$script The script will be modified in this method. - */ - protected function addAttributes(&$script) - { - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('tableMapFilter', $script, ""); - } - - /** - * Adds the addInitialize() method to the table map class. - * @param string &$script The script will be modified in this method. - */ - protected function addInitialize(&$script) - { - - $table = $this->getTable(); - $platform = $this->getPlatform(); - $ddlBuilder = $this->getDDLBuilder(); - - $script .= " - /** - * Initialize the table attributes, columns and validators - * Relations are not initialized by this method since they are lazy loaded - * - * @return void - * @throws PropelException - */ - public function initialize() - { - // attributes - \$this->setName('".$table->getName()."'); - \$this->setPhpName('".$table->getPhpName()."'); - \$this->setClassname('" . addslashes($this->getStubObjectBuilder()->getFullyQualifiedClassname()) . "'); - \$this->setPackage('" . parent::getPackage() . "');"; - if ($table->getIdMethod() == "native") { - $script .= " - \$this->setUseIdGenerator(true);"; - } else { - $script .= " - \$this->setUseIdGenerator(false);"; - } - - if ($table->getIdMethodParameters()) { - $params = $table->getIdMethodParameters(); - $imp = $params[0]; - $script .= " - \$this->setPrimaryKeyMethodInfo('".$imp->getValue()."');"; - } elseif ($table->getIdMethod() == IDMethod::NATIVE && ($platform->getNativeIdMethod() == Platform::SEQUENCE || $platform->getNativeIdMethod() == Platform::SERIAL)) { - $script .= " - \$this->setPrimaryKeyMethodInfo('".$ddlBuilder->getSequenceName()."');"; - } - - if ($this->getTable()->getChildrenColumn()) { - $script .= " - \$this->setSingleTableInheritance(true);"; - } - - // Add columns to map - $script .= " - // columns"; - foreach ($table->getColumns() as $col) { - $cup=strtoupper($col->getName()); - $cfc=$col->getPhpName(); - if (!$col->getSize()) { - $size = "null"; - } else { - $size = $col->getSize(); - } - $default = $col->getDefaultValueString(); - if ($col->isPrimaryKey()) { - if ($col->isForeignKey()) { - foreach ($col->getForeignKeys() as $fk) { - $script .= " - \$this->addForeignPrimaryKey('$cup', '$cfc', '".$col->getType()."' , '".$fk->getForeignTableName()."', '".strtoupper($fk->getMappedForeignColumn($col->getName()))."', ".($col->isNotNull() ? 'true' : 'false').", ".$size.", $default);"; - } - } else { - $script .= " - \$this->addPrimaryKey('$cup', '$cfc', '".$col->getType()."', ".var_export($col->isNotNull(), true).", ".$size.", $default);"; - } - } else { - if ($col->isForeignKey()) { - foreach ($col->getForeignKeys() as $fk) { - $script .= " - \$this->addForeignKey('$cup', '$cfc', '".$col->getType()."', '".$fk->getForeignTableName()."', '".strtoupper($fk->getMappedForeignColumn($col->getName()))."', ".($col->isNotNull() ? 'true' : 'false').", ".$size.", $default);"; - } - } else { - $script .= " - \$this->addColumn('$cup', '$cfc', '".$col->getType()."', ".var_export($col->isNotNull(), true).", ".$size.", $default);"; - } - } // if col-is prim key - } // foreach - - // validators - $script .= " - // validators"; - foreach ($table->getValidators() as $val) { - $col = $val->getColumn(); - $cup = strtoupper($col->getName()); - foreach ($val->getRules() as $rule) { - if ($val->getTranslate() !== Validator::TRANSLATE_NONE) { - $script .= " - \$this->addValidator('$cup', '".$rule->getName()."', '".$rule->getClass()."', '".str_replace("'", "\'", $rule->getValue())."', ".$val->getTranslate()."('".str_replace("'", "\'", $rule->getMessage())."'));"; - } else { - $script .= " - \$this->addValidator('$cup', '".$rule->getName()."', '".$rule->getClass()."', '".str_replace("'", "\'", $rule->getValue())."', '".str_replace("'", "\'", $rule->getMessage())."');"; - } // if ($rule->getTranslation() ... - } // foreach rule - } // foreach validator - - $script .= " - } // initialize() -"; - - } - - /** - * Adds the method that build the RelationMap objects - * @param string &$script The script will be modified in this method. - */ - protected function addBuildRelations(&$script) - { - $script .= " - /** - * Build the RelationMap objects for this table relationships - */ - public function buildRelations() - {"; - foreach ($this->getTable()->getForeignKeys() as $fkey) - { - $columnMapping = 'array('; - foreach ($fkey->getLocalForeignMapping() as $key => $value) - { - $columnMapping .= "'$key' => '$value', "; - } - $columnMapping .= ')'; - $onDelete = $fkey->hasOnDelete() ? "'" . $fkey->getOnDelete() . "'" : 'null'; - $onUpdate = $fkey->hasOnUpdate() ? "'" . $fkey->getOnUpdate() . "'" : 'null'; - $script .= " - \$this->addRelation('" . $this->getFKPhpNameAffix($fkey) . "', '" . addslashes($this->getNewStubObjectBuilder($fkey->getForeignTable())->getFullyQualifiedClassname()) . "', RelationMap::MANY_TO_ONE, $columnMapping, $onDelete, $onUpdate);"; - } - foreach ($this->getTable()->getReferrers() as $fkey) - { - $columnMapping = 'array('; - foreach ($fkey->getForeignLocalMapping() as $key => $value) - { - $columnMapping .= "'$key' => '$value', "; - } - $columnMapping .= ')'; - $onDelete = $fkey->hasOnDelete() ? "'" . $fkey->getOnDelete() . "'" : 'null'; - $onUpdate = $fkey->hasOnUpdate() ? "'" . $fkey->getOnUpdate() . "'" : 'null'; - $script .= " - \$this->addRelation('" . $this->getRefFKPhpNameAffix($fkey) . "', '" . addslashes($this->getNewStubObjectBuilder($fkey->getTable())->getFullyQualifiedClassname()) . "', RelationMap::ONE_TO_" . ($fkey->isLocalPrimaryKey() ? "ONE" : "MANY") .", $columnMapping, $onDelete, $onUpdate);"; - } - foreach ($this->getTable()->getCrossFks() as $fkList) - { - list($refFK, $crossFK) = $fkList; - $onDelete = $fkey->hasOnDelete() ? "'" . $fkey->getOnDelete() . "'" : 'null'; - $onUpdate = $fkey->hasOnUpdate() ? "'" . $fkey->getOnUpdate() . "'" : 'null'; - $script .= " - \$this->addRelation('" . $this->getFKPhpNameAffix($crossFK) . "', '" . addslashes($this->getNewStubObjectBuilder($crossFK->getForeignTable())->getFullyQualifiedClassname()) . "', RelationMap::MANY_TO_MANY, array(), $onDelete, $onUpdate);"; - } - $script .= " - } // buildRelations() -"; - } - - /** - * Adds the behaviors getter - * @param string &$script The script will be modified in this method. - */ - protected function addGetBehaviors(&$script) - { - if ($behaviors = $this->getTable()->getBehaviors()) - { - $script .= " - /** - * - * Gets the list of behaviors registered for this table - * - * @return array Associative array (name => parameters) of behaviors - */ - public function getBehaviors() - { - return array("; - foreach ($behaviors as $behavior) - { - $script .= " - '{$behavior->getName()}' => array("; - foreach ($behavior->getParameters() as $key => $value) - { - $script .= "'$key' => '$value', "; - } - $script .= "),"; - } - $script .= " - ); - } // getBehaviors() -"; - } - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier = null) - { - return parent::hasBehaviorModifier($hookName, 'TableMapBuilderModifier'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifier($hookName, &$script, $tab = " ") - { - return $this->applyBehaviorModifierBase($hookName, 'TableMapBuilderModifier', $script, $tab); - } -} // PHP5TableMapBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/PeerBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/PeerBuilder.php deleted file mode 100644 index 36c8ecb6f..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/PeerBuilder.php +++ /dev/null @@ -1,305 +0,0 @@ - - * @package propel.generator.builder.om - */ -abstract class PeerBuilder extends OMBuilder -{ - - protected $basePeerClass; - protected $basePeerClassname; - - /** - * Constructs a new PeerBuilder subclass. - */ - public function __construct(Table $table) { - parent::__construct($table); - $this->basePeerClassname = $this->basePeerClass = $this->getBasePeer($table); - $pos = strrpos($this->basePeerClassname, '.'); - if ($pos !== false) { - $this->basePeerClassname = substr($this->basePeerClassname, $pos + 1); - } - } - - /** - * Adds the addSelectColumns(), doCount(), etc. methods. - * @param string &$script The script will be modified in this method. - */ - protected function addSelectMethods(&$script) - { - $this->addAddSelectColumns($script); - - $this->addDoCount($script); - - // consider refactoring the doSelect stuff - // into a top-level method - $this->addDoSelectOne($script); - $this->addDoSelect($script); - $this->addDoSelectStmt($script); // <-- there's PDO code in here - - $this->addAddInstanceToPool($script); - $this->addRemoveInstanceFromPool($script); - $this->addGetInstanceFromPool($script); - $this->addClearInstancePool($script); - $this->addClearRelatedInstancePool($script); - - $this->addGetPrimaryKeyHash($script); - $this->addGetPrimaryKeyFromRow($script); - $this->addPopulateObjects($script); // <-- there's PDO code in here - $this->addPopulateObject($script); - - } - - /** - * Adds the correct getOMClass() method, depending on whether this table uses inheritance. - * @param string &$script The script will be modified in this method. - */ - protected function addGetOMClassMethod(&$script) - { - $table = $this->getTable(); - if ($table->getChildrenColumn()) { - $this->addGetOMClass_Inheritance($script); - } else { - if ($table->isAbstract()) { - $this->addGetOMClass_NoInheritance_Abstract($script); - } else { - $this->addGetOMClass_NoInheritance($script); - } - } - } - - /** - * Adds the doInsert(), doUpdate(), doDeleteAll(), doValidate(), etc. methods. - * @param string &$script The script will be modified in this method. - */ - protected function addUpdateMethods(&$script) - { - $this->addDoInsert($script); - $this->addDoUpdate($script); - $this->addDoDeleteAll($script); - $this->addDoDelete($script); - if ($this->isDeleteCascadeEmulationNeeded()) { - $this->addDoOnDeleteCascade($script); - } - if ($this->isDeleteSetNullEmulationNeeded()) { - $this->addDoOnDeleteSetNull($script); - } - $this->addDoValidate($script); - } - - /** - * Adds the retrieveByPK() (and possibly retrieveByPKs()) method(s) appropriate for this class. - * @param string &$script The script will be modified in this method. - */ - protected function addRetrieveByPKMethods(&$script) - { - if (count($this->getTable()->getPrimaryKey()) === 1) { - $this->addRetrieveByPK_SinglePK($script); - $this->addRetrieveByPKs_SinglePK($script); - } else { - $this->addRetrieveByPK_MultiPK($script); - } - } - - /** - * This method adds the contents of the generated class to the script. - * - * This method contains the high-level logic that determines which methods - * get generated. - * - * Hint: Override this method in your subclass if you want to reorganize or - * drastically change the contents of the generated peer class. - * - * @param string &$script The script will be modified in this method. - */ - protected function addClassBody(&$script) - { - - $table = $this->getTable(); - - if (!$table->isAlias()) { - $this->addConstantsAndAttributes($script); - } - - $this->addTranslateFieldName($script); - $this->addGetFieldNames($script); - - if (!$table->isAlias()) { - $this->addAlias($script); // alias() utility method (deprecated?) - $this->addSelectMethods($script); - $this->addGetTableMap($script); - } - - $this->addBuildTableMap($script); - - $this->addGetOMClassMethod($script); - - // add the insert, update, delete, validate etc. methods - if (!$table->isAlias() && !$table->isReadOnly()) { - $this->addUpdateMethods($script); - } - - if (count($table->getPrimaryKey()) > 0) { - $this->addRetrieveByPKMethods($script); - } - } - - /** - * Whether the platform in use requires ON DELETE CASCADE emulation and whether there are references to this table. - * @return boolean - */ - protected function isDeleteCascadeEmulationNeeded() - { - $table = $this->getTable(); - if ((!$this->getPlatform()->supportsNativeDeleteTrigger() || $this->getBuildProperty('emulateForeignKeyConstraints')) && count($table->getReferrers()) > 0) { - foreach ($table->getReferrers() as $fk) { - if ($fk->getOnDelete() == ForeignKey::CASCADE) { - return true; - } - } - } - return false; - } - - /** - * Whether the platform in use requires ON DELETE SETNULL emulation and whether there are references to this table. - * @return boolean - */ - protected function isDeleteSetNullEmulationNeeded() - { - $table = $this->getTable(); - if ((!$this->getPlatform()->supportsNativeDeleteTrigger() || $this->getBuildProperty('emulateForeignKeyConstraints')) && count($table->getReferrers()) > 0) { - foreach ($table->getReferrers() as $fk) { - if ($fk->getOnDelete() == ForeignKey::SETNULL) { - return true; - } - } - } - return false; - } - - /** - * Whether to add the generic mutator methods (setByName(), setByPosition(), fromArray()). - * This is based on the build property propel.addGenericMutators, and also whether the - * table is read-only or an alias. - * @return boolean - */ - protected function isAddGenericMutators() - { - $table = $this->getTable(); - return (!$table->isAlias() && $this->getBuildProperty('addGenericMutators') && !$table->isReadOnly()); - } - - /** - * Whether to add the generic accessor methods (getByName(), getByPosition(), toArray()). - * This is based on the build property propel.addGenericAccessors, and also whether the - * table is an alias. - * @return boolean - */ - protected function isAddGenericAccessors() - { - $table = $this->getTable(); - return (!$table->isAlias() && $this->getBuildProperty('addGenericAccessors')); - } - - /** - * Returns the retrieveByPK method name to use for this table. - * If the table is an alias then the method name looks like "retrieveTablenameByPK" - * otherwise simply "retrieveByPK". - * @return string - */ - public function getRetrieveMethodName() - { - if ($this->getTable()->isAlias()) { - $retrieveMethod = "retrieve" . $this->getTable()->getPhpName() . "ByPK"; - } else { - $retrieveMethod = "retrieveByPK"; - } - return $retrieveMethod; - } - - - /** - * COMPATIBILITY: Get the column constant name (e.g. PeerName::COLUMN_NAME). - * - * This method exists simply because it belonged to the 'PeerBuilder' that this - * class is replacing (because of name conflict more than actual functionality overlap). - * When the new builder model is finished this method will be removed. - * - * @param Column $col The column we need a name for. - * @param string $phpName The PHP Name of the peer class. The 'Peer' is appended automatically. - * - * @return string If $phpName is provided, then will return {$phpName}Peer::COLUMN_NAME; if not, just COLUMN_NAME. - * @deprecated - */ - public static function getColumnName(Column $col, $phpName = null) { - // was it overridden in schema.xml ? - if ($col->getPeerName()) { - $const = strtoupper($col->getPeerName()); - } else { - $const = strtoupper($col->getName()); - } - if ($phpName !== null) { - return $phpName . 'Peer::' . $const; - } else { - return $const; - } - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier = null) - { - return parent::hasBehaviorModifier($hookName, 'PeerBuilderModifier'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifier($hookName, &$script, $tab = " ") - { - return $this->applyBehaviorModifierBase($hookName, 'PeerBuilderModifier', $script, $tab); - } - - /** - * Checks whether any registered behavior content creator on that table exists a contentName - * @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname" - */ - public function getBehaviorContent($contentName) - { - return $this->getBehaviorContentBase($contentName, 'PeerBuilderModifier'); - } - - /** - * Get the BasePeer class name for the current table (e.g. 'BasePeer') - * - * @return string The Base Peer Class name - */ - public function getBasePeerClassname() - { - return $this->basePeerClassname; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/QueryBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/QueryBuilder.php deleted file mode 100644 index 1d21aa59a..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/QueryBuilder.php +++ /dev/null @@ -1,1065 +0,0 @@ -getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceOm')) { - return $namespace . '\\' . $omns; - } else { - return $namespace; - } - } - } - - /** - * Returns the name of the current class being built. - * @return string - */ - public function getUnprefixedClassname() - { - return $this->getBuildProperty('basePrefix') . $this->getStubQueryBuilder()->getUnprefixedClassname(); - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - } - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $modelClass = $this->getStubObjectBuilder()->getClassname(); - $parentClass = $this->getBehaviorContent('parentClass'); - $parentClass = null === $parentClass ? 'ModelCriteria' : $parentClass; - $script .= " -/** - * Base class that represents a query for the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - - // magic orderBy() methods, for IDE completion - foreach ($this->getTable()->getColumns() as $column) { - $script .= " - * @method $queryClass orderBy" . $column->getPhpName() . "(\$order = Criteria::ASC) Order by the " . $column->getName() . " column"; - } - $script .= " - *"; - - // magic groupBy() methods, for IDE completion - foreach ($this->getTable()->getColumns() as $column) { - $script .= " - * @method $queryClass groupBy" . $column->getPhpName() . "() Group by the " . $column->getName() . " column"; - } - - // override the signature of ModelCriteria::left-, right- and innerJoin to specify the class of the returned object, for IDE completion - $script .= " - * - * @method $queryClass leftJoin(\$relation) Adds a LEFT JOIN clause to the query - * @method $queryClass rightJoin(\$relation) Adds a RIGHT JOIN clause to the query - * @method $queryClass innerJoin(\$relation) Adds a INNER JOIN clause to the query - *"; - - // magic XXXjoinYYY() methods, for IDE completion - foreach ($this->getTable()->getForeignKeys() as $fk) { - $relationName = $this->getFKPhpNameAffix($fk); - - $script .= " - * @method $queryClass leftJoin" . $relationName . "(\$relationAlias = '') Adds a LEFT JOIN clause to the query using the " . $relationName . " relation - * @method $queryClass rightJoin" . $relationName . "(\$relationAlias = '') Adds a RIGHT JOIN clause to the query using the " . $relationName . " relation - * @method $queryClass innerJoin" . $relationName . "(\$relationAlias = '') Adds a INNER JOIN clause to the query using the " . $relationName . " relation - *"; - } - foreach ($this->getTable()->getReferrers() as $refFK) { - $relationName = $this->getRefFKPhpNameAffix($refFK); - - $script .= " - * @method $queryClass leftJoin" . $relationName . "(\$relationAlias = '') Adds a LEFT JOIN clause to the query using the " . $relationName . " relation - * @method $queryClass rightJoin" . $relationName . "(\$relationAlias = '') Adds a RIGHT JOIN clause to the query using the " . $relationName . " relation - * @method $queryClass innerJoin" . $relationName . "(\$relationAlias = '') Adds a INNER JOIN clause to the query using the " . $relationName . " relation - *"; - } - - // override the signature of ModelCriteria::findOne() to specify the class of the returned object, for IDE completion - $script .= " - * @method $modelClass findOne(PropelPDO \$con = null) Return the first $modelClass matching the query - * @method $modelClass findOneOrCreate(PropelPDO \$con = null) Return the first $modelClass matching the query, or a new $modelClass object populated from the query conditions when no match is found - *"; - - // magic findBy() methods, for IDE completion - foreach ($this->getTable()->getColumns() as $column) { - $script .= " - * @method $modelClass findOneBy" . $column->getPhpName() . "(" . $column->getPhpType() . " \$" . $column->getName() . ") Return the first $modelClass filtered by the " . $column->getName() . " column"; - } - $script .= " - *"; - foreach ($this->getTable()->getColumns() as $column) { - $script .= " - * @method array findBy" . $column->getPhpName() . "(" . $column->getPhpType() . " \$" . $column->getName() . ") Return $modelClass objects filtered by the " . $column->getName() . " column"; - } - - $script .= " - * - * @package propel.generator.".$this->getPackage()." - */ -abstract class ".$this->getClassname()." extends " . $parentClass . " -{ -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - // namespaces - $this->declareClasses('ModelCriteria', 'Criteria', 'ModelJoin'); - $this->declareClassFromBuilder($this->getStubQueryBuilder()); - $this->declareClassFromBuilder($this->getStubPeerBuilder()); - - // apply behaviors - $this->applyBehaviorModifier('queryAttributes', $script, " "); - $this->addConstructor($script); - $this->addFactory($script); - $this->addFindPk($script); - $this->addFindPks($script); - $this->addFilterByPrimaryKey($script); - $this->addFilterByPrimaryKeys($script); - foreach ($this->getTable()->getColumns() as $col) { - $this->addFilterByCol($script, $col); - } - foreach ($this->getTable()->getForeignKeys() as $fk) { - $this->addFilterByFK($script, $fk); - $this->addJoinFk($script, $fk); - $this->addUseFKQuery($script, $fk); - } - foreach ($this->getTable()->getReferrers() as $refFK) { - $this->addFilterByRefFK($script, $refFK); - $this->addJoinRefFk($script, $refFK); - $this->addUseRefFKQuery($script, $refFK); - } - foreach ($this->getTable()->getCrossFks() as $fkList) { - list($refFK, $crossFK) = $fkList; - $this->addFilterByCrossFK($script, $refFK, $crossFK); - } - $this->addPrune($script); - $this->addBasePreSelect($script); - $this->addBasePreDelete($script); - $this->addBasePostDelete($script); - $this->addBasePreUpdate($script); - $this->addBasePostUpdate($script); - // apply behaviors - $this->applyBehaviorModifier('queryMethods', $script, " "); - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - $this->applyBehaviorModifier('queryFilter', $script, ""); - } - - /** - * Adds the constructor for this object. - * @param string &$script The script will be modified in this method. - * @see addConstructor() - */ - protected function addConstructor(&$script) - { - $this->addConstructorComment($script); - $this->addConstructorOpen($script); - $this->addConstructorBody($script); - $this->addConstructorClose($script); - } - - /** - * Adds the comment for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorComment(&$script) - { - $script .= " - /** - * Initializes internal state of ".$this->getClassname()." object. - * - * @param string \$dbName The dabase name - * @param string \$modelName The phpName of a model, e.g. 'Book' - * @param string \$modelAlias The alias for the model in this query, e.g. 'b' - */"; - } - - /** - * Adds the function declaration for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorOpen(&$script) - { - $table = $this->getTable(); - $script .= " - public function __construct(\$dbName = '" . $table->getDatabase()->getName() . "', \$modelName = '" . addslashes($this->getNewStubObjectBuilder($table)->getFullyQualifiedClassname()) . "', \$modelAlias = null) - {"; - } - - /** - * Adds the function body for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorBody(&$script) - { - $script .= " - parent::__construct(\$dbName, \$modelName, \$modelAlias);"; - } - - /** - * Adds the function close for the constructor - * @param string &$script The script will be modified in this method. - **/ - protected function addConstructorClose(&$script) - { - $script .= " - } -"; - } - - /** - * Adds the factory for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFactory(&$script) - { - $this->addFactoryComment($script); - $this->addFactoryOpen($script); - $this->addFactoryBody($script); - $this->addFactoryClose($script); - } - - /** - * Adds the comment for the factory - * @param string &$script The script will be modified in this method. - **/ - protected function addFactoryComment(&$script) - { - $classname = $this->getNewStubQueryBuilder($this->getTable())->getClassname(); - $script .= " - /** - * Returns a new " . $classname . " object. - * - * @param string \$modelAlias The alias of a model in the query - * @param Criteria \$criteria Optional Criteria to build the query from - * - * @return " . $classname . " - */"; - } - - /** - * Adds the function declaration for the factory - * @param string &$script The script will be modified in this method. - **/ - protected function addFactoryOpen(&$script) - { - $script .= " - public static function create(\$modelAlias = null, \$criteria = null) - {"; - } - - /** - * Adds the function body for the factory - * @param string &$script The script will be modified in this method. - **/ - protected function addFactoryBody(&$script) - { - $classname = $this->getNewStubQueryBuilder($this->getTable())->getClassname(); - $script .= " - if (\$criteria instanceof " . $classname . ") { - return \$criteria; - } - \$query = new " . $classname . "(); - if (null !== \$modelAlias) { - \$query->setModelAlias(\$modelAlias); - } - if (\$criteria instanceof Criteria) { - \$query->mergeWith(\$criteria); - } - return \$query;"; - } - - /** - * Adds the function close for the factory - * @param string &$script The script will be modified in this method. - **/ - protected function addFactoryClose(&$script) - { - $script .= " - } -"; - } - - - /** - * Adds the findPk method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFindPk(&$script) - { - $table = $this->getTable(); - $pks = $table->getPrimaryKey(); - $class = $class = $this->getStubObjectBuilder()->getClassname(); - $script .= " - /** - * Find object by primary key"; - if (count($pks) === 1) { - $pkType = 'mixed'; - $script .= " - * Use instance pooling to avoid a database query if the object exists - * - * \$obj = \$c->findPk(12, \$con);"; - } else { - $examplePk = array_slice(array(12, 34, 56, 78, 91), 0, count($pks)); - $colNames = array(); - foreach ($pks as $col) { - $colNames[]= '$' . $col->getName(); - } - $pkType = 'array['. join($colNames, ', ') . ']'; - $script .= " - * - * \$obj = \$c->findPk(array(" . join($examplePk, ', ') . "), \$con);"; - } - $script .= " - * - * @param " . $pkType . " \$key Primary key to use for the query - * @param PropelPDO \$con an optional connection object - * - * @return " . $class . "|array|mixed the result, formatted by the current formatter - */ - public function findPk(\$key, \$con = null) - {"; - if (count($pks) === 1) { - $poolKeyHashParams = '$key'; - } else { - $poolKeyHashParams = array(); - for ($i = 0, $count = count($pks); $i < $count; $i++) { - $poolKeyHashParams[]= '$key[' . $i . ']'; - } - } - // tip: we don't use findOne() to avoid putting an unecessary LIMIT 1 statement, - // which may be costly on platforms not natively supporting LIMIT (like Oracle) - $script .= " - if ((null !== (\$obj = ".$this->getPeerClassname()."::getInstanceFromPool(".$this->getPeerBuilder()->getInstancePoolKeySnippet($poolKeyHashParams)."))) && \$this->getFormatter()->isObjectFormatter()) { - // the object is alredy in the instance pool - return \$obj; - } else { - // the object has not been requested yet, or the formatter is not an object formatter - \$criteria = \$this->isKeepQuery() ? clone \$this : \$this; - \$stmt = \$criteria - ->filterByPrimaryKey(\$key) - ->getSelectStatement(\$con); - return \$criteria->getFormatter()->init(\$criteria)->formatOne(\$stmt); - } - } -"; - } - - /** - * Adds the findPks method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFindPks(&$script) - { - $table = $this->getTable(); - $pks = $table->getPrimaryKey(); - $count = count($pks); - $script .= " - /** - * Find objects by primary key - * "; - if ($count === 1) { - $script .= " - * \$objs = \$c->findPks(array(12, 56, 832), \$con);"; - } else { - $script .= " - * \$objs = \$c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), \$con);"; - } - $script .= " - * - * @param array \$keys Primary keys to use for the query - * @param PropelPDO \$con an optional connection object - * - * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter - */ - public function findPks(\$keys, \$con = null) - { - \$criteria = \$this->isKeepQuery() ? clone \$this : \$this; - return \$this - ->filterByPrimaryKeys(\$keys) - ->find(\$con); - } -"; - } - - /** - * Adds the filterByPrimaryKey method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFilterByPrimaryKey(&$script) - { - $script .= " - /** - * Filter the query by primary key - * - * @param mixed \$key Primary key to use for the query - * - * @return " . $this->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface - */ - public function filterByPrimaryKey(\$key) - {"; - $table = $this->getTable(); - $pks = $table->getPrimaryKey(); - if (count($pks) === 1) { - // simple primary key - $col = $pks[0]; - $const = $this->getColumnConstant($col); - $script .= " - return \$this->addUsingAlias($const, \$key, Criteria::EQUAL);"; - } else { - // composite primary key - $i = 0; - foreach ($pks as $col) { - $const = $this->getColumnConstant($col); - $script .= " - \$this->addUsingAlias($const, \$key[$i], Criteria::EQUAL);"; - $i++; - } - $script .= " - - return \$this;"; - } - $script .= " - } -"; - } - - /** - * Adds the filterByPrimaryKey method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFilterByPrimaryKeys(&$script) - { - $script .= " - /** - * Filter the query by a list of primary keys - * - * @param array \$keys The list of primary key to use for the query - * - * @return " . $this->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface - */ - public function filterByPrimaryKeys(\$keys) - {"; - $table = $this->getTable(); - $pks = $table->getPrimaryKey(); - if (count($pks) === 1) { - // simple primary key - $col = $pks[0]; - $const = $this->getColumnConstant($col); - $script .= " - return \$this->addUsingAlias($const, \$keys, Criteria::IN);"; - } else { - // composite primary key - $script .= " - foreach (\$keys as \$key) {"; - $i = 0; - foreach ($pks as $col) { - $const = $this->getColumnConstant($col); - $script .= " - \$cton$i = \$this->getNewCriterion($const, \$key[$i], Criteria::EQUAL);"; - if ($i>0) { - $script .= " - \$cton0->addAnd(\$cton$i);"; - } - $i++; - } - $script .= " - \$this->addOr(\$cton0); - }"; - $script .= " - - return \$this;"; - } - $script .= " - } -"; - } - - /** - * Adds the filterByCol method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFilterByCol(&$script, $col) - { - $colPhpName = $col->getPhpName(); - $colName = $col->getName(); - $variableName = $col->getStudlyPhpName(); - $qualifiedName = $this->getColumnConstant($col); - $script .= " - /** - * Filter the query on the $colName column - * "; - if ($col->isNumericType() || $col->isTemporalType()) { - $script .= " - * @param " . $col->getPhpType() . "|array \$$variableName The value to use as filter. - * Accepts an associative array('min' => \$minValue, 'max' => \$maxValue)"; - } elseif ($col->isTextType()) { - $script .= " - * @param string \$$variableName The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE)"; - } elseif ($col->isBooleanType()) { - $script .= " - * @param boolean|string \$$variableName The value to use as filter. - * Accepts strings ('false', 'off', '-', 'no', 'n', and '0' are false, the rest is true)"; - } else { - $script .= " - * @param mixed \$$variableName The value to use as filter"; - } - $script .= " - * @param string \$comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return " . $this->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface - */ - public function filterBy$colPhpName(\$$variableName = null, \$comparison = null) - {"; - if ($col->isPrimaryKey() && ($col->getType() == PropelTypes::INTEGER || $col->getType() == PropelTypes::BIGINT)) { - $script .= " - if (is_array(\$$variableName) && null === \$comparison) { - \$comparison = Criteria::IN; - }"; - } elseif ($col->isNumericType() || $col->isTemporalType()) { - $script .= " - if (is_array(\$$variableName)) { - \$useMinMax = false; - if (isset(\${$variableName}['min'])) { - \$this->addUsingAlias($qualifiedName, \${$variableName}['min'], Criteria::GREATER_EQUAL); - \$useMinMax = true; - } - if (isset(\${$variableName}['max'])) { - \$this->addUsingAlias($qualifiedName, \${$variableName}['max'], Criteria::LESS_EQUAL); - \$useMinMax = true; - } - if (\$useMinMax) { - return \$this; - } - if (null === \$comparison) { - \$comparison = Criteria::IN; - } - }"; - } elseif ($col->isTextType()) { - $script .= " - if (null === \$comparison) { - if (is_array(\$$variableName)) { - \$comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', \$$variableName)) { - \$$variableName = str_replace('*', '%', \$$variableName); - \$comparison = Criteria::LIKE; - } - }"; - } elseif ($col->isBooleanType()) { - $script .= " - if (is_string(\$$variableName)) { - \$$colName = in_array(strtolower(\$$variableName), array('false', 'off', '-', 'no', 'n', '0')) ? false : true; - }"; - } - $script .= " - return \$this->addUsingAlias($qualifiedName, \$$variableName, \$comparison); - } -"; - } - - /** - * Adds the filterByFk method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFilterByFk(&$script, $fk) - { - $table = $this->getTable(); - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $fkTable = $this->getForeignTable($fk); - $fkPhpName = $this->getNewStubObjectBuilder($fkTable)->getClassname(); - $relationName = $this->getFKPhpNameAffix($fk); - $objectName = '$' . $fkTable->getStudlyPhpName(); - $script .= " - /** - * Filter the query by a related $fkPhpName object - * - * @param $fkPhpName $objectName the related object to use as filter - * @param string \$comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return $queryClass The current query, for fluid interface - */ - public function filterBy$relationName($objectName, \$comparison = null) - { - return \$this"; - foreach ($fk->getLocalForeignMapping() as $localColumn => $foreignColumn) { - $localColumnObject = $table->getColumn($localColumn); - $foreignColumnObject = $fkTable->getColumn($foreignColumn); - $script .= " - ->addUsingAlias(" . $this->getColumnConstant($localColumnObject) . ", " . $objectName . "->get" . $foreignColumnObject->getPhpName() . "(), \$comparison)"; - } - $script .= "; - } -"; - } - - /** - * Adds the filterByRefFk method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFilterByRefFk(&$script, $fk) - { - $table = $this->getTable(); - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $fkTable = $this->getTable()->getDatabase()->getTable($fk->getTableName()); - $fkPhpName = $this->getNewStubObjectBuilder($fkTable)->getClassname(); - $relationName = $this->getRefFKPhpNameAffix($fk); - $objectName = '$' . $fkTable->getStudlyPhpName(); - $script .= " - /** - * Filter the query by a related $fkPhpName object - * - * @param $fkPhpName $objectName the related object to use as filter - * @param string \$comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return $queryClass The current query, for fluid interface - */ - public function filterBy$relationName($objectName, \$comparison = null) - { - return \$this"; - foreach ($fk->getForeignLocalMapping() as $localColumn => $foreignColumn) { - $localColumnObject = $table->getColumn($localColumn); - $foreignColumnObject = $fkTable->getColumn($foreignColumn); - $script .= " - ->addUsingAlias(" . $this->getColumnConstant($localColumnObject) . ", " . $objectName . "->get" . $foreignColumnObject->getPhpName() . "(), \$comparison)"; - } - $script .= "; - } -"; - } - - /** - * Adds the joinFk method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addJoinFk(&$script, $fk) - { - $table = $this->getTable(); - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $fkTable = $this->getForeignTable($fk); - $relationName = $this->getFKPhpNameAffix($fk); - $joinType = $this->getJoinType($fk); - $this->addJoinRelated($script, $fkTable, $queryClass, $relationName, $joinType); - } - - /** - * Adds the joinRefFk method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addJoinRefFk(&$script, $fk) - { - $table = $this->getTable(); - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $fkTable = $this->getTable()->getDatabase()->getTable($fk->getTableName()); - $relationName = $this->getRefFKPhpNameAffix($fk); - $joinType = $this->getJoinType($fk); - $this->addJoinRelated($script, $fkTable, $queryClass, $relationName, $joinType); - } - - /** - * Adds a joinRelated method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addJoinRelated(&$script, $fkTable, $queryClass, $relationName, $joinType) - { - $script .= " - /** - * Adds a JOIN clause to the query using the " . $relationName . " relation - * - * @param string \$relationAlias optional alias for the relation - * @param string \$joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return ". $queryClass . " The current query, for fluid interface - */ - public function join" . $relationName . "(\$relationAlias = '', \$joinType = " . $joinType . ") - { - \$tableMap = \$this->getTableMap(); - \$relationMap = \$tableMap->getRelation('" . $relationName . "'); - - // create a ModelJoin object for this join - \$join = new ModelJoin(); - \$join->setJoinType(\$joinType); - \$join->setRelationMap(\$relationMap, \$this->useAliasInSQL ? \$this->getModelAlias() : null, \$relationAlias); - if (\$previousJoin = \$this->getPreviousJoin()) { - \$join->setPreviousJoin(\$previousJoin); - } - - // add the ModelJoin to the current object - if(\$relationAlias) { - \$this->addAlias(\$relationAlias, \$relationMap->getRightTable()->getName()); - \$this->addJoinObject(\$join, \$relationAlias); - } else { - \$this->addJoinObject(\$join, '" . $relationName . "'); - } - - return \$this; - } -"; - } - - /** - * Adds the useFkQuery method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addUseFkQuery(&$script, $fk) - { - $table = $this->getTable(); - $fkTable = $this->getForeignTable($fk); - $queryClass = $this->getNewStubQueryBuilder($fkTable)->getClassname(); - $relationName = $this->getFKPhpNameAffix($fk); - $joinType = $this->getJoinType($fk); - $this->addUseRelatedQuery($script, $fkTable, $queryClass, $relationName, $joinType); - } - - /** - * Adds the useFkQuery method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addUseRefFkQuery(&$script, $fk) - { - $table = $this->getTable(); - $fkTable = $this->getTable()->getDatabase()->getTable($fk->getTableName()); - $queryClass = $this->getNewStubQueryBuilder($fkTable)->getClassname(); - $relationName = $this->getRefFKPhpNameAffix($fk); - $joinType = $this->getJoinType($fk); - $this->addUseRelatedQuery($script, $fkTable, $queryClass, $relationName, $joinType); - } - - /** - * Adds a useRelatedQuery method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addUseRelatedQuery(&$script, $fkTable, $queryClass, $relationName, $joinType) - { - $script .= " - /** - * Use the $relationName relation " . $fkTable->getPhpName() . " object - * - * @see useQuery() - * - * @param string \$relationAlias optional alias for the relation, - * to be used as main alias in the secondary query - * @param string \$joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return $queryClass A secondary query class using the current class as primary query - */ - public function use" . $relationName . "Query(\$relationAlias = '', \$joinType = " . $joinType . ") - { - return \$this - ->join" . $relationName . "(\$relationAlias, \$joinType) - ->useQuery(\$relationAlias ? \$relationAlias : '$relationName', '$queryClass'); - } -"; - } - - protected function addFilterByCrossFK(&$script, $refFK, $crossFK) - { - $queryClass = $this->getStubQueryBuilder()->getClassname(); - $crossRefTable = $crossFK->getTable(); - $foreignTable = $crossFK->getForeignTable(); - $fkPhpName = $foreignTable->getPhpName(); - $crossTableName = $crossRefTable->getName(); - $relName = $this->getFKPhpNameAffix($crossFK, $plural = false); - $objectName = '$' . $foreignTable->getStudlyPhpName(); - $relationName = $this->getRefFKPhpNameAffix($refFK, $plural = false); - $script .= " - /** - * Filter the query by a related $fkPhpName object - * using the $crossTableName table as cross reference - * - * @param $fkPhpName $objectName the related object to use as filter - * @param string \$comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return $queryClass The current query, for fluid interface - */ - public function filterBy{$relName}($objectName, \$comparison = Criteria::EQUAL) - { - return \$this - ->use{$relationName}Query() - ->filterBy{$relName}($objectName, \$comparison) - ->endUse(); - } - "; - } - - /** - * Adds the prune method for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addPrune(&$script) - { - $table = $this->getTable(); - $class = $this->getStubObjectBuilder()->getClassname(); - $objectName = '$' . $table->getStudlyPhpName(); - $script .= " - /** - * Exclude object from result - * - * @param $class $objectName Object to remove from the list of results - * - * @return " . $this->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface - */ - public function prune($objectName = null) - { - if ($objectName) {"; - $pks = $table->getPrimaryKey(); - if (count($pks) > 1) { - $i = 0; - $conditions = array(); - foreach ($pks as $col) { - $const = $this->getColumnConstant($col); - $condName = "'pruneCond" . $i . "'"; - $conditions[]= $condName; - $script .= " - \$this->addCond(". $condName . ", \$this->getAliasedColName($const), " . $objectName . "->get" . $col->getPhpName() . "(), Criteria::NOT_EQUAL);"; - $i++; - } - $conditionsString = implode(', ', $conditions); - $script .= " - \$this->combine(array(" . $conditionsString . "), Criteria::LOGICAL_OR);"; - } else { - $col = $pks[0]; - $const = $this->getColumnConstant($col); - $script .= " - \$this->addUsingAlias($const, " . $objectName . "->get" . $col->getPhpName() . "(), Criteria::NOT_EQUAL);"; - } - $script .= " - } - - return \$this; - } -"; - } - - /** - * Adds the basePreSelect hook for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addBasePreSelect(&$script) - { - $behaviorCode = ''; - $this->applyBehaviorModifier('preSelectQuery', $behaviorCode, " "); - if (!$behaviorCode) { - return; - } - $script .= " - /** - * Code to execute before every SELECT statement - * - * @param PropelPDO \$con The connection object used by the query - */ - protected function basePreSelect(PropelPDO \$con) - {" . $behaviorCode . " - - return \$this->preSelect(\$con); - } -"; - } - - /** - * Adds the basePreDelete hook for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addBasePreDelete(&$script) - { - $behaviorCode = ''; - $this->applyBehaviorModifier('preDeleteQuery', $behaviorCode, " "); - if (!$behaviorCode) { - return; - } - $script .= " - /** - * Code to execute before every DELETE statement - * - * @param PropelPDO \$con The connection object used by the query - */ - protected function basePreDelete(PropelPDO \$con) - {" . $behaviorCode . " - - return \$this->preDelete(\$con); - } -"; - } - - /** - * Adds the basePostDelete hook for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addBasePostDelete(&$script) - { - $behaviorCode = ''; - $this->applyBehaviorModifier('postDeleteQuery', $behaviorCode, " "); - if (!$behaviorCode) { - return; - } - $script .= " - /** - * Code to execute after every DELETE statement - * - * @param int \$affectedRows the number of deleted rows - * @param PropelPDO \$con The connection object used by the query - */ - protected function basePostDelete(\$affectedRows, PropelPDO \$con) - {" . $behaviorCode . " - - return \$this->postDelete(\$affectedRows, \$con); - } -"; - } - - /** - * Adds the basePreUpdate hook for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addBasePreUpdate(&$script) - { - $behaviorCode = ''; - $this->applyBehaviorModifier('preUpdateQuery', $behaviorCode, " "); - if (!$behaviorCode) { - return; - } - $script .= " - /** - * Code to execute before every UPDATE statement - * - * @param array \$values The associatiove array of columns and values for the update - * @param PropelPDO \$con The connection object used by the query - * @param boolean \$forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects - */ - protected function basePreUpdate(&\$values, PropelPDO \$con, \$forceIndividualSaves = false) - {" . $behaviorCode . " - - return \$this->preUpdate(\$values, \$con, \$forceIndividualSaves); - } -"; - } - - /** - * Adds the basePostUpdate hook for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addBasePostUpdate(&$script) - { - $behaviorCode = ''; - $this->applyBehaviorModifier('postUpdateQuery', $behaviorCode, " "); - if (!$behaviorCode) { - return; - } - $script .= " - /** - * Code to execute after every UPDATE statement - * - * @param int \$affectedRows the number of udated rows - * @param PropelPDO \$con The connection object used by the query - */ - protected function basePostUpdate(\$affectedRows, PropelPDO \$con) - {" . $behaviorCode . " - - return \$this->postUpdate(\$affectedRows, \$con); - } -"; - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @return boolean - */ - public function hasBehaviorModifier($hookName, $modifier = null) - { - return parent::hasBehaviorModifier($hookName, 'QueryBuilderModifier'); - } - - /** - * Checks whether any registered behavior on that table has a modifier for a hook - * @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave" - * @param string &$script The script will be modified in this method. - */ - public function applyBehaviorModifier($hookName, &$script, $tab = " ") - { - return $this->applyBehaviorModifierBase($hookName, 'QueryBuilderModifier', $script, $tab); - } - - /** - * Checks whether any registered behavior content creator on that table exists a contentName - * @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname" - */ - public function getBehaviorContent($contentName) - { - return $this->getBehaviorContentBase($contentName, 'QueryBuilderModifier'); - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/om/QueryInheritanceBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/om/QueryInheritanceBuilder.php deleted file mode 100644 index 316a87949..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/om/QueryInheritanceBuilder.php +++ /dev/null @@ -1,276 +0,0 @@ -getBuildProperty('basePrefix') . $this->getNewStubQueryInheritanceBuilder($this->getChild())->getUnprefixedClassname(); - } - - /** - * Gets the package for the [base] object classes. - * @return string - */ - public function getPackage() - { - return parent::getPackage() . ".om"; - } - - public function getNamespace() - { - if ($namespace = parent::getNamespace()) { - if ($this->getGeneratorConfig() && $omns = $this->getGeneratorConfig()->getBuildProperty('namespaceOm')) { - return $namespace . '\\' . $omns; - } else { - return $namespace; - } - } - } - - /** - * Set the child object that we're operating on currrently. - * @param $child Inheritance - */ - public function setChild(Inheritance $child) - { - $this->child = $child; - } - - /** - * Returns the child object we're operating on currently. - * @return Inheritance - * @throws BuildException - if child was not set. - */ - public function getChild() - { - if (!$this->child) { - throw new BuildException("The PHP5MultiExtendObjectBuilder needs to be told which child class to build (via setChild() method) before it can build the stub class."); - } - return $this->child; - } - - /** - * Adds the include() statements for files that this class depends on or utilizes. - * @param string &$script The script will be modified in this method. - */ - protected function addIncludes(&$script) - { - $requiredClassFilePath = $this->getStubQueryBuilder()->getClassFilePath(); - - $script .=" -require '".$requiredClassFilePath."'; -"; - } // addIncludes() - - /** - * Adds class phpdoc comment and openning of class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassOpen(&$script) - { - $table = $this->getTable(); - $tableName = $table->getName(); - $tableDesc = $table->getDescription(); - - $baseBuilder = $this->getStubQueryBuilder(); - $this->declareClassFromBuilder($baseBuilder); - $baseClassname = $baseBuilder->getClassname(); - - $script .= " -/** - * Skeleton subclass for representing a query for one of the subclasses of the '$tableName' table. - * - * $tableDesc - *"; - if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); - $script .= " - * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on: - * - * $now - *"; - } - $script .= " - * You should add additional methods to this class to meet the - * application requirements. This class will only be generated as - * long as it does not already exist in the output directory. - * - * @package propel.generator.".$this->getPackage()." - */ -class " .$this->getClassname() . " extends " . $baseClassname . " { -"; - } - - /** - * Specifies the methods that are added as part of the stub object class. - * - * By default there are no methods for the empty stub classes; override this method - * if you want to change that behavior. - * - * @see ObjectBuilder::addClassBody() - */ - protected function addClassBody(&$script) - { - $this->declareClassFromBuilder($this->getStubPeerBuilder()); - $this->declareClasses('PropelPDO', 'Criteria'); - $this->addFactory($script); - $this->addPreSelect($script); - $this->addPreUpdate($script); - $this->addPreDelete($script); - $this->addDoDeleteAll($script); - } - - /** - * Adds the factory for this object. - * @param string &$script The script will be modified in this method. - */ - protected function addFactory(&$script) - { - $builder = $this->getNewStubQueryInheritanceBuilder($this->getChild()); - $this->declareClassFromBuilder($builder); - $classname = $builder->getClassname(); - $script .= " - /** - * Returns a new " . $classname . " object. - * - * @param string \$modelAlias The alias of a model in the query - * @param Criteria \$criteria Optional Criteria to build the query from - * - * @return " . $classname . " - */ - public static function create(\$modelAlias = null, \$criteria = null) - { - if (\$criteria instanceof " . $classname . ") { - return \$criteria; - } - \$query = new " . $classname . "(); - if (null !== \$modelAlias) { - \$query->setModelAlias(\$modelAlias); - } - if (\$criteria instanceof Criteria) { - \$query->mergeWith(\$criteria); - } - return \$query; - } -"; - } - - protected function addPreSelect(&$script) - { - $child = $this->getChild(); - $col = $child->getColumn(); - - $script .= " - /** - * Filters the query to target only " . $child->getClassname() . " objects. - */ - public function preSelect(PropelPDO \$con) - { - " . $this->getClassKeyCondition() . " - } -"; - } - - protected function addPreUpdate(&$script) - { - $child = $this->getChild(); - $col = $child->getColumn(); - - $script .= " - /** - * Filters the query to target only " . $child->getClassname() . " objects. - */ - public function preUpdate(&\$values, PropelPDO \$con, \$forceIndividualSaves = false) - { - " . $this->getClassKeyCondition() . " - } -"; - } - - protected function addPreDelete(&$script) - { - $child = $this->getChild(); - $col = $child->getColumn(); - - $script .= " - /** - * Filters the query to target only " . $child->getClassname() . " objects. - */ - public function preDelete(PropelPDO \$con) - { - " . $this->getClassKeyCondition() . " - } -"; - } - - protected function getClassKeyCondition() - { - $child = $this->getChild(); - $col = $child->getColumn(); - return "\$this->addUsingAlias(" . $col->getConstantName() . ", " . $this->getPeerClassname()."::CLASSKEY_".strtoupper($child->getKey()).");"; - } - - protected function addDoDeleteAll(&$script) - { - $child = $this->getChild(); - - $script .= " - /** - * Issue a DELETE query based on the current ModelCriteria deleting all rows in the table - * Having the " . $child->getClassname() . " class. - * This method is called by ModelCriteria::deleteAll() inside a transaction - * - * @param PropelPDO \$con a connection object - * - * @return integer the number of deleted rows - */ - public function doDeleteAll(\$con) - { - // condition on class key is already added in preDelete() - return parent::doDelete(\$con); - } -"; - } - - /** - * Closes class. - * @param string &$script The script will be modified in this method. - */ - protected function addClassClose(&$script) - { - $script .= " -} // " . $this->getClassname() . " -"; - } - -} // MultiExtensionQueryBuilder diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/DDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/DDLBuilder.php deleted file mode 100644 index db7fffa79..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/DDLBuilder.php +++ /dev/null @@ -1,166 +0,0 @@ - - * @package propel.generator.builder.sql - */ -abstract class DDLBuilder extends DataModelBuilder -{ - - /** - * Builds the SQL for current table and returns it as a string. - * - * This is the main entry point and defines a basic structure that classes should follow. - * In most cases this method will not need to be overridden by subclasses. - * - * @return string The resulting SQL DDL. - */ - public function build() - { - $script = ""; - $this->addTable($script); - $this->addIndices($script); - $this->addForeignKeys($script); - return $script; - } - - /** - * Gets the name to use for creating a sequence for the current table. - * - * This will create a new name or use one specified in an id-method-parameter - * tag, if specified. - * - * @return string Sequence name for this table. - */ - public function getSequenceName() - { - $table = $this->getTable(); - static $longNamesMap = array(); - $result = null; - if ($table->getIdMethod() == IDMethod::NATIVE) { - $idMethodParams = $table->getIdMethodParameters(); - $maxIdentifierLength = $table->getDatabase()->getPlatform()->getMaxColumnNameLength(); - if (empty($idMethodParams)) { - if (strlen($table->getName() . "_SEQ") > $maxIdentifierLength) { - if (!isset($longNamesMap[$table->getName()])) { - $longNamesMap[$table->getName()] = strval(count($longNamesMap) + 1); - } - $result = substr($table->getName(), 0, $maxIdentifierLength - strlen("_SEQ_" . $longNamesMap[$table->getName()])) . "_SEQ_" . $longNamesMap[$table->getName()]; - } - else { - $result = substr($table->getName(), 0, $maxIdentifierLength -4) . "_SEQ"; - } - } else { - $result = substr($idMethodParams[0]->getValue(), 0, $maxIdentifierLength); - } - } - return $result; - } - - /** - * Builds the DDL SQL for a Column object. - * @return string - */ - public function getColumnDDL(Column $col) - { - $platform = $this->getPlatform(); - $domain = $col->getDomain(); - - $sb = ""; - $sb .= $this->quoteIdentifier($col->getName()) . " "; - $sb .= $domain->getSqlType(); - if ($platform->hasSize($domain->getSqlType())) { - $sb .= $domain->printSize(); - } - $sb .= " "; - $sb .= $col->getDefaultSetting() . " "; - $sb .= $col->getNotNullString() . " "; - $sb .= $col->getAutoIncrementString(); - - return trim($sb); - } - - /** - * Creates a delimiter-delimited string list of column names, quoted using quoteIdentifier(). - * @param array Column[] or string[] - * @param string $delim The delimiter to use in separating the column names. - * @return string - */ - public function getColumnList($columns, $delim=',') - { - $list = array(); - foreach ($columns as $col) { - if ($col instanceof Column) { - $col = $col->getName(); - } - $list[] = $this->quoteIdentifier($col); - } - return implode($delim, $list); - } - - /** - * This function adds any _database_ start/initialization SQL. - * This is designed to be called for a database, not a specific table, hence it is static. - * @return string The DDL is returned as astring. - */ - public static function getDatabaseStartDDL() - { - return ''; - } - - /** - * This function adds any _database_ end/cleanup SQL. - * This is designed to be called for a database, not a specific table, hence it is static. - * @return string The DDL is returned as astring. - */ - public static function getDatabaseEndDDL() - { - return ''; - } - - /** - * Resets any static variables between building a SQL file for a database. - * - * Theoretically, Propel could build multiple .sql files for multiple databases; in - * many cases we don't want static values to persist between these. This method provides - * a way to clear out static values between iterations, if the subclasses choose to implement - * it. - */ - public static function reset() - { - // nothing by default - } - - /** - * Adds table definition. - * @param string &$script The script will be modified in this method. - */ - abstract protected function addTable(&$script); - - /** - * Adds index definitions. - * @param string &$script The script will be modified in this method. - */ - abstract protected function addIndices(&$script); - - /** - * Adds foreign key constraint definitions. - * @param string &$script The script will be modified in this method. - */ - abstract protected function addForeignKeys(&$script); - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/DataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/DataSQLBuilder.php deleted file mode 100644 index 012498602..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/DataSQLBuilder.php +++ /dev/null @@ -1,253 +0,0 @@ - - * @package propel.generator.builder.sql - */ -abstract class DataSQLBuilder extends DataModelBuilder -{ - - /** - * Perform any reset between runs of this builder. - * - * This can be used, for example, to clear any stored start/end SQL. - */ - public static function reset() - { - // does nothing by default - } - - /** - * Gets any SQL to place at the start of all the row inserts. - * - * @return string - */ - public static function getDatabaseStartSql() - { - return ''; - } - - /** - * Gets any SQL to place at the end of all the row inserts. - * - * @return string - */ - public static function getDatabaseEndSql() - { - return ''; - } - - /** - * Gets any SQL to place before row inserts for a new table. - * - * @return string - */ - public function getTableStartSql() - { - return ''; - } - - /** - * Gets any SQL to place at the end of row inserts for a table. - * - * @return string - */ - public function getTableEndSql() - { - return ''; - } - - /** - * The main method in this class, returns the SQL for INSERTing data into a row. - * @param DataRow $row The row to process. - * @return string - */ - public function buildRowSql(DataRow $row) - { - $sql = ""; - $platform = $this->getPlatform(); - $table = $this->getTable(); - - $sql .= "INSERT INTO ".$this->quoteIdentifier($this->getTable()->getName())." ("; - - // add column names to SQL - $colNames = array(); - foreach ($row->getColumnValues() as $colValue) { - $colNames[] = $this->quoteIdentifier($colValue->getColumn()->getName()); - } - - $sql .= implode(',', $colNames); - - $sql .= ") VALUES ("; - - $colVals = array(); - foreach ($row->getColumnValues() as $colValue) { - $colVals[] = $this->getColumnValueSql($colValue); - } - - $sql .= implode(',', $colVals); - $sql .= "); -"; - - return $sql; - } - - /** - * Gets the propertly escaped (and quoted) value for a column. - * @param ColumnValue $colValue - * @return mixed The proper value to be added to the string. - */ - protected function getColumnValueSql(ColumnValue $colValue) - { - $column = $colValue->getColumn(); - $method = 'get' . $column->getPhpNative() . 'Sql'; - return $this->$method($colValue->getValue()); - } - - - - /** - * Gets a representation of a binary value suitable for use in a SQL statement. - * Default behavior is true = 1, false = 0. - * @param boolean $value - * @return int - */ - protected function getBooleanSql($value) - { - return (int) $value; - } - - - /** - * Gets a representation of a BLOB/LONGVARBINARY value suitable for use in a SQL statement. - * @param mixed $blob Blob object or string data. - * @return string - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - return $this->getPlatform()->quote($blob->__toString()); - } else { - return $this->getPlatform()->quote($blob); - } - } - - /** - * Gets a representation of a CLOB/LONGVARCHAR value suitable for use in a SQL statement. - * @param mixed $clob Clob object or string data. - * @return string - */ - protected function getClobSql($clob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($clob)) { - return $this->getPlatform()->quote($clob->__toString()); - } else { - return $this->getPlatform()->quote($clob); - } - } - - /** - * Gets a representation of a date value suitable for use in a SQL statement. - * @param string $value - * @return string - */ - protected function getDateSql($value) - { - return "'" . date('Y-m-d', strtotime($value)) . "'"; - } - - /** - * Gets a representation of a decimal value suitable for use in a SQL statement. - * @param double $value - * @return float - */ - protected function getDecimalSql($value) - { - return (float) $value; - } - - /** - * Gets a representation of a double value suitable for use in a SQL statement. - * @param double $value - * @return double - */ - protected function getDoubleSql($value) - { - return (double) $value; - } - - /** - * Gets a representation of a float value suitable for use in a SQL statement. - * @param float $value - * @return float - */ - protected function getFloatSql($value) - { - return (float) $value; - } - - /** - * Gets a representation of an integer value suitable for use in a SQL statement. - * @param int $value - * @return int - */ - protected function getIntSql($value) - { - return (int) $value; - } - - /** - * Gets a representation of a NULL value suitable for use in a SQL statement. - * @return null - */ - protected function getNullSql() - { - return 'NULL'; - } - - /** - * Gets a representation of a string value suitable for use in a SQL statement. - * @param string $value - * @return string - */ - protected function getStringSql($value) - { - return $this->getPlatform()->quote($value); - } - - /** - * Gets a representation of a time value suitable for use in a SQL statement. - * @param string $value - * @return string - */ - protected function getTimeSql($paramIndex, $value) - { - return "'" . date('H:i:s', strtotime($value)) . "'"; - } - - /** - * Gets a representation of a timestamp value suitable for use in a SQL statement. - * @param string $value - * @return string - */ - function getTimestampSql($value) - { - return "'" . date('Y-m-d H:i:s', strtotime($value)) . "'"; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDDLBuilder.php deleted file mode 100644 index 2bd923e3b..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDDLBuilder.php +++ /dev/null @@ -1,173 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class MssqlDDLBuilder extends DDLBuilder -{ - - private static $dropCount = 0; - - /** - * - * @see parent::addDropStatement() - */ - protected function addDropStatements(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getForeignKeys() as $fk) { - $script .= " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='".$fk->getName()."') - ALTER TABLE ".$this->quoteIdentifier($table->getName())." DROP CONSTRAINT ".$this->quoteIdentifier($fk->getName())."; -"; - } - - - self::$dropCount++; - - $script .= " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = '".$table->getName()."') -BEGIN - DECLARE @reftable_".self::$dropCount." nvarchar(60), @constraintname_".self::$dropCount." nvarchar(60) - DECLARE refcursor CURSOR FOR - select reftables.name tablename, cons.name constraintname - from sysobjects tables, - sysobjects reftables, - sysobjects cons, - sysreferences ref - where tables.id = ref.rkeyid - and cons.id = ref.constid - and reftables.id = ref.fkeyid - and tables.name = '".$table->getName()."' - OPEN refcursor - FETCH NEXT from refcursor into @reftable_".self::$dropCount.", @constraintname_".self::$dropCount." - while @@FETCH_STATUS = 0 - BEGIN - exec ('alter table '+@reftable_".self::$dropCount."+' drop constraint '+@constraintname_".self::$dropCount.") - FETCH NEXT from refcursor into @reftable_".self::$dropCount.", @constraintname_".self::$dropCount." - END - CLOSE refcursor - DEALLOCATE refcursor - DROP TABLE ".$this->quoteIdentifier($table->getName())." -END -"; - } - - /** - * @see parent::addColumns() - */ - protected function addTable(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " -/* ---------------------------------------------------------------------- */ -/* ".$table->getName()." */ -/* ---------------------------------------------------------------------- */ - -"; - - $this->addDropStatements($script); - - $script .= " - -CREATE TABLE ".$this->quoteIdentifier($table->getName())." -( - "; - - $lines = array(); - - foreach ($table->getColumns() as $col) { - $lines[] = $this->getColumnDDL($col); - } - - if ($table->hasPrimaryKey()) { - $lines[] = "CONSTRAINT ".$this->quoteIdentifier($table->getName()."_PK") . " PRIMARY KEY (".$this->getColumnList($table->getPrimaryKey()).")"; - } - - foreach ($table->getUnices() as $unique ) { - $lines[] = "UNIQUE (".$this->getColumnList($unique->getColumns()).")"; - } - - $sep = ", - "; - $script .= implode($sep, $lines); - $script .= " -); -"; - } - - /** - * Adds CREATE INDEX statements for this table. - * @see parent::addIndices() - */ - protected function addIndices(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getIndices() as $index) { - $script .= " -CREATE "; - if ($index->getIsUnique()) { - $script .= "UNIQUE"; - } - $script .= "INDEX ".$this->quoteIdentifier($index->getName())." ON ".$this->quoteIdentifier($table->getName())." (".$this->getColumnList($index->getColumns())."); -"; - } - } - - /** - * - * @see parent::addForeignKeys() - */ - protected function addForeignKeys(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getForeignKeys() as $fk) { - $script .= " -BEGIN -ALTER TABLE ".$this->quoteIdentifier($table->getName())." ADD CONSTRAINT ".$this->quoteIdentifier($fk->getName())." FOREIGN KEY (".$this->getColumnList($fk->getLocalColumns()) .") REFERENCES ".$this->quoteIdentifier($fk->getForeignTableName())." (".$this->getColumnList($fk->getForeignColumns()).")"; - if ($fk->hasOnUpdate()) { - if ($fk->getOnUpdate() == ForeignKey::SETNULL) { // there may be others that also won't work - // we have to skip this because it's unsupported. - $this->warn("MSSQL doesn't support the 'SET NULL' option for ON UPDATE (ignoring for ".$this->getColumnList($fk->getLocalColumns())." fk)."); - } else { - $script .= " ON UPDATE ".$fk->getOnUpdate(); - } - - } - if ($fk->hasOnDelete()) { - if ($fk->getOnDelete() == ForeignKey::SETNULL) { // there may be others that also won't work - // we have to skip this because it's unsupported. - $this->warn("MSSQL doesn't support the 'SET NULL' option for ON DELETE (ignoring for ".$this->getColumnList($fk->getLocalColumns())." fk)."); - } else { - $script .= " ON DELETE ".$fk->getOnDelete(); - } - } - $script .= " -END -; -"; - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php deleted file mode 100644 index a72bad2e0..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php +++ /dev/null @@ -1,37 +0,0 @@ - - * @package propel.generator.builder.sql.mssql - */ -class MssqlDataSQLBuilder extends DataSQLBuilder -{ - - /** - * - * @param mixed $blob Blob object or string containing data. - * @return string - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - $blob = $blob->__toString(); - } - $data = unpack("H*hex", $blob); - return '0x'.$data['hex']; // no surrounding quotes! - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDDLBuilder.php deleted file mode 100644 index 67fb15b19..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDDLBuilder.php +++ /dev/null @@ -1,413 +0,0 @@ - - * @package propel.generator.builder.sql.mysql - */ -class MysqlDDLBuilder extends DDLBuilder -{ - - /** - * Returns some header SQL that disables foreign key checking. - * @return string DDL - */ - public static function getDatabaseStartDDL() - { - $ddl = " -# This is a fix for InnoDB in MySQL >= 4.1.x -# It \"suspends judgement\" for fkey relationships until are tables are set. -SET FOREIGN_KEY_CHECKS = 0; -"; - return $ddl; - } - - /** - * Returns some footer SQL that re-enables foreign key checking. - * @return string DDL - */ - public static function getDatabaseEndDDL() - { - $ddl = " -# This restores the fkey checks, after having unset them earlier -SET FOREIGN_KEY_CHECKS = 1; -"; - return $ddl; - } - - - /** - * - * @see parent::addDropStatement() - */ - protected function addDropStatements(&$script) - { - $script .= " -DROP TABLE IF EXISTS ".$this->quoteIdentifier($this->getTable()->getName())."; -"; - } - - /** - * Builds the SQL for current table and returns it as a string. - * - * This is the main entry point and defines a basic structure that classes should follow. - * In most cases this method will not need to be overridden by subclasses. - * - * @return string The resulting SQL DDL. - */ - public function build() - { - $script = ""; - $this->addTable($script); - return $script; - } - - /** - * - * @see parent::addColumns() - */ - protected function addTable(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " -#----------------------------------------------------------------------------- -#-- ".$table->getName()." -#----------------------------------------------------------------------------- -"; - - $this->addDropStatements($script); - - $script .= " - -CREATE TABLE ".$this->quoteIdentifier($table->getName())." -( - "; - - $lines = array(); - - $databaseType = $this->getPlatform()->getDatabaseType(); - - foreach ($table->getColumns() as $col) { - $entry = $this->getColumnDDL($col); - $colinfo = $col->getVendorInfoForType($databaseType); - if ( $colinfo->hasParameter('Charset') ) { - $entry .= ' CHARACTER SET '.$platform->quote($colinfo->getParameter('Charset')); - } - if ( $colinfo->hasParameter('Collation') ) { - $entry .= ' COLLATE '.$platform->quote($colinfo->getParameter('Collation')); - } elseif ( $colinfo->hasParameter('Collate') ) { - $entry .= ' COLLATE '.$platform->quote($colinfo->getParameter('Collate')); - } - if ($col->getDescription()) { - $entry .= " COMMENT ".$platform->quote($col->getDescription()); - } - $lines[] = $entry; - } - - if ($table->hasPrimaryKey()) { - $lines[] = "PRIMARY KEY (".$this->getColumnList($table->getPrimaryKey()).")"; - } - - $this->addIndicesLines($lines); - $this->addForeignKeysLines($lines); - - $sep = ", - "; - $script .= implode($sep, $lines); - - $script .= " -)"; - - $vendorSpecific = $table->getVendorInfoForType($this->getPlatform()->getDatabaseType()); - if ($vendorSpecific->hasParameter('Type')) { - $mysqlTableType = $vendorSpecific->getParameter('Type'); - } elseif ($vendorSpecific->hasParameter('Engine')) { - $mysqlTableType = $vendorSpecific->getParameter('Engine'); - } else { - $mysqlTableType = $this->getBuildProperty("mysqlTableType"); - } - - $script .= sprintf(' %s=%s', $this->getBuildProperty("mysqlTableEngineKeyword"), $mysqlTableType); - - $dbVendorSpecific = $table->getDatabase()->getVendorInfoForType($databaseType); - $tableVendorSpecific = $table->getVendorInfoForType($databaseType); - $vendorSpecific = $dbVendorSpecific->getMergedVendorInfo($tableVendorSpecific); - - if ( $vendorSpecific->hasParameter('Charset') ) { - $script .= ' CHARACTER SET '.$platform->quote($vendorSpecific->getParameter('Charset')); - } - if ( $vendorSpecific->hasParameter('Collate') ) { - $script .= ' COLLATE '.$platform->quote($vendorSpecific->getParameter('Collate')); - } - if ( $vendorSpecific->hasParameter('Checksum') ) { - $script .= ' CHECKSUM='.$platform->quote($vendorSpecific->getParameter('Checksum')); - } - if ( $vendorSpecific->hasParameter('Pack_Keys') ) { - $script .= ' PACK_KEYS='.$platform->quote($vendorSpecific->getParameter('Pack_Keys')); - } - if ( $vendorSpecific->hasParameter('Delay_key_write') ) { - $script .= ' DELAY_KEY_WRITE='.$platform->quote($vendorSpecific->getParameter('Delay_key_write')); - } - - if ($table->getDescription()) { - $script .= " COMMENT=".$platform->quote($table->getDescription()); - } - $script .= "; -"; - } - - /** - * Creates a comma-separated list of column names for the index. - * For MySQL unique indexes there is the option of specifying size, so we cannot simply use - * the getColumnsList() method. - * @param Index $index - * @return string - */ - private function getIndexColumnList(Index $index) - { - $platform = $this->getPlatform(); - - $cols = $index->getColumns(); - $list = array(); - foreach ($cols as $col) { - $list[] = $this->quoteIdentifier($col) . ($index->hasColumnSize($col) ? '(' . $index->getColumnSize($col) . ')' : ''); - } - return implode(', ', $list); - } - - /** - * Adds indexes - */ - protected function addIndicesLines(&$lines) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getUnices() as $unique) { - $lines[] = "UNIQUE KEY ".$this->quoteIdentifier($unique->getName())." (".$this->getIndexColumnList($unique).")"; - } - - foreach ($table->getIndices() as $index ) { - $vendorInfo = $index->getVendorInfoForType($platform->getDatabaseType()); - $lines[] .= (($vendorInfo && $vendorInfo->getParameter('Index_type') == 'FULLTEXT') ? 'FULLTEXT ' : '') . "KEY " . $this->quoteIdentifier($index->getName()) . "(" . $this->getIndexColumnList($index) . ")"; - } - - } - - /** - * Adds foreign key declarations & necessary indexes for mysql (if they don't exist already). - * @see parent::addForeignKeys() - */ - protected function addForeignKeysLines(&$lines) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - - /** - * A collection of indexed columns. The keys is the column name - * (concatenated with a comma in the case of multi-col index), the value is - * an array with the names of the indexes that index these columns. We use - * it to determine which additional indexes must be created for foreign - * keys. It could also be used to detect duplicate indexes, but this is not - * implemented yet. - * @var array - */ - $_indices = array(); - - $this->collectIndexedColumns('PRIMARY', $table->getPrimaryKey(), $_indices, 'getName'); - - $_tableIndices = array_merge($table->getIndices(), $table->getUnices()); - foreach ($_tableIndices as $_index) { - $this->collectIndexedColumns($_index->getName(), $_index->getColumns(), $_indices); - } - - // we're determining which tables have foreign keys that point to this table, since MySQL needs an index on - // any column that is referenced by another table (yep, MySQL _is_ a PITA) - $counter = 0; - $allTables = $table->getDatabase()->getTables(); - foreach ($allTables as $_table) { - foreach ($_table->getForeignKeys() as $_foreignKey) { - if ($_foreignKey->getForeignTableName() == $table->getName()) { - $referencedColumns = $_foreignKey->getForeignColumns(); - $referencedColumnsHash = $this->getColumnList($referencedColumns); - if (!array_key_exists($referencedColumnsHash, $_indices)) { - // no matching index defined in the schema, so we have to create one - $indexName = "I_referenced_".$_foreignKey->getName()."_".(++$counter); - $lines[] = "INDEX ".$this->quoteIdentifier($indexName)." (" .$referencedColumnsHash.")"; - // Add this new index to our collection, otherwise we might add it again (bug #725) - $this->collectIndexedColumns($indexName, $referencedColumns, $_indices); - } - } - } - } - - foreach ($table->getForeignKeys() as $fk) { - - $indexName = $this->quoteIdentifier(substr_replace($fk->getName(), 'FI_', strrpos($fk->getName(), 'FK_'), 3)); - - $localColumns = $fk->getLocalColumns(); - $localColumnsHash = $this->getColumnList($localColumns); - - if (!array_key_exists($localColumnsHash, $_indices)) { - // no matching index defined in the schema, so we have to create one. MySQL needs indices on any columns that serve as foreign keys. these are not auto-created prior to 4.1.2 - $lines[] = "INDEX $indexName (".$localColumnsHash.")"; - $this->collectIndexedColumns($indexName, $localColumns, $_indices); - } - $str = "CONSTRAINT ".$this->quoteIdentifier($fk->getName())." - FOREIGN KEY (".$this->getColumnList($fk->getLocalColumns()).") - REFERENCES ".$this->quoteIdentifier($fk->getForeignTableName()) . " (".$this->getColumnList($fk->getForeignColumns()).")"; - if ($fk->hasOnUpdate()) { - $str .= " - ON UPDATE ".$fk->getOnUpdate(); - } - if ($fk->hasOnDelete()) { - $str .= " - ON DELETE ".$fk->getOnDelete(); - } - $lines[] = $str; - } - } - - /** - * Helper function to collect indexed columns. - * @param array $columns The column names, or objects with a $callback method - * @param array $indexedColumns The collected indexes - * @param string $callback The name of a method to call on each of $columns to get the column name, if needed. - * @return unknown_type - */ - private function collectIndexedColumns($indexName, $columns, &$collectedIndexes, $callback = null) - { - // Get the actual column names, using the callback if needed. - // DDLBuilder::getColumnList tests $col instanceof Column, and no callback - maybe we should too? - $colnames = $columns; - if ($callback) { - $colnames = array(); - foreach ($columns as $col) { - $colnames[] = $col->$callback(); - } - } - - /** - * "If the table has a multiple-column index, any leftmost prefix of the - * index can be used by the optimizer to find rows. For example, if you - * have a three-column index on (col1, col2, col3), you have indexed search - * capabilities on (col1), (col1, col2), and (col1, col2, col3)." - * @link http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html - */ - $indexedColumns = array(); - foreach ($colnames as $colname) { - $indexedColumns[] = $this->quoteIdentifier($colname); - $indexedColumnsHash = implode(',', $indexedColumns); - if (!array_key_exists($indexedColumnsHash, $collectedIndexes)) { - $collectedIndexes[$indexedColumnsHash] = array(); - } - $collectedIndexes[$indexedColumnsHash][] = $indexName; - } - } - - /** - * Checks whether passed-in array of Column objects contains a column with specified name. - * @param array Column[] or string[] - * @param string $searchcol Column name to search for - */ - private function containsColname($columns, $searchcol) - { - foreach ($columns as $col) { - if ($col instanceof Column) { - $col = $col->getName(); - } - if ($col == $searchcol) { - return true; - } - } - return false; - } - - /** - * Not used for MySQL since foreign keys are declared inside table declaration. - * @see addForeignKeysLines() - */ - protected function addForeignKeys(&$script) - { - } - - /** - * Not used for MySQL since indexes are declared inside table declaration. - * @see addIndicesLines() - */ - protected function addIndices(&$script) - { - } - - /** - * Builds the DDL SQL for a Column object. - * @return string - */ - public function getColumnDDL(Column $col) - { - $platform = $this->getPlatform(); - $domain = $col->getDomain(); - $sqlType = $domain->getSqlType(); - $notNullString = $col->getNotNullString(); - $defaultSetting = $col->getDefaultSetting(); - - // Special handling of TIMESTAMP/DATETIME types ... - // See: http://propel.phpdb.org/trac/ticket/538 - if ($sqlType == 'DATETIME') { - $def = $domain->getDefaultValue(); - if ($def && $def->isExpression()) { // DATETIME values can only have constant expressions - $sqlType = 'TIMESTAMP'; - } - } elseif ($sqlType == 'DATE') { - $def = $domain->getDefaultValue(); - if ($def && $def->isExpression()) { - throw new EngineException("DATE columns cannot have default *expressions* in MySQL."); - } - } elseif ($sqlType == 'TEXT' || $sqlType == 'BLOB') { - if ($domain->getDefaultValue()) { - throw new EngineException("BLOB and TEXT columns cannot have DEFAULT values. in MySQL."); - } - } - - $sb = ""; - $sb .= $this->quoteIdentifier($col->getName()) . " "; - $sb .= $sqlType; - if ($platform->hasSize($sqlType)) { - $sb .= $domain->printSize(); - } - $sb .= " "; - - if ($sqlType == 'TIMESTAMP') { - $notNullString = $col->getNotNullString(); - $defaultSetting = $col->getDefaultSetting(); - if ($notNullString == '') { - $notNullString = 'NULL'; - } - if ($defaultSetting == '' && $notNullString == 'NOT NULL') { - $defaultSetting = 'DEFAULT CURRENT_TIMESTAMP'; - } - $sb .= $notNullString . " " . $defaultSetting . " "; - } else { - $sb .= $defaultSetting . " "; - $sb .= $notNullString . " "; - } - $sb .= $col->getAutoIncrementString(); - - return trim($sb); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDataSQLBuilder.php deleted file mode 100644 index 5938b6e64..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/mysql/MysqlDataSQLBuilder.php +++ /dev/null @@ -1,22 +0,0 @@ - - * @package propel.generator.builder.sql.mysql - */ -class MysqlDataSQLBuilder extends DataSQLBuilder -{ - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDDLBuilder.php deleted file mode 100644 index 8503f1834..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDDLBuilder.php +++ /dev/null @@ -1,185 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class OracleDDLBuilder extends DDLBuilder -{ - - /** - * This function adds any _database_ start/initialization SQL. - * This is designed to be called for a database, not a specific table, hence it is static. - * @see parent::getDatabaseStartDDL() - * - * @return string The DDL is returned as astring. - */ - public static function getDatabaseStartDDL() - { - return " -ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'; -ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'; -"; - } - - /** - * - * @see parent::addDropStatement() - */ - protected function addDropStatements(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - $script .= " -DROP TABLE ".$this->quoteIdentifier($table->getName())." CASCADE CONSTRAINTS; -"; - if ($table->getIdMethod() == "native") { - $script .= " -DROP SEQUENCE ".$this->quoteIdentifier($this->getSequenceName())."; -"; - } - } - - /** - * - * @see parent::addColumns() - */ - protected function addTable(&$script) - { - $table = $this->getTable(); - $script .= " - ------------------------------------------------------------------------ --- ".$table->getName()." ------------------------------------------------------------------------ -"; - - $this->addDropStatements($script); - - $script .= " -CREATE TABLE ".$this->quoteIdentifier($table->getName())." -( - "; - - $lines = array(); - - foreach ($table->getColumns() as $col) { - $lines[] = $this->getColumnDDL($col); - } - - $sep = ", - "; - $script .= implode($sep, $lines); - $script .= " -); -"; - $this->addPrimaryKey($script); - $this->addSequences($script); - - } - - /** - * - * - */ - protected function addPrimaryKey(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - $tableName = $table->getName(); - $length = strlen($tableName); - if ($length > 27) { - $length = 27; - } - if ( is_array($table->getPrimaryKey()) && count($table->getPrimaryKey()) ) { - $script .= " -ALTER TABLE ".$this->quoteIdentifier($table->getName())." - ADD CONSTRAINT ".$this->quoteIdentifier(substr($tableName,0,$length)."_PK")." - PRIMARY KEY ("; - $delim = ""; - foreach ($table->getPrimaryKey() as $col) { - $script .= $delim . $this->quoteIdentifier($col->getName()); - $delim = ","; - } - $script .= "); -"; - } - } - - /** - * Adds CREATE SEQUENCE statements for this table. - * - */ - protected function addSequences(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - if ($table->getIdMethod() == "native") { - $script .= " -CREATE SEQUENCE ".$this->quoteIdentifier($this->getSequenceName())." - INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER; -"; - } - } - - - /** - * Adds CREATE INDEX statements for this table. - * @see parent::addIndices() - */ - protected function addIndices(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - foreach ($table->getIndices() as $index) { - $script .= " -CREATE "; - if ($index->getIsUnique()) { - $script .= "UNIQUE"; - } - $script .= "INDEX ".$this->quoteIdentifier($index->getName()) ." ON ".$this->quoteIdentifier($table->getName())." (".$this->getColumnList($index->getColumns())."); -"; - } - } - - /** - * - * @see parent::addForeignKeys() - */ - protected function addForeignKeys(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - foreach ($table->getForeignKeys() as $fk) { - $script .= " -ALTER TABLE ".$this->quoteIdentifier($table->getName())." - ADD CONSTRAINT ".$this->quoteIdentifier($fk->getName())." - FOREIGN KEY (".$this->getColumnList($fk->getLocalColumns()) .") REFERENCES ".$this->quoteIdentifier($fk->getForeignTableName())." (".$this->getColumnList($fk->getForeignColumns()).")"; - if ($fk->hasOnUpdate()) { - $this->warn("ON UPDATE not yet implemented for Oracle builder.(ignoring for ".$this->getColumnList($fk->getLocalColumns())." fk)."); - //$script .= " ON UPDATE ".$fk->getOnUpdate(); - } - if ($fk->hasOnDelete()) { - $script .= " - ON DELETE ".$fk->getOnDelete(); - } - $script .= "; -"; - } - } - - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php deleted file mode 100644 index bf7a35dae..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php +++ /dev/null @@ -1,22 +0,0 @@ - - * @package propel.generator.builder.sql.oracle - */ -class OracleDataSQLBuilder extends DataSQLBuilder -{ - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDDLBuilder.php deleted file mode 100644 index 92e0185d1..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDDLBuilder.php +++ /dev/null @@ -1,304 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class PgsqlDDLBuilder extends DDLBuilder -{ - - /** - * Array that keeps track of already - * added schema names - * - * @var Array of schema names - */ - protected static $addedSchemas = array(); - - /** - * Queue of constraint SQL that will be added to script at the end. - * - * PostgreSQL seems (now?) to not like constraints for tables that don't exist, - * so the solution is to queue up the statements and execute it at the end. - * - * @var array - */ - protected static $queuedConstraints = array(); - - /** - * Reset static vars between db iterations. - */ - public static function reset() - { - self::$addedSchemas = array(); - self::$queuedConstraints = array(); - } - - /** - * Returns all the ALTER TABLE ADD CONSTRAINT lines for inclusion at end of file. - * @return string DDL - */ - public static function getDatabaseEndDDL() - { - $ddl = implode("", self::$queuedConstraints); - return $ddl; - } - - /** - * Get the schema for the current table - * - * @author Markus Lervik - * @access protected - * @return schema name if table has one, else - * null - **/ - protected function getSchema() - { - $table = $this->getTable(); - $vi = $table->getVendorInfoForType($this->getPlatform()->getDatabaseType()); - if ($vi->hasParameter('schema')) { - return $vi->getParameter('schema'); - } - return null; - } - - /** - * Add a schema to the generated SQL script - * - * @author Markus Lervik - * @access protected - * @return string with CREATE SCHEMA statement if - * applicable, else empty string - **/ - protected function addSchema() - { - - $schemaName = $this->getSchema(); - - if ($schemaName !== null) { - - if (!in_array($schemaName, self::$addedSchemas)) { - $platform = $this->getPlatform(); - self::$addedSchemas[] = $schemaName; - return "\nCREATE SCHEMA " . $this->quoteIdentifier($schemaName) . ";\n"; - } - } - - return ''; - - } - - /** - * - * @see parent::addDropStatement() - */ - protected function addDropStatements(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " -DROP TABLE ".$this->quoteIdentifier($table->getName())." CASCADE; -"; - - if ($table->getIdMethod() == IDMethod::NATIVE && $table->getIdMethodParameters()) { - $script .= " -DROP SEQUENCE ".$this->quoteIdentifier(strtolower($this->getSequenceName()))."; -"; - } - } - - /** - * - * @see parent::addColumns() - */ - protected function addTable(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " ------------------------------------------------------------------------------ --- ".$table->getName()." ------------------------------------------------------------------------------ -"; - - $script .= $this->addSchema(); - - $schemaName = $this->getSchema(); - if ($schemaName !== null) { - $script .= "\nSET search_path TO " . $this->quoteIdentifier($schemaName) . ";\n"; - } - - $this->addDropStatements($script); - $this->addSequences($script); - - $script .= " - -CREATE TABLE ".$this->quoteIdentifier($table->getName())." -( - "; - - $lines = array(); - - foreach ($table->getColumns() as $col) { - /* @var $col Column */ - $colDDL = $this->getColumnDDL($col); - if ($col->isAutoIncrement() && $table->getIdMethodParameters() == null) { - if ($col->getType() === PropelTypes::BIGINT) { - $colDDL = str_replace($col->getDomain()->getSqlType(), 'bigserial', $colDDL); - } else { - $colDDL = str_replace($col->getDomain()->getSqlType(), 'serial', $colDDL); - } - } - $lines[] = $colDDL; - } - - if ($table->hasPrimaryKey()) { - $lines[] = "PRIMARY KEY (".$this->getColumnList($table->getPrimaryKey()).")"; - } - - foreach ($table->getUnices() as $unique ) { - $lines[] = "CONSTRAINT ".$this->quoteIdentifier($unique->getName())." UNIQUE (".$this->getColumnList($unique->getColumns()).")"; - } - - $sep = ", - "; - $script .= implode($sep, $lines); - $script .= " -); - -COMMENT ON TABLE ".$this->quoteIdentifier($table->getName())." IS " . $platform->quote($table->getDescription())."; - -"; - - $this->addColumnComments($script); - - $script .= "\nSET search_path TO public;"; - - } - - /** - * Adds comments for the columns. - * - */ - protected function addColumnComments(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($this->getTable()->getColumns() as $col) { - if ( $col->getDescription() != '' ) { - $script .= " -COMMENT ON COLUMN ".$this->quoteIdentifier($table->getName()).".".$this->quoteIdentifier($col->getName())." IS ".$platform->quote($col->getDescription()) ."; -"; - } - } - } - - /** - * Override to provide sequence names that conform to postgres' standard when - * no id-method-parameter specified. - * - * @see DataModelBuilder::getSequenceName() - * @return string - */ - public function getSequenceName() - { - $table = $this->getTable(); - static $longNamesMap = array(); - $result = null; - if ($table->getIdMethod() == IDMethod::NATIVE) { - $idMethodParams = $table->getIdMethodParameters(); - if (empty($idMethodParams)) { - $result = null; - // We're going to ignore a check for max length (mainly - // because I'm not sure how Postgres would handle this w/ SERIAL anyway) - foreach ($table->getColumns() as $col) { - if ($col->isAutoIncrement()) { - $result = $table->getName() . '_' . $col->getName() . '_seq'; - break; // there's only one auto-increment column allowed - } - } - } else { - $result = $idMethodParams[0]->getValue(); - } - } - return $result; - } - - /** - * Adds CREATE SEQUENCE statements for this table. - * - */ - protected function addSequences(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - if ($table->getIdMethod() == IDMethod::NATIVE && $table->getIdMethodParameters() != null) { - $script .= " -CREATE SEQUENCE ".$this->quoteIdentifier(strtolower($this->getSequenceName()))."; -"; - } - } - - - /** - * Adds CREATE INDEX statements for this table. - * @see parent::addIndices() - */ - protected function addIndices(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getIndices() as $index) { - $script .= " -CREATE "; - if ($index->getIsUnique()) { - $script .= "UNIQUE"; - } - $script .= "INDEX ".$this->quoteIdentifier($index->getName())." ON ".$this->quoteIdentifier($table->getName())." (".$this->getColumnList($index->getColumns())."); -"; - } - } - - /** - * - * @see parent::addForeignKeys() - */ - protected function addForeignKeys(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getForeignKeys() as $fk) { - $privscript = " -ALTER TABLE ".$this->quoteIdentifier($table->getName())." ADD CONSTRAINT ".$this->quoteIdentifier($fk->getName())." FOREIGN KEY (".$this->getColumnList($fk->getLocalColumns()) .") REFERENCES ".$this->quoteIdentifier($fk->getForeignTableName())." (".$this->getColumnList($fk->getForeignColumns()).")"; - if ($fk->hasOnUpdate()) { - $privscript .= " ON UPDATE ".$fk->getOnUpdate(); - } - if ($fk->hasOnDelete()) { - $privscript .= " ON DELETE ".$fk->getOnDelete(); - } - $privscript .= "; -"; - self::$queuedConstraints[] = $privscript; - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php deleted file mode 100644 index c5a644bba..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php +++ /dev/null @@ -1,102 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class PgsqlDataSQLBuilder extends DataSQLBuilder -{ - - /** - * The largets serial value encountered this far. - * - * @var int - */ - private $maxSeqVal; - - /** - * Construct a new PgsqlDataSQLBuilder object. - * - * @param Table $table - */ - public function __construct(Table $table) - { - parent::__construct($table); - } - - /** - * The main method in this class, returns the SQL for INSERTing data into a row. - * @param DataRow $row The row to process. - * @return string - */ - public function buildRowSql(DataRow $row) - { - $sql = parent::buildRowSql($row); - - $table = $this->getTable(); - - if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) { - foreach ($row->getColumnValues() as $colValue) { - if ($colValue->getColumn()->isAutoIncrement()) { - if ($colValue->getValue() > $this->maxSeqVal) { - $this->maxSeqVal = $colValue->getValue(); - } - } - } - } - - return $sql; - } - - public function getTableEndSql() - { - $table = $this->getTable(); - $sql = ""; - if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) { - $seqname = $this->getDDLBuilder()->getSequenceName(); - $sql .= "SELECT pg_catalog.setval('$seqname', ".((int)$this->maxSeqVal)."); -"; - } - return $sql; - } - - /** - * Get SQL value to insert for Postgres BOOLEAN column. - * @param boolean $value - * @return string The representation of boolean for Postgres ('t' or 'f'). - */ - protected function getBooleanSql($value) - { - if ($value === 'f' || $value === 'false' || $value === "0") { - $value = false; - } - return ($value ? "'t'" : "'f'"); - } - - /** - * - * @param mixed $blob Blob object or string containing data. - * @return string - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - $blob = $blob->__toString(); - } - return "'" . pg_escape_bytea($blob) . "'"; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDDLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDDLBuilder.php deleted file mode 100644 index 3a2c3c041..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDDLBuilder.php +++ /dev/null @@ -1,119 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class SqliteDDLBuilder extends DDLBuilder -{ - - /** - * - * @see parent::addDropStatement() - */ - protected function addDropStatements(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " -DROP TABLE ".$this->quoteIdentifier($table->getName())."; -"; - } - - /** - * - * @see parent::addColumns() - */ - protected function addTable(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - $script .= " ------------------------------------------------------------------------------ --- ".$table->getName()." ------------------------------------------------------------------------------ -"; - - $this->addDropStatements($script); - - $script .= " - -CREATE TABLE ".$this->quoteIdentifier($table->getName())." -( - "; - - $lines = array(); - - foreach ($table->getColumns() as $col) { - $lines[] = $this->getColumnDDL($col); - } - - if ($table->hasPrimaryKey() && count($table->getPrimaryKey()) > 1) { - $lines[] = "PRIMARY KEY (".$this->getColumnList($table->getPrimaryKey()).")"; - } - - foreach ($table->getUnices() as $unique ) { - $lines[] = "UNIQUE (".$this->getColumnList($unique->getColumns()).")"; - } - - $sep = ", - "; - $script .= implode($sep, $lines); - $script .= " -); -"; - } - - /** - * Adds CREATE INDEX statements for this table. - * @see parent::addIndices() - */ - protected function addIndices(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getIndices() as $index) { - $script .= " -CREATE "; - if ($index->getIsUnique()) { - $script .= "UNIQUE"; - } - $script .= "INDEX ".$this->quoteIdentifier($index->getName())." ON ".$this->quoteIdentifier($table->getName())." (".$this->getColumnList($index->getColumns())."); -"; - } - } - - /** - * - * @see parent::addForeignKeys() - */ - protected function addForeignKeys(&$script) - { - $table = $this->getTable(); - $platform = $this->getPlatform(); - - foreach ($table->getForeignKeys() as $fk) { - $script .= " --- SQLite does not support foreign keys; this is just for reference --- FOREIGN KEY (".$this->getColumnList($fk->getLocalColumns()).") REFERENCES ".$fk->getForeignTableName()." (".$this->getColumnList($fk->getForeignColumns()).") -"; - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDataSQLBuilder.php b/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDataSQLBuilder.php deleted file mode 100644 index 7f266afb4..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/sql/sqlite/SqliteDataSQLBuilder.php +++ /dev/null @@ -1,36 +0,0 @@ - - * @package propel.generator.builder.sql.sqlite - */ -class SqliteDataSQLBuilder extends DataSQLBuilder -{ - - /** - * Returns string processed by sqlite_udf_encode_binary() to ensure that binary contents will be handled correctly by sqlite. - * @param mixed $blob Blob or string - * @return string encoded text - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - $blob = $blob->__toString(); - } - return "'" . sqlite_udf_encode_binary($blob) . "'"; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/util/DefaultEnglishPluralizer.php b/airtime_mvc/library/propel/generator/lib/builder/util/DefaultEnglishPluralizer.php deleted file mode 100644 index 7d0fad699..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/util/DefaultEnglishPluralizer.php +++ /dev/null @@ -1,33 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.builder.util - */ -class DefaultEnglishPluralizer implements Pluralizer -{ - - /** - * Generate a plural name based on the passed in root. - * @param string $root The root that needs to be pluralized (e.g. Author) - * @return string The plural form of $root (e.g. Authors). - */ - public function getPluralForm($root) - { - return $root . 's'; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/util/Pluralizer.php b/airtime_mvc/library/propel/generator/lib/builder/util/Pluralizer.php deleted file mode 100644 index 9f382718a..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/util/Pluralizer.php +++ /dev/null @@ -1,28 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.builder.util - */ -interface Pluralizer -{ - - /** - * Generate a plural name based on the passed in root. - * @param string $root The root that needs to be pluralized (e.g. Author) - * @return string The plural form of $root. - */ - public function getPluralForm($root); - -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/util/PropelStringReader.php b/airtime_mvc/library/propel/generator/lib/builder/util/PropelStringReader.php deleted file mode 100644 index fb9fd0992..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/util/PropelStringReader.php +++ /dev/null @@ -1,91 +0,0 @@ -_string = $string; - } - - public function skip($n) - { - $this->currPos = $this->currPos + $n; - } - - public function eof() - { - return $this->currPos == strlen($this->_string); - } - - public function read($len = null) - { - if ($len === null) { - return $this->_string; - } else { - if ($this->currPos >= strlen($this->_string)) { - return -1; - } - $out = substr($this->_string, $this->currPos, $len); - $this->currPos += $len; - return $out; - } - } - - public function mark() - { - $this->mark = $this->currPos; - } - - public function reset() - { - $this->currPos = $this->mark; - } - - public function close() {} - - public function open() {} - - public function ready() {} - - public function markSupported() - { - return true; - } - - public function getResource() - { - return '(string) "'.$this->_string . '"'; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/lib/builder/util/PropelTemplate.php b/airtime_mvc/library/propel/generator/lib/builder/util/PropelTemplate.php deleted file mode 100644 index dd8f937a4..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/util/PropelTemplate.php +++ /dev/null @@ -1,92 +0,0 @@ - - * $template->setTemplate('This is '); - * - * - * @param string $template the template string - */ - public function setTemplate($template) - { - $this->template = $template; - } - - /** - * Set a file as a template. The file can be any regular PHP file. - * - * - * $template->setTemplateFile(dirname(__FILE__) . '/template/foo.php'); - * - * - * @param string $filePath The (absolute or relative to the include path) file path - */ - public function setTemplateFile($filePath) - { - $this->templateFile = $filePath; - } - - /** - * Render the template using the variable provided as arguments. - * - * - * $template = new PropelTemplate(); - * $template->setTemplate('This is '); - * echo $template->render(array('name' => 'Mike')); - * // This is Mike - * - * - * @param array $vars An associative array of argumens to be rendered - * - * @return string The rendered template - */ - public function render($vars = array()) - { - if (null === $this->templateFile && null === $this->template) { - throw new InvalidArgumentException('You must set a template or a template file before rendering'); - } - - extract($vars); - ob_start(); - ob_implicit_flush(0); - - try - { - if (null !== $this->templateFile) { - require($this->templateFile); - } else { - eval('?>' . $this->template . ' (Propel) - * @author Leon Messerschmidt (Torque) - * @author Jason van Zyl (Torque) - * @author Martin Poeschl (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1764 $ - * @package propel.generator.builder.util - */ -class XmlToAppData extends AbstractHandler -{ - - /** enables debug output */ - const DEBUG = false; - - private $app; - private $platform; - private $currDB; - private $currTable; - private $currColumn; - private $currFK; - private $currIndex; - private $currUnique; - private $currValidator; - private $currBehavior; - private $currVendorObject; - - private $isForReferenceOnly; - private $currentPackage; - private $currentXmlFile; - private $defaultPackage; - - private $encoding; - - /** two-dimensional array, - first dimension is for schemas(key is the path to the schema file), - second is for tags within the schema */ - private $schemasTagsStack = array(); - - public $parser; - - /** - * Creates a new instance for the specified database type. - * - * @param Platform $platform The type of database for the application. - * @param string $defaultPackage the default PHP package used for the om - * @param string $encoding The database encoding. - */ - public function __construct(Platform $platform, $defaultPackage, $encoding = 'iso-8859-1') - { - $this->app = new AppData($platform); - $this->platform = $platform; - $this->defaultPackage = $defaultPackage; - $this->firstPass = true; - $this->encoding = $encoding; - } - - /** - * Parses a XML input file and returns a newly created and - * populated AppData structure. - * - * @param string $xmlFile The input file to parse. - * @return AppData populated by xmlFile. - */ - public function parseFile($xmlFile) - { - // we don't want infinite recursion - if ($this->isAlreadyParsed($xmlFile)) { - return; - } - - $f = new PhingFile($xmlFile); - - return $this->parseString($f->contents(), $xmlFile); - } - - /** - * Parses a XML input string and returns a newly created and - * populated AppData structure. - * - * @param string $xmlString The input string to parse. - * @param string $xmlFile The input file name. - * @return AppData populated by xmlFile. - */ - public function parseString($xmlString, $xmlFile) - { - // we don't want infinite recursion - if ($this->isAlreadyParsed($xmlFile)) { - return; - } - - // store current schema file path - $this->schemasTagsStack[$xmlFile] = array(); - - $this->currentXmlFile = $xmlFile; - - try { - $sr = new PropelStringReader($xmlString); - - } catch (Exception $e) { - $f = new PhingFile($xmlFile); - throw new Exception("XML File not found: " . $f->getAbsolutePath()); - } - - $br = new BufferedReader($sr); - - $this->parser = new ExpatParser($br); - $this->parser->parserSetOption(XML_OPTION_CASE_FOLDING, 0); - $this->parser->setHandler($this); - - try { - $this->parser->parse(); - } catch (Exception $e) { - $br->close(); - throw $e; - } - $br->close(); - - array_pop($this->schemasTagsStack); - - return $this->app; - } - - /** - * Handles opening elements of the xml file. - * - * @param string $uri - * @param string $localName The local name (without prefix), or the empty string if - * Namespace processing is not being performed. - * @param string $rawName The qualified name (with prefix), or the empty string if - * qualified names are not available. - * @param string $attributes The specified or defaulted attributes - */ - public function startElement($name, $attributes) { - - try { - - $parentTag = $this->peekCurrentSchemaTag(); - - if ($parentTag === false) { - - switch($name) { - case "database": - if ($this->isExternalSchema()) { - $this->currentPackage = @$attributes["package"]; - if ($this->currentPackage === null) { - $this->currentPackage = $this->defaultPackage; - } - } else { - $this->currDB = $this->app->addDatabase($attributes); - } - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "database") { - - switch($name) { - - case "external-schema": - $xmlFile = @$attributes["filename"]; - - //"referenceOnly" attribute is valid in the main schema XML file only, - //and it's ingnored in the nested external-schemas - if (!$this->isExternalSchema()) { - $isForRefOnly = @$attributes["referenceOnly"]; - $this->isForReferenceOnly = ($isForRefOnly !== null ? (strtolower($isForRefOnly) === "true") : true); // defaults to TRUE - } - - if ($xmlFile{0} != '/') { - $f = new PhingFile($this->currentXmlFile); - $xf = new PhingFile($f->getParent(), $xmlFile); - $xmlFile = $xf->getPath(); - } - - $this->parseFile($xmlFile); - break; - - case "domain": - $this->currDB->addDomain($attributes); - break; - - case "table": - $this->currTable = $this->currDB->addTable($attributes); - if ($this->isExternalSchema()) { - $this->currTable->setForReferenceOnly($this->isForReferenceOnly); - $this->currTable->setPackage($this->currentPackage); - } - break; - - case "vendor": - $this->currVendorObject = $this->currDB->addVendorInfo($attributes); - break; - - case "behavior": - $this->currBehavior = $this->currDB->addBehavior($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "table") { - - switch($name) { - case "column": - $this->currColumn = $this->currTable->addColumn($attributes); - break; - - case "foreign-key": - $this->currFK = $this->currTable->addForeignKey($attributes); - break; - - case "index": - $this->currIndex = $this->currTable->addIndex($attributes); - break; - - case "unique": - $this->currUnique = $this->currTable->addUnique($attributes); - break; - - case "vendor": - $this->currVendorObject = $this->currTable->addVendorInfo($attributes); - break; - - case "validator": - $this->currValidator = $this->currTable->addValidator($attributes); - break; - - case "id-method-parameter": - $this->currTable->addIdMethodParameter($attributes); - break; - - case "behavior": - $this->currBehavior = $this->currTable->addBehavior($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "column") { - - switch($name) { - case "inheritance": - $this->currColumn->addInheritance($attributes); - break; - - case "vendor": - $this->currVendorObject = $this->currColumn->addVendorInfo($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "foreign-key") { - - switch($name) { - case "reference": - $this->currFK->addReference($attributes); - break; - - case "vendor": - $this->currVendorObject = $this->currUnique->addVendorInfo($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "index") { - - switch($name) { - case "index-column": - $this->currIndex->addColumn($attributes); - break; - - case "vendor": - $this->currVendorObject = $this->currIndex->addVendorInfo($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - - } elseif ($parentTag == "unique") { - - switch($name) { - case "unique-column": - $this->currUnique->addColumn($attributes); - break; - - case "vendor": - $this->currVendorObject = $this->currUnique->addVendorInfo($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - } elseif ($parentTag == "behavior") { - - switch($name) { - case "parameter": - $this->currBehavior->addParameter($attributes); - break; - - default: - $this->_throwInvalidTagException($name); - } - } elseif ($parentTag == "validator") { - switch($name) { - case "rule": - $this->currValidator->addRule($attributes); - break; - default: - $this->_throwInvalidTagException($name); - } - } elseif ($parentTag == "vendor") { - - switch($name) { - case "parameter": - $this->currVendorObject->addParameter($attributes); - break; - default: - $this->_throwInvalidTagException($name); - } - - } else { - // it must be an invalid tag - $this->_throwInvalidTagException($name); - } - - $this->pushCurrentSchemaTag($name); - - } catch (BuildException $e) { - throw $e; - } catch (Exception $e) { - echo $e; - echo "\n"; - throw $e; - } - } - - function _throwInvalidTagException($tag_name) - { - throw new BuildException("Unexpected tag <" . $tag_name . ">", $this->parser->getLocation()); - } - - /** - * Handles closing elements of the xml file. - * - * @param uri - * @param localName The local name (without prefix), or the empty string if - * Namespace processing is not being performed. - * @param rawName The qualified name (with prefix), or the empty string if - * qualified names are not available. - */ - public function endElement($name) - { - if (self::DEBUG) { - print("endElement(" . $name . ") called\n"); - } - - $this->popCurrentSchemaTag(); - } - - protected function peekCurrentSchemaTag() - { - $keys = array_keys($this->schemasTagsStack); - return end($this->schemasTagsStack[end($keys)]); - } - - protected function popCurrentSchemaTag() - { - $keys = array_keys($this->schemasTagsStack); - array_pop($this->schemasTagsStack[end($keys)]); - } - - protected function pushCurrentSchemaTag($tag) - { - $keys = array_keys($this->schemasTagsStack); - $this->schemasTagsStack[end($keys)][] = $tag; - } - - protected function isExternalSchema() - { - return count($this->schemasTagsStack) > 1; - } - - protected function isAlreadyParsed($filePath) - { - return isset($this->schemasTagsStack[$filePath]); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/builder/util/XmlToDataSQL.php b/airtime_mvc/library/propel/generator/lib/builder/util/XmlToDataSQL.php deleted file mode 100644 index 09854080e..000000000 --- a/airtime_mvc/library/propel/generator/lib/builder/util/XmlToDataSQL.php +++ /dev/null @@ -1,265 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.generator.builder.util - */ -class XmlToDataSQL extends AbstractHandler -{ - - /** - * The GeneratorConfig associated with the build. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * The database. - * - * @var Database - */ - private $database; - - /** - * The output writer for the SQL file. - * - * @var Writer - */ - private $sqlWriter; - - /** - * The database (and output SQL file) encoding. - * - * Values will be converted to this encoding in the output file. - * - * @var string - */ - private $encoding; - - /** - * The classname of the static class that will perform the building. - * - * This is needed because there are some pre/post methods that get called - * on the static class. - * - * @var string - */ - private $builderClazz; - - /** - * The name of the current table being processed. - * - * @var string - */ - private $currTableName; - - /** - * The DataSQLBuilder for the current table. - * - * @var DataSQLBuilder - */ - private $currBuilder; - - /** - * Expat Parser. - * - * @var ExpatParser - */ - public $parser; - - /** - * Flag for enabing debug output to aid in parser tracing. - */ - const DEBUG = false; - - /** - * Construct new XmlToDataSQL class. - * - * This class is passed the Database object so that it knows what to expect from - * the XML file. - * - * @param Database $database - * @param GeneratorConfig $config - * @param string $encoding Database encoding - */ - public function __construct(Database $database, GeneratorConfig $config, $encoding = 'iso-8859-1') - { - $this->database = $database; - $this->generatorConfig = $config; - $this->encoding = $encoding; - } - - /** - * Transform the data dump input file into SQL and writes it to the output stream. - * - * @param PhingFile $xmlFile - * @param Writer $out - */ - public function transform(PhingFile $xmlFile, Writer $out) - { - $this->sqlWriter = $out; - - // Reset some vars just in case this is being run multiple times. - $this->currTableName = $this->currBuilder = null; - - $this->builderClazz = $this->generatorConfig->getBuilderClassname('datasql'); - - try { - $fr = new FileReader($xmlFile); - } catch (Exception $e) { - throw new BuildException("XML File not found: " . $xmlFile->getAbsolutePath()); - } - - $br = new BufferedReader($fr); - - $this->parser = new ExpatParser($br); - $this->parser->parserSetOption(XML_OPTION_CASE_FOLDING, 0); - $this->parser->setHandler($this); - - try { - $this->parser->parse(); - } catch (Exception $e) { - print $e->getMessage() . "\n"; - $br->close(); - } - $br->close(); - } - - /** - * Handles opening elements of the xml file. - */ - public function startElement($name, $attributes) - { - try { - if ($name == "dataset") { - // Clear any start/end DLL - call_user_func(array($this->builderClazz, 'reset')); - $this->sqlWriter->write(call_user_func(array($this->builderClazz, 'getDatabaseStartSql'))); - } else { - - // we're processing a row of data - // where tag name is phpName e.g. - - $table = $this->database->getTableByPhpName($name); - - $columnValues = array(); - foreach ($attributes as $name => $value) { - $col = $table->getColumnByPhpName($name); - $columnValues[] = new ColumnValue($col, iconv('utf-8',$this->encoding, $value)); - } - - $data = new DataRow($table, $columnValues); - - if ($this->currTableName !== $table->getName()) { - // new table encountered - - if ($this->currBuilder !== null) { - $this->sqlWriter->write($this->currBuilder->getTableEndSql()); - } - - $this->currTableName = $table->getName(); - $this->currBuilder = $this->generatorConfig->getConfiguredBuilder($table, 'datasql'); - - $this->sqlWriter->write($this->currBuilder->getTableStartSql()); - } - - // Write the SQL - $this->sqlWriter->write($this->currBuilder->buildRowSql($data)); - - } - - } catch (Exception $e) { - // Exceptions have traditionally not bubbled up nicely from the expat parser, - // so we also print the stack trace here. - print $e; - throw $e; - } - } - - - /** - * Handles closing elements of the xml file. - * - * @param $name The local name (without prefix), or the empty string if - * Namespace processing is not being performed. - */ - public function endElement($name) - { - if (self::DEBUG) { - print("endElement(" . $name . ") called\n"); - } - if ($name == "dataset") { - if ($this->currBuilder !== null) { - $this->sqlWriter->write($this->currBuilder->getTableEndSql()); - } - $this->sqlWriter->write(call_user_func(array($this->builderClazz, 'getDatabaseEndSql'))); - } - } - -} // XmlToData - -/** - * "inner class" - * @package propel.generator.builder.util - */ -class DataRow -{ - private $table; - private $columnValues; - - public function __construct(Table $table, $columnValues) - { - $this->table = $table; - $this->columnValues = $columnValues; - } - - public function getTable() - { - return $this->table; - } - - public function getColumnValues() - { - return $this->columnValues; - } -} - -/** - * "inner" class - * @package propel.generator.builder.util - */ -class ColumnValue { - - private $col; - private $val; - - public function __construct(Column $col, $val) - { - $this->col = $col; - $this->val = $val; - } - - public function getColumn() - { - return $this->col; - } - - public function getValue() - { - return $this->val; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/config/GeneratorConfig.php b/airtime_mvc/library/propel/generator/lib/config/GeneratorConfig.php deleted file mode 100644 index 119007910..000000000 --- a/airtime_mvc/library/propel/generator/lib/config/GeneratorConfig.php +++ /dev/null @@ -1,217 +0,0 @@ - - * @package propel.generator.config - */ -class GeneratorConfig { - - /** - * The build properties. - * - * @var array - */ - private $buildProperties = array(); - - /** - * Construct a new GeneratorConfig. - * @param mixed $props Array or Iterator - */ - public function __construct($props = null) - { - if ($props) $this->setBuildProperties($props); - } - - /** - * Gets the build properties. - * @return array - */ - public function getBuildProperties() - { - return $this->buildProperties; - } - - /** - * Parses the passed-in properties, renaming and saving eligible properties in this object. - * - * Renames the propel.xxx properties to just xxx and renames any xxx.yyy properties - * to xxxYyy as PHP doesn't like the xxx.yyy syntax. - * - * @param mixed $props Array or Iterator - */ - public function setBuildProperties($props) - { - $this->buildProperties = array(); - - $renamedPropelProps = array(); - foreach ($props as $key => $propValue) { - if (strpos($key, "propel.") === 0) { - $newKey = substr($key, strlen("propel.")); - $j = strpos($newKey, '.'); - while ($j !== false) { - $newKey = substr($newKey, 0, $j) . ucfirst(substr($newKey, $j + 1)); - $j = strpos($newKey, '.'); - } - $this->setBuildProperty($newKey, $propValue); - } - } - } - - /** - * Gets a specific propel (renamed) property from the build. - * - * @param string $name - * @return mixed - */ - public function getBuildProperty($name) - { - return isset($this->buildProperties[$name]) ? $this->buildProperties[$name] : null; - } - - /** - * Sets a specific propel (renamed) property from the build. - * - * @param string $name - * @param mixed $value - */ - public function setBuildProperty($name, $value) - { - $this->buildProperties[$name] = $value; - } - - /** - * Resolves and returns the class name based on the specified property value. - * - * @param string $propname The name of the property that holds the class path (dot-path notation). - * @return string The class name. - * @throws BuildException If the classname cannot be determined or class cannot be loaded. - */ - public function getClassname($propname) - { - $classpath = $this->getBuildProperty($propname); - if (empty($classpath)) { - throw new BuildException("Unable to find class path for '$propname' property."); - } - - // This is a slight hack to workaround camel case inconsistencies for the DDL classes. - // Basically, we want to turn ?.?.?.sqliteDDLBuilder into ?.?.?.SqliteDDLBuilder - $lastdotpos = strrpos($classpath, '.'); - if ($lastdotpos !== null) { - $classpath{$lastdotpos+1} = strtoupper($classpath{$lastdotpos+1}); - } else { - $classpath = ucfirst($classpath); - } - - if (empty($classpath)) { - throw new BuildException("Unable to find class path for '$propname' property."); - } - - $clazz = Phing::import($classpath); - - return $clazz; - } - - /** - * Resolves and returns the builder class name. - * - * @param string $type - * @return string The class name. - */ - public function getBuilderClassname($type) - { - $propname = 'builder' . ucfirst(strtolower($type)) . 'Class'; - return $this->getClassname($propname); - } - - /** - * Creates and configures a new Platform class. - * - * @param PDO $con - * @return Platform - */ - public function getConfiguredPlatform(PDO $con = null) - { - $clazz = $this->getClassname("platformClass"); - $platform = new $clazz(); - - if (!$platform instanceof Platform) { - throw new BuildException("Specified platform class ($clazz) does not implement Platform interface.", $this->getLocation()); - } - - $platform->setConnection($con); - $platform->setGeneratorConfig($this); - return $platform; - } - - /** - * Creates and configures a new SchemaParser class for specified platform. - * @param PDO $con - * @return SchemaParser - */ - public function getConfiguredSchemaParser(PDO $con = null) - { - $clazz = $this->getClassname("reverseParserClass"); - $parser = new $clazz(); - if (!$parser instanceof SchemaParser) { - throw new BuildException("Specified platform class ($clazz) does implement SchemaParser interface.", $this->getLocation()); - } - $parser->setConnection($con); - $parser->setGeneratorConfig($this); - return $parser; - } - - /** - * Gets a configured data model builder class for specified table and based on type. - * - * @param Table $table - * @param string $type The type of builder ('ddl', 'sql', etc.) - * @return DataModelBuilder - */ - public function getConfiguredBuilder(Table $table, $type, $cache = true) - { - $classname = $this->getBuilderClassname($type); - $builder = new $classname($table); - $builder->setGeneratorConfig($this); - return $builder; - } - - /** - * Gets a configured Pluralizer class. - * - * @return Pluralizer - */ - public function getConfiguredPluralizer() - { - $classname = $this->getBuilderClassname('pluralizer'); - $pluralizer = new $classname(); - return $pluralizer; - } - - /** - * Gets a configured behavior class - * - * @param string $name a behavior name - * @return string a behavior class name - */ - public function getConfiguredBehavior($name) - { - $propname = 'behavior' . ucfirst(strtolower($name)) . 'Class'; - try { - $ret = $this->getClassname($propname); - } catch (BuildException $e) { - // class path not configured - $ret = false; - } - return $ret; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/exception/EngineException.php b/airtime_mvc/library/propel/generator/lib/exception/EngineException.php deleted file mode 100644 index e296c6bbc..000000000 --- a/airtime_mvc/library/propel/generator/lib/exception/EngineException.php +++ /dev/null @@ -1,22 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @author Jason van Zyl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.exception - */ -class EngineException extends BuildException {} diff --git a/airtime_mvc/library/propel/generator/lib/model/AppData.php b/airtime_mvc/library/propel/generator/lib/model/AppData.php deleted file mode 100644 index 39bb749d0..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/AppData.php +++ /dev/null @@ -1,222 +0,0 @@ - (Propel) - * @author Leon Messerschmidt (Torque) - * @author John McNally (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1640 $ - * @package propel.generator.model - */ -class AppData -{ - - /** - * The list of databases for this application. - * @var array Database[] - */ - private $dbList = array(); - - /** - * The platform class for our database(s). - * @var string - */ - private $platform; - - /** - * Name of the database. Only one database definition - * is allowed in one XML descriptor. - */ - private $name; - - /** - * Flag to ensure that initialization is performed only once. - * @var boolean - */ - private $isInitialized = false; - - /** - * Creates a new instance for the specified database type. - * - * @param Platform $platform The platform object to use for any databases added to this application model. - */ - public function __construct(Platform $platform) - { - $this->platform = $platform; - } - - /** - * Gets the platform object to use for any databases added to this application model. - * - * @return Platform - */ - public function getPlatform() - { - return $this->platform; - } - - /** - * Set the name of the database. - * - * @param name of the database. - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get the name of the database. - * - * @return String name - */ - public function getName() - { - return $this->name; - } - - /** - * Get the short name of the database (without the '-schema' postfix). - * - * @return String name - */ - public function getShortName() - { - return str_replace("-schema", "", $this->name); - } - - /** - * Return an array of all databases - * - * @return Array of Database objects - */ - public function getDatabases($doFinalInit = true) - { - // this is temporary until we'll have a clean solution - // for packaging datamodels/requiring schemas - if ($doFinalInit) { - $this->doFinalInitialization(); - } - return $this->dbList; - } - - /** - * Returns whether this application has multiple databases. - * - * @return boolean True if the application has multiple databases - */ - public function hasMultipleDatabases() - { - return (count($this->dbList) > 1); - } - - /** - * Return the database with the specified name. - * - * @param name database name - * @return A Database object. If it does not exist it returns null - */ - public function getDatabase($name = null, $doFinalInit = true) - { - // this is temporary until we'll have a clean solution - // for packaging datamodels/requiring schemas - if ($doFinalInit) { - $this->doFinalInitialization(); - } - - if ($name === null) { - return $this->dbList[0]; - } - - for ($i=0,$size=count($this->dbList); $i < $size; $i++) { - $db = $this->dbList[$i]; - if ($db->getName() === $name) { - return $db; - } - } - return null; - } - - /** - * Checks whether a database with the specified nam exists in this AppData - * - * @param name database name - * @return boolean - */ - public function hasDatabase($name) - { - foreach ($this->dbList as $db) { - if ($db->getName() === $name) { - return true; - } - } - return false; - } - - /** - * Add a database to the list and sets the AppData property to this - * AppData - * - * @param db the database to add - */ - public function addDatabase($db) - { - if ($db instanceof Database) { - $db->setAppData($this); - if ($db->getPlatform() === null) { - $db->setPlatform($this->platform); - } - $this->dbList[] = $db; - return $db; - } else { - // XML attributes array / hash - $d = new Database(); - $d->setAppData($this); - if ($d->getPlatform() === null) { - $d->setPlatform($this->platform); - } - $d->loadFromXML($db); - return $this->addDatabase($d); // calls self w/ different param type - } - - } - - public function doFinalInitialization() - { - if (!$this->isInitialized) { - for ($i=0, $size=count($this->dbList); $i < $size; $i++) { - $this->dbList[$i]->doFinalInitialization(); - } - $this->isInitialized = true; - } - } - - /** - * Creats a string representation of this AppData. - * The representation is given in xml format. - * - * @return string Representation in xml format - */ - public function toString() - { - $result = "\n"; - for ($i=0,$size=count($this->dbList); $i < $size; $i++) { - $result .= $this->dbList[$i]->toString(); - } - $result .= ""; - return $result; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Behavior.php b/airtime_mvc/library/propel/generator/lib/model/Behavior.php deleted file mode 100644 index 281158311..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Behavior.php +++ /dev/null @@ -1,247 +0,0 @@ -name = $name; - } - - public function getName() - { - return $this->name; - } - - public function setTable(Table $table) - { - $this->table = $table; - } - - public function getTable() - { - return $this->table; - } - - public function setDatabase(Database $database) - { - $this->database = $database; - } - - public function getDatabase() - { - return $this->database; - } - - /** - * Add a parameter - * Expects an associative array looking like array('name' => 'foo', 'value' => bar) - * - * @param array associative array with name and value keys - */ - public function addParameter($attribute) - { - $attribute = array_change_key_case($attribute, CASE_LOWER); - $this->parameters[$attribute['name']] = $attribute['value']; - } - - /** - * Overrides the behavior parameters - * Expects an associative array looking like array('foo' => 'bar') - * - * @param array associative array - */ - public function setParameters($parameters) - { - $this->parameters = $parameters; - } - - /** - * Get the associative array of parameters - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - public function getParameter($name) - { - return $this->parameters[$name]; - } - - /** - * This method is automatically called on database behaviors when the database model is finished - * Propagate the behavior to the tables of the database - * Override this method to have a database behavior do something special - */ - public function modifyDatabase() - { - foreach ($this->getDatabase()->getTables() as $table) - { - $b = clone $this; - $table->addBehavior($b); - } - } - - /** - * This method is automatically called on table behaviors when the database model is finished - * Override it to add columns to the current table - */ - public function modifyTable() - { - } - - public function setTableModified($bool) - { - $this->isTableModified = $bool; - } - - public function isTableModified() - { - return $this->isTableModified; - } - - public function setEarly($bool = true) - { - $this->isEarly = $bool; - } - - public function isEarly() - { - return $this->isEarly; - } - - /** - * Use Propel's simple templating system to render a PHP file - * using variables passed as arguments. - * - * @param string $filename The template file name, relative to the behavior's dirname - * @param array $vars An associative array of argumens to be rendered - * @param string $templateDir The name of the template subdirectory - * - * @return string The rendered template - */ - public function renderTemplate($filename, $vars = array(), $templateDir = '/templates/') - { - $filePath = $this->getDirname() . $templateDir . $filename; - if (!file_exists($filePath)) { - // try with '.php' at the end - $filePath = $filePath . '.php'; - if (!file_exists($filePath)) { - throw new InvalidArgumentException(sprintf('Template "%s" not found in "%s" directory', - $filename, - $this->getDirname() . $templateDir - )); - } - } - $template = new PropelTemplate(); - $template->setTemplateFile($filePath); - $vars = array_merge($vars, array('behavior' => $this)); - - return $template->render($vars); - } - - /** - * Returns the current dirname of this behavior (also works for descendants) - * - * @return string The absolute directory name - */ - protected function getDirname() - { - if (null === $this->dirname) { - $r = new ReflectionObject($this); - $this->dirname = dirname($r->getFileName()); - } - return $this->dirname; - } - - /** - * Retrieve a column object using a name stored in the behavior parameters - * Useful for table behaviors - * - * @param string $param Name of the parameter storing the column name - * @return ColumnMap The column of the table supporting the behavior - */ - public function getColumnForParameter($param) - { - return $this->getTable()->getColumn($this->getParameter($param)); - } - - /** - * Sets up the Behavior object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->name = $this->getAttribute("name"); - } - - /** - * @see parent::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $bNode = $node->appendChild($doc->createElement('behavior')); - $bNode->setAttribute('name', $this->getName()); - - foreach ($this->parameters as $name => $value) { - $parameterNode = $bNode->appendChild($doc->createElement('parameter')); - $parameterNode->setAttribute('name', $name); - $parameterNode->setAttribute('value', $value); - } - } - - public function getTableModifier() - { - return $this; - } - - public function getObjectBuilderModifier() - { - return $this; - } - - public function getQueryBuilderModifier() - { - return $this; - } - - public function getPeerBuilderModifier() - { - return $this; - } - - public function getTableMapBuilderModifier() - { - return $this; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Column.php b/airtime_mvc/library/propel/generator/lib/model/Column.php deleted file mode 100644 index 053d78066..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Column.php +++ /dev/null @@ -1,1188 +0,0 @@ - (Propel) - * @author Leon Messerschmidt (Torque) - * @author Jason van Zyl (Torque) - * @author Jon S. Stevens (Torque) - * @author Daniel Rall (Torque) - * @author Byron Foster (Torque) - * @author Bernd Goldschmidt - * @version $Revision: 1778 $ - * @package propel.generator.model - */ -class Column extends XMLElement -{ - - const DEFAULT_TYPE = "VARCHAR"; - const DEFAULT_VISIBILITY = 'public'; - public static $valid_visibilities = array('public', 'protected', 'private'); - - private $name; - private $description; - private $phpName = null; - private $phpNamingMethod; - private $isNotNull = false; - private $size; - private $namePrefix; - private $accessorVisibility; - private $mutatorVisibility; - - /** - * The name to use for the Peer constant that identifies this column. - * (Will be converted to all-uppercase in the templates.) - * @var string - */ - private $peerName; - - /** - * Native PHP type (scalar or class name) - * @var string "string", "boolean", "int", "double" - */ - private $phpType; - - /** - * @var Table - */ - private $parentTable; - - private $position; - private $isPrimaryKey = false; - private $isNodeKey = false; - private $nodeKeySep; - private $isNestedSetLeftKey = false; - private $isNestedSetRightKey = false; - private $isTreeScopeKey = false; - private $isUnique = false; - private $isAutoIncrement = false; - private $isLazyLoad = false; - private $defaultValue; - private $referrers; - private $isPrimaryString = false; - - // only one type is supported currently, which assumes the - // column either contains the classnames or a key to - // classnames specified in the schema. Others may be - // supported later. - private $inheritanceType; - private $isInheritance; - private $isEnumeratedClasses; - private $inheritanceList; - private $needsTransactionInPostgres; //maybe this can be retrieved from vendorSpecificInfo - - /** class name to do input validation on this column */ - private $inputValidator = null; - - /** - * @var Domain The domain object associated with this Column. - */ - private $domain; - - /** - * Creates a new column and set the name - * - * @param name column name - */ - public function __construct($name = null) - { - $this->name = $name; - } - - /** - * Return a comma delimited string listing the specified columns. - * - * @param columns Either a list of Column objects, or - * a list of String objects with column names. - * @deprecated Use the DDLBuilder->getColumnList() method instead; this will be removed in 1.3 - */ - public static function makeList($columns, Platform $platform) - { - $list = array(); - foreach ($columns as $col) { - if ($col instanceof Column) { - $col = $col->getName(); - } - $list[] = $platform->quoteIdentifier($col); - } - return implode(", ", $list); - } - - /** - * Sets up the Column object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - try { - $dom = $this->getAttribute("domain"); - if ($dom) { - $this->getDomain()->copy($this->getTable()->getDatabase()->getDomain($dom)); - } else { - $type = strtoupper($this->getAttribute("type")); - if ($type) { - $this->getDomain()->copy($this->getPlatform()->getDomainForType($type)); - } else { - $this->getDomain()->copy($this->getPlatform()->getDomainForType(self::DEFAULT_TYPE)); - } - } - - $this->name = $this->getAttribute("name"); - $this->phpName = $this->getAttribute("phpName"); - $this->phpType = $this->getAttribute("phpType"); - - if ($this->getAttribute("prefix", null) !== null) { - $this->namePrefix = $this->getAttribute("prefix"); - } elseif ($this->getTable()->getAttribute('columnPrefix', null) !== null) { - $this->namePrefix = $this->getTable()->getAttribute('columnPrefix'); - } else { - $this->namePrefix = ''; - } - - // Accessor visibility - if ($this->getAttribute('accessorVisibility', null) !== null) { - $this->setAccessorVisibility($this->getAttribute('accessorVisibility')); - } elseif ($this->getTable()->getAttribute('defaultAccessorVisibility', null) !== null) { - $this->setAccessorVisibility($this->getTable()->getAttribute('defaultAccessorVisibility')); - } elseif ($this->getTable()->getDatabase()->getAttribute('defaultAccessorVisibility', null) !== null) { - $this->setAccessorVisibility($this->getTable()->getDatabase()->getAttribute('defaultAccessorVisibility')); - } else { - $this->setAccessorVisibility(self::DEFAULT_VISIBILITY); - } - - // Mutator visibility - if ($this->getAttribute('mutatorVisibility', null) !== null) { - $this->setMutatorVisibility($this->getAttribute('mutatorVisibility')); - } elseif ($this->getTable()->getAttribute('defaultMutatorVisibility', null) !== null) { - $this->setMutatorVisibility($this->getTable()->getAttribute('defaultMutatorVisibility')); - } elseif ($this->getTable()->getDatabase()->getAttribute('defaultMutatorVisibility', null) !== null) { - $this->setMutatorVisibility($this->getTable()->getDatabase()->getAttribute('defaultMutatorVisibility')); - } else { - $this->setMutatorVisibility(self::DEFAULT_VISIBILITY); - } - - $this->peerName = $this->getAttribute("peerName"); - - // retrieves the method for converting from specified name to a PHP name, defaulting to parent tables default method - $this->phpNamingMethod = $this->getAttribute("phpNamingMethod", $this->parentTable->getDatabase()->getDefaultPhpNamingMethod()); - - $this->isPrimaryString = $this->booleanValue($this->getAttribute("primaryString")); - - $this->isPrimaryKey = $this->booleanValue($this->getAttribute("primaryKey")); - - $this->isNodeKey = $this->booleanValue($this->getAttribute("nodeKey")); - $this->nodeKeySep = $this->getAttribute("nodeKeySep", "."); - - $this->isNestedSetLeftKey = $this->booleanValue($this->getAttribute("nestedSetLeftKey")); - $this->isNestedSetRightKey = $this->booleanValue($this->getAttribute("nestedSetRightKey")); - $this->isTreeScopeKey = $this->booleanValue($this->getAttribute("treeScopeKey")); - - $this->isNotNull = ($this->booleanValue($this->getAttribute("required"), false) || $this->isPrimaryKey); // primary keys are required - - //AutoIncrement/Sequences - $this->isAutoIncrement = $this->booleanValue($this->getAttribute("autoIncrement")); - $this->isLazyLoad = $this->booleanValue($this->getAttribute("lazyLoad")); - - // Add type, size information to associated Domain object - $this->getDomain()->replaceSqlType($this->getAttribute("sqlType")); - if (!$this->getAttribute("size") && $this->getDomain()->getType() == 'VARCHAR' && !$this->getAttribute("sqlType")) { - $size = 255; - } else { - $size = $this->getAttribute("size"); - } - $this->getDomain()->replaceSize($size); - $this->getDomain()->replaceScale($this->getAttribute("scale")); - - $defval = $this->getAttribute("defaultValue", $this->getAttribute("default")); - if ($defval !== null && strtolower($defval) !== 'null') { - $this->getDomain()->setDefaultValue(new ColumnDefaultValue($defval, ColumnDefaultValue::TYPE_VALUE)); - } elseif ($this->getAttribute("defaultExpr") !== null) { - $this->getDomain()->setDefaultValue(new ColumnDefaultValue($this->getAttribute("defaultExpr"), ColumnDefaultValue::TYPE_EXPR)); - } - - $this->inheritanceType = $this->getAttribute("inheritance"); - $this->isInheritance = ($this->inheritanceType !== null - && $this->inheritanceType !== "false"); // here we are only checking for 'false', so don't - // use boleanValue() - - $this->inputValidator = $this->getAttribute("inputValidator"); - $this->description = $this->getAttribute("description"); - } catch (Exception $e) { - throw new EngineException("Error setting up column " . var_export($this->getAttribute("name"), true) . ": " . $e->getMessage()); - } - } - - /** - * Gets domain for this column, creating a new empty domain object if none is set. - * @return Domain - */ - public function getDomain() - { - if ($this->domain === null) { - $this->domain = new Domain(); - } - return $this->domain; - } - - /** - * Returns table.column - */ - public function getFullyQualifiedName() - { - return ($this->parentTable->getName() . '.' . strtoupper($this->getName())); - } - - /** - * Get the name of the column - */ - public function getName() - { - return $this->name; - } - - /** - * Set the name of the column - */ - public function setName($newName) - { - $this->name = $newName; - } - - /** - * Get the description for the Table - */ - public function getDescription() - { - return $this->description; - } - - /** - * Set the description for the Table - * - * @param newDescription description for the Table - */ - public function setDescription($newDescription) - { - $this->description = $newDescription; - } - - /** - * Get name to use in PHP sources. It will set & return - * a self-generated phpName from it's name if it's - * not already set. - * @return string - */ - public function getPhpName() - { - if ($this->phpName === null) { - $this->setPhpName(); - } - return $this->phpName; - } - - /** - * Set name to use in PHP sources. - * - * It will generate a phpName from it's name if no - * $phpName is passed. - * - * @param String $phpName PhpName to be set - */ - public function setPhpName($phpName = null) - { - if ($phpName == null) { - $this->phpName = self::generatePhpName($this->name, $this->phpNamingMethod, $this->namePrefix); - } else { - $this->phpName = $phpName; - } - } - - /** - * Get studly version of PHP name. - * - * The studly name is the PHP name with the first character lowercase. - * - * @return string - */ - public function getStudlyPhpName() - { - $phpname = $this->getPhpName(); - if (strlen($phpname) > 1) { - return strtolower(substr($phpname, 0, 1)) . substr($phpname, 1); - } else { // 0 or 1 chars (I suppose that's rare) - return strtolower($phpname); - } - } - - /** - * Get the visibility of the accessors of this column / attribute - * @return string - */ - public function getAccessorVisibility() { - if ($this->accessorVisibility !== null) { - return $this->accessorVisibility; - } else { - return self::DEFAULT_VISIBILITY; - } - } - - /** - * Set the visibility of the accessor methods for this column / attribute - * @param $newVisibility string - */ - public function setAccessorVisibility($newVisibility) { - if (in_array($newVisibility, self::$valid_visibilities)) { - $this->accessorVisibility = $newVisibility; - } else { - $this->accessorVisibility = self::DEFAULT_VISIBILITY; - } - - } - - /** - * Get the visibility of the mutator of this column / attribute - * @return string - */ - public function getMutatorVisibility() { - if ($this->mutatorVisibility !== null) { - return $this->mutatorVisibility; - } else { - return self::DEFAULT_VISIBILITY; - } - } - - /** - * Set the visibility of the mutator methods for this column / attribute - * @param $newVisibility string - */ - public function setMutatorVisibility($newVisibility) { - if (in_array($newVisibility, self::$valid_visibilities)) { - $this->mutatorVisibility = $newVisibility; - } else { - $this->mutatorVisibility = self::DEFAULT_VISIBILITY; - } - - } - - /** - * Get the column constant name (e.g. PeerName::COLUMN_NAME). - * - * @return string A column constant name for insertion into PHP code - */ - public function getConstantName() - { - $classname = $this->getTable()->getPhpName() . 'Peer'; - $const = $this->getConstantColumnName(); - return $classname.'::'.$const; - } - - public function getConstantColumnName() - { - // was it overridden in schema.xml ? - if ($this->getPeerName()) { - return strtoupper($this->getPeerName()); - } else { - return strtoupper($this->getName()); - } - } - - /** - * Get the Peer constant name that will identify this column. - * @return string - */ - public function getPeerName() { - return $this->peerName; - } - - /** - * Set the Peer constant name that will identify this column. - * @param $name string - */ - public function setPeerName($name) { - $this->peerName = $name; - } - - /** - * Get type to use in PHP sources. - * - * If no type has been specified, then uses results of getPhpNative(). - * - * @return string The type name. - * @see getPhpNative() - */ - public function getPhpType() - { - if ($this->phpType !== null) { - return $this->phpType; - } - return $this->getPhpNative(); - } - - /** - * Get the location of this column within the table (one-based). - * @return int value of position. - */ - public function getPosition() - { - return $this->position; - } - - /** - * Get the location of this column within the table (one-based). - * @param int $v Value to assign to position. - */ - public function setPosition($v) - { - $this->position = $v; - } - - /** - * Set the parent Table of the column - */ - public function setTable(Table $parent) - { - $this->parentTable = $parent; - } - - /** - * Get the parent Table of the column - */ - public function getTable() - { - return $this->parentTable; - } - - /** - * Returns the Name of the table the column is in - */ - public function getTableName() - { - return $this->parentTable->getName(); - } - - /** - * Adds a new inheritance definition to the inheritance list and set the - * parent column of the inheritance to the current column - * @param mixed $inhdata Inheritance or XML data. - */ - public function addInheritance($inhdata) - { - if ($inhdata instanceof Inheritance) { - $inh = $inhdata; - $inh->setColumn($this); - if ($this->inheritanceList === null) { - $this->inheritanceList = array(); - $this->isEnumeratedClasses = true; - } - $this->inheritanceList[] = $inh; - return $inh; - } else { - $inh = new Inheritance(); - $inh->loadFromXML($inhdata); - return $this->addInheritance($inh); - } - } - - /** - * Get the inheritance definitions. - */ - public function getChildren() - { - return $this->inheritanceList; - } - - /** - * Determine if this column is a normal property or specifies a - * the classes that are represented in the table containing this column. - */ - public function isInheritance() - { - return $this->isInheritance; - } - - /** - * Determine if possible classes have been enumerated in the xml file. - */ - public function isEnumeratedClasses() - { - return $this->isEnumeratedClasses; - } - - /** - * Return the isNotNull property of the column - */ - public function isNotNull() - { - return $this->isNotNull; - } - - /** - * Set the isNotNull property of the column - */ - public function setNotNull($status) - { - $this->isNotNull = (boolean) $status; - } - - /** - * Return NOT NULL String for this column - * - * @return "NOT NULL" if null values are not allowed or an empty string. - */ - public function getNotNullString() - { - return $this->getTable()->getDatabase()->getPlatform()->getNullString($this->isNotNull()); - } - - /** - * Set whether the column is the primary string, - * i.e. whether its value is the default string representation of the table - * @param boolean $v - */ - public function setPrimaryString($v) - { - $this->isPrimaryString = (boolean) $v; - } - - /** - * Return true if the column is the primary string, - * i.e. if its value is the default string representation of the table - */ - public function isPrimaryString() - { - return $this->isPrimaryString; - } - - /** - * Set whether the column is a primary key or not. - * @param boolean $v - */ - public function setPrimaryKey($v) - { - $this->isPrimaryKey = (boolean) $v; - } - - /** - * Return true if the column is a primary key - */ - public function isPrimaryKey() - { - return $this->isPrimaryKey; - } - - /** - * Set if the column is the node key of a tree - */ - public function setNodeKey($nk) - { - $this->isNodeKey = (boolean) $nk; - } - - /** - * Return true if the column is a node key of a tree - */ - public function isNodeKey() - { - return $this->isNodeKey; - } - - /** - * Set if the column is the node key of a tree - */ - public function setNodeKeySep($sep) - { - $this->nodeKeySep = (string) $sep; - } - - /** - * Return true if the column is a node key of a tree - */ - public function getNodeKeySep() - { - return $this->nodeKeySep; - } - - /** - * Set if the column is the nested set left key of a tree - */ - public function setNestedSetLeftKey($nslk) - { - $this->isNestedSetLeftKey = (boolean) $nslk; - } - - /** - * Return true if the column is a nested set key of a tree - */ - public function isNestedSetLeftKey() - { - return $this->isNestedSetLeftKey; - } - - /** - * Set if the column is the nested set right key of a tree - */ - public function setNestedSetRightKey($nsrk) - { - $this->isNestedSetRightKey = (boolean) $nsrk; - } - - /** - * Return true if the column is a nested set right key of a tree - */ - public function isNestedSetRightKey() - { - return $this->isNestedSetRightKey; - } - - /** - * Set if the column is the scope key of a tree - */ - public function setTreeScopeKey($tsk) - { - $this->isTreeScopeKey = (boolean) $tsk; - } - - /** - * Return true if the column is a scope key of a tree - * @return boolean - */ - public function isTreeScopeKey() - { - return $this->isTreeScopeKey; - } - - /** - * Set true if the column is UNIQUE - * @param boolean $u - */ - public function setUnique($u) - { - $this->isUnique = $u; - } - - /** - * Get the UNIQUE property. - * @return boolean - */ - public function isUnique() - { - return $this->isUnique; - } - - /** - * Return true if the column requires a transaction in Postgres - * @return boolean - */ - public function requiresTransactionInPostgres() - { - return $this->needsTransactionInPostgres; - } - - /** - * Utility method to determine if this column is a foreign key. - * @return boolean - */ - public function isForeignKey() - { - return (count($this->getForeignKeys()) > 0); - } - - /** - * Whether this column is a part of more than one foreign key. - * @return boolean - */ - public function hasMultipleFK() - { - return (count($this->getForeignKeys()) > 1); - } - - /** - * Get the foreign key objects for this column (if it is a foreign key or part of a foreign key) - * @return array - */ - public function getForeignKeys() - { - return $this->parentTable->getColumnForeignKeys($this->name); - } - - /** - * Adds the foreign key from another table that refers to this column. - */ - public function addReferrer(ForeignKey $fk) - { - if ($this->referrers === null) { - $this->referrers = array(); - } - $this->referrers[] = $fk; - } - - /** - * Get list of references to this column. - */ - public function getReferrers() - { - if ($this->referrers === null) { - $this->referrers = array(); - } - return $this->referrers; - } - - /** - * Sets the domain up for specified Propel type. - * - * Calling this method will implicitly overwrite any previously set type, - * size, scale (or other domain attributes). - * - * @param string $propelType - */ - public function setDomainForType($propelType) - { - $this->getDomain()->copy($this->getPlatform()->getDomainForType($propelType)); - } - - /** - * Sets the propel colunm type. - * @param string $propelType - * @see Domain::setType() - */ - public function setType($propelType) - { - $this->getDomain()->setType($propelType); - if ($propelType == PropelTypes::VARBINARY|| $propelType == PropelTypes::LONGVARBINARY || $propelType == PropelTypes::BLOB) { - $this->needsTransactionInPostgres = true; - } - } - - /** - * Returns the Propel column type as a string. - * @return string The constant representing Propel type: e.g. "VARCHAR". - * @see Domain::getType() - */ - public function getType() - { - return $this->getDomain()->getType(); - } - - /** - * Returns the column PDO type integer for this column's Propel type. - * @return int The integer value representing PDO type param: e.g. PDO::PARAM_INT - */ - public function getPDOType() - { - return PropelTypes::getPDOType($this->getType()); - } - - /** - * Returns the column type as given in the schema as an object - */ - public function getPropelType() - { - return $this->getType(); - } - - /** - * Utility method to know whether column needs Blob/Lob handling. - * @return boolean - */ - public function isLobType() - { - return PropelTypes::isLobType($this->getType()); - } - - /** - * Utility method to see if the column is text type. - */ - public function isTextType() - { - return PropelTypes::isTextType($this->getType()); - } - - /** - * Utility method to see if the column is numeric type. - * @return boolean - */ - public function isNumericType() - { - return PropelTypes::isNumericType($this->getType()); - } - - /** - * Utility method to see if the column is boolean type. - * @return boolean - */ - public function isBooleanType() - { - return PropelTypes::isBooleanType($this->getType()); - } - - /** - * Utility method to know whether column is a temporal column. - * @return boolean - */ - public function isTemporalType() - { - return PropelTypes::isTemporalType($this->getType()); - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $colNode = $node->appendChild($doc->createElement('column')); - $colNode->setAttribute('name', $this->name); - - if ($this->phpName !== null) { - $colNode->setAttribute('phpName', $this->getPhpName()); - } - - $colNode->setAttribute('type', $this->getType()); - - $domain = $this->getDomain(); - - if ($domain->getSize() !== null) { - $colNode->setAttribute('size', $domain->getSize()); - } - - if ($domain->getScale() !== null) { - $colNode->setAttribute('scale', $domain->getScale()); - } - - if ($this->isPrimaryKey) { - $colNode->setAttribute('primaryKey', var_export($this->isPrimaryKey, true)); - } - - if ($this->isAutoIncrement) { - $colNode->setAttribute('autoIncrement', var_export($this->isAutoIncrement, true)); - } - - if ($this->isNotNull) { - $colNode->setAttribute('required', 'true'); - } else { - $colNode->setAttribute('required', 'false'); - } - - if ($domain->getDefaultValue() !== null) { - $def = $domain->getDefaultValue(); - if ($def->isExpression()) { - $colNode->setAttribute('defaultExpr', $def->getValue()); - } else { - $colNode->setAttribute('defaultValue', $def->getValue()); - } - } - - if ($this->isInheritance()) { - $colNode->setAttribute('inheritance', $this->inheritanceType); - foreach ($this->inheritanceList as $inheritance) { - $inheritance->appendXml($colNode); - } - } - - if ($this->isNodeKey()) { - $colNode->setAttribute('nodeKey', 'true'); - if ($this->getNodeKeySep() !== null) { - $colNode->setAttribute('nodeKeySep', $this->nodeKeySep); - } - } - - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($colNode); - } - } - - /** - * Returns the size of the column - * @return string - */ - public function getSize() - { - return $this->domain->getSize(); - } - - /** - * Set the size of the column - * @param string $newSize - */ - public function setSize($newSize) - { - $this->domain->setSize($newSize); - } - - /** - * Returns the scale of the column - * @return string - */ - public function getScale() - { - return $this->domain->getScale(); - } - - /** - * Set the scale of the column - * @param string $newScale - */ - public function setScale($newScale) - { - $this->domain->setScale($newScale); - } - - /** - * Return the size in brackets for use in an sql - * schema if the type is String. Otherwise return an empty string - */ - public function printSize() - { - return $this->domain->printSize(); - } - - /** - * Return a string that will give this column a default value. - * @return string - */ - public function getDefaultSetting() - { - $dflt = ""; - $defaultValue = $this->getDefaultValue(); - if ($defaultValue !== null) { - $dflt .= "default "; - - if ($this->getDefaultValue()->isExpression()) { - $dflt .= $this->getDefaultValue()->getValue(); - } else { - if ($this->isTextType()) { - $dflt .= $this->getPlatform()->quote($defaultValue->getValue()); - } elseif ($this->getType() == PropelTypes::BOOLEAN) { - $dflt .= $this->getPlatform()->getBooleanString($defaultValue->getValue()); - } else { - $dflt .= $defaultValue->getValue(); - } - } - } - return $dflt; - } - - /** - * Return a string that will give this column a default value in PHP - * @return string - */ - public function getDefaultValueString() - { - $defaultValue = $this->getDefaultValue(); - if ($defaultValue !== null) { - if ($this->isNumericType()) { - $dflt = (float) $defaultValue->getValue(); - } elseif ($this->isTextType() || $this->getDefaultValue()->isExpression()) { - $dflt = "'" . str_replace("'", "\'", $defaultValue->getValue()) . "'"; - } elseif ($this->getType() == PropelTypes::BOOLEAN) { - $dflt = $this->booleanValue($defaultValue->getValue()) ? 'true' : 'false'; - } else { - $dflt = "'" . $defaultValue->getValue() . "'"; - } - } else { - $dflt = "null"; - } - return $dflt; - } - - /** - * Set a string that will give this column a default value. - */ - public function setDefaultValue($def) - { - $this->domain->setDefaultValue($def); - } - - /** - * Get the default value object for this column. - * @return ColumnDefaultValue - * @see Domain::getDefaultValue() - */ - public function getDefaultValue() - { - return $this->domain->getDefaultValue(); - } - - /** - * Get the default value suitable for use in PHP. - * @return mixed - * @see Domain::getPhpDefaultValue() - */ - public function getPhpDefaultValue() - { - return $this->domain->getPhpDefaultValue(); - } - - /** - * Returns the class name to do input validation - */ - public function getInputValidator() - { - return $this->inputValidator; - } - - /** - * Return auto increment/sequence string for the target database. We need to - * pass in the props for the target database! - */ - public function isAutoIncrement() - { - return $this->isAutoIncrement; - } - - /** - * Return auto increment/sequence string for the target database. We need to - * pass in the props for the target database! - */ - public function isLazyLoad() - { - return $this->isLazyLoad; - } - - /** - * Gets the auto-increment string. - * @return string - */ - public function getAutoIncrementString() - { - if ($this->isAutoIncrement()&& IDMethod::NATIVE === $this->getTable()->getIdMethod()) { - return $this->getPlatform()->getAutoIncrement(); - } elseif ($this->isAutoIncrement()) { - throw new EngineException("You have specified autoIncrement for column '" . $this->name . "' but you have not specified idMethod=\"native\" for table '" . $this->getTable()->getName() . "'."); - } - return ""; - } - - /** - * Set the auto increment value. - * Use isAutoIncrement() to find out if it is set or not. - */ - public function setAutoIncrement($value) - { - $this->isAutoIncrement = (boolean) $value; - } - - /** - * Set the column type from a string property - * (normally a string from an sql input file) - * - * @deprecated Do not use; this will be removed in next release. - */ - public function setTypeFromString($typeName, $size) - { - $tn = strtoupper($typeName); - $this->setType($tn); - - if ($size !== null) { - $this->size = $size; - } - - if (strpos($tn, "CHAR") !== false) { - $this->domain->setType(PropelTypes::VARCHAR); - } elseif (strpos($tn, "INT") !== false) { - $this->domain->setType(PropelTypes::INTEGER); - } elseif (strpos($tn, "FLOAT") !== false) { - $this->domain->setType(PropelTypes::FLOAT); - } elseif (strpos($tn, "DATE") !== false) { - $this->domain->setType(PropelTypes::DATE); - } elseif (strpos($tn, "TIME") !== false) { - $this->domain->setType(PropelTypes::TIMESTAMP); - } else if (strpos($tn, "BINARY") !== false) { - $this->domain->setType(PropelTypes::LONGVARBINARY); - } else { - $this->domain->setType(PropelTypes::VARCHAR); - } - } - - /** - * Return a string representation of the native PHP type which corresponds - * to the propel type of this column. Use in the generation of Base objects. - * - * @return string PHP datatype used by propel. - */ - public function getPhpNative() - { - return PropelTypes::getPhpNative($this->getType()); - } - - /** - * Returns true if the column's PHP native type is an boolean, int, long, float, double, string. - * @return boolean - * @see PropelTypes::isPhpPrimitiveType() - */ - public function isPhpPrimitiveType() - { - return PropelTypes::isPhpPrimitiveType($this->getPhpType()); - } - - /** - * Return true if column's PHP native type is an boolean, int, long, float, double. - * @return boolean - * @see PropelTypes::isPhpPrimitiveNumericType() - */ - public function isPhpPrimitiveNumericType() - { - return PropelTypes::isPhpPrimitiveNumericType($this->getPhpType()); - } - - /** - * Returns true if the column's PHP native type is a class name. - * @return boolean - * @see PropelTypes::isPhpObjectType() - */ - public function isPhpObjectType() - { - return PropelTypes::isPhpObjectType($this->getPhpType()); - } - - /** - * Get the platform/adapter impl. - * - * @return Platform - */ - public function getPlatform() - { - return $this->getTable()->getDatabase()->getPlatform(); - } - - /** - * - * @return string - * @deprecated Use DDLBuilder->getColumnDDL() instead; this will be removed in 1.3 - */ - public function getSqlString() - { - $sb = ""; - $sb .= $this->getPlatform()->quoteIdentifier($this->getName()) . " "; - $sb .= $this->getDomain()->getSqlType(); - if ($this->getPlatform()->hasSize($this->getDomain()->getSqlType())) { - $sb .= $this->getDomain()->printSize(); - } - $sb .= " "; - $sb .= $this->getDefaultSetting() . " "; - $sb .= $this->getNotNullString() . " "; - $sb .= $this->getAutoIncrementString(); - return trim($sb); - } - - public static function generatePhpName($name, $phpNamingMethod = PhpNameGenerator::CONV_METHOD_CLEAN, $namePrefix = null) { - return NameFactory::generateName(NameFactory::PHP_GENERATOR, array($name, $phpNamingMethod, $namePrefix)); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/ColumnDefaultValue.php b/airtime_mvc/library/propel/generator/lib/model/ColumnDefaultValue.php deleted file mode 100644 index 212fc44e4..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/ColumnDefaultValue.php +++ /dev/null @@ -1,91 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class ColumnDefaultValue -{ - - const TYPE_VALUE = "value"; - const TYPE_EXPR = "expr"; - - /** - * @var string The default value, as specified in the schema. - */ - private $value; - - /** - * @var string The type of value represented by this object (DefaultValue::TYPE_VALUE or DefaultValue::TYPE_EXPR). - */ - private $type = ColumnDefaultValue::TYPE_VALUE; - - /** - * Creates a new DefaultValue object. - * - * @param string $value The default value, as specified in the schema. - * @param string $type The type of default value (DefaultValue::TYPE_VALUE or DefaultValue::TYPE_EXPR) - */ - public function __construct($value, $type = null) - { - $this->setValue($value); - if ($type !== null) { - $this->setType($type); - } - } - - /** - * @return string The type of default value (DefaultValue::TYPE_VALUE or DefaultValue::TYPE_EXPR) - */ - public function getType() - { - return $this->type; - } - - /** - * @param string $type The type of default value (DefaultValue::TYPE_VALUE or DefaultValue::TYPE_EXPR) - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Convenience method to indicate whether the value in this object is an expression (as opposed to simple value). - * - * @return boolean Whether value this object holds is an expression. - */ - public function isExpression() - { - return ($this->type == self::TYPE_EXPR); - } - - /** - * @return string The value, as specified in the schema. - */ - public function getValue() - { - return $this->value; - } - - /** - * @param string $value The value, as specified in the schema. - */ - public function setValue($value) - { - $this->value = $value; - } - - -} diff --git a/airtime_mvc/library/propel/generator/lib/model/ConstraintNameGenerator.php b/airtime_mvc/library/propel/generator/lib/model/ConstraintNameGenerator.php deleted file mode 100644 index 735fea1b8..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/ConstraintNameGenerator.php +++ /dev/null @@ -1,72 +0,0 @@ -NameGenerator implementation for table-specific - * constraints. Conforms to the maximum column name length for the - * type of database in use. - * - * @author Hans Lellelid (Propel) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class ConstraintNameGenerator implements NameGenerator -{ - /** - * Conditional compilation flag. - */ - const DEBUG = false; - - /** - * First element of inputs should be of type {@link Database}, second - * should be a table name, third is the type identifier (spared if - * trimming is necessary due to database type length constraints), - * and the fourth is a Integer indicating the number - * of this contraint. - * - * @see NameGenerator - * @throws EngineException - */ - public function generateName($inputs) - { - - $db = $inputs[0]; - $name = $inputs[1]; - $namePostfix = $inputs[2]; - $constraintNbr = (string) $inputs[3]; - - // Calculate maximum RDBMS-specific column character limit. - $maxBodyLength = -1; - try { - $maxColumnNameLength = (int) $db->getPlatform()->getMaxColumnNameLength(); - $maxBodyLength = ($maxColumnNameLength - strlen($namePostfix) - - strlen($constraintNbr) - 2); - - if (self::DEBUG) { - print("maxColumnNameLength=" . $maxColumnNameLength - . " maxBodyLength=" . $maxBodyLength . "\n"); - } - } catch (EngineException $e) { - echo $e; - throw $e; - } - - // Do any necessary trimming. - if ($maxBodyLength !== -1 && strlen($name) > $maxBodyLength) { - $name = substr($name, 0, $maxBodyLength); - } - - $name .= self::STD_SEPARATOR_CHAR . $namePostfix - . self::STD_SEPARATOR_CHAR . $constraintNbr; - - return $name; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Database.php b/airtime_mvc/library/propel/generator/lib/model/Database.php deleted file mode 100644 index e34e4485d..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Database.php +++ /dev/null @@ -1,676 +0,0 @@ - (Propel) - * @author Leon Messerschmidt (Torque) - * @author John McNally (Torque) - * @author Martin Poeschl (Torque) - * @author Daniel Rall (Torque) - * @author Byron Foster (Torque) - * @version $Revision: 1802 $ - * @package propel.generator.model - */ -class Database extends XMLElement -{ - - private $platform; - private $tableList = array(); - private $curColumn; - private $name; - private $pkg; - - /** - * Namespace for the generated OM. - * - * @var string - */ - protected $namespace; - - private $baseClass; - private $basePeer; - private $defaultIdMethod; - private $defaultPhpNamingMethod; - private $defaultTranslateMethod; - private $dbParent; - private $tablesByName = array(); - private $tablesByPhpName = array(); - private $heavyIndexing; - protected $tablePrefix = ''; - - private $domainMap = array(); - - /** - * List of behaviors registered for this table - * - * @var array - */ - protected $behaviors = array(); - - /** - * Constructs a new Database object. - * - * @param string $name - */ - public function __construct($name = null) - { - $this->name = $name; - } - - /** - * Sets up the Database object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->name = $this->getAttribute("name"); - $namespace = $this->getAttribute("namespace", ''); - $package = $this->getAttribute("package"); - if ($namespace && !$package && $this->getBuildProperty('namespaceAutoPackage')) { - $package = str_replace('\\', '.', $namespace); - } - $this->namespace = $namespace; - $this->pkg = $package; - $this->baseClass = $this->getAttribute("baseClass"); - $this->basePeer = $this->getAttribute("basePeer"); - $this->defaultIdMethod = $this->getAttribute("defaultIdMethod", IDMethod::NATIVE); - $this->defaultPhpNamingMethod = $this->getAttribute("defaultPhpNamingMethod", NameGenerator::CONV_METHOD_UNDERSCORE); - $this->defaultTranslateMethod = $this->getAttribute("defaultTranslateMethod", Validator::TRANSLATE_NONE); - $this->heavyIndexing = $this->booleanValue($this->getAttribute("heavyIndexing")); - $this->tablePrefix = $this->getAttribute('tablePrefix', $this->getBuildProperty('tablePrefix')); - } - - /** - * Returns the Platform implementation for this database. - * - * @return Platform a Platform implementation - */ - public function getPlatform() - { - return $this->platform; - } - - /** - * Sets the Platform implementation for this database. - * - * @param Platform $platform A Platform implementation - */ - public function setPlatform($platform) - { - $this->platform = $platform; - } - - /** - * Get the name of the Database - */ - public function getName() - { - return $this->name; - } - - /** - * Set the name of the Database - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get the value of package. - * @return value of package. - */ - public function getPackage() - { - return $this->pkg; - } - - /** - * Set the value of package. - * @param v Value to assign to package. - */ - public function setPackage($v) - { - $this->pkg = $v; - } - - /** - * Get the value of the namespace. - * @return value of namespace. - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * Set the value of the namespace. - * @param v Value to assign to namespace. - */ - public function setNamespace($v) - { - $this->namespace = $v; - } - - /** - * Get the value of baseClass. - * @return value of baseClass. - */ - public function getBaseClass() - { - return $this->baseClass; - } - - /** - * Set the value of baseClass. - * @param v Value to assign to baseClass. - */ - public function setBaseClass($v) - { - $this->baseClass = $v; - } - - /** - * Get the value of basePeer. - * @return value of basePeer. - */ - public function getBasePeer() - { - return $this->basePeer; - } - - /** - * Set the value of basePeer. - * @param v Value to assign to basePeer. - */ - public function setBasePeer($v) - { - $this->basePeer = $v; - } - - /** - * Get the value of defaultIdMethod. - * @return value of defaultIdMethod. - */ - public function getDefaultIdMethod() - { - return $this->defaultIdMethod; - } - - /** - * Set the value of defaultIdMethod. - * @param v Value to assign to defaultIdMethod. - */ - public function setDefaultIdMethod($v) - { - $this->defaultIdMethod = $v; - } - - /** - * Get the value of defaultPHPNamingMethod which specifies the - * method for converting schema names for table and column to PHP names. - * @return string The default naming conversion used by this database. - */ - public function getDefaultPhpNamingMethod() - { - return $this->defaultPhpNamingMethod; - } - - /** - * Set the value of defaultPHPNamingMethod. - * @param string $v The default naming conversion for this database to use. - */ - public function setDefaultPhpNamingMethod($v) - { - $this->defaultPhpNamingMethod = $v; - } - - /** - * Get the value of defaultTranslateMethod which specifies the - * method for translate validator error messages. - * @return string The default translate method. - */ - public function getDefaultTranslateMethod() - { - return $this->defaultTranslateMethod; - } - - /** - * Set the value of defaultTranslateMethod. - * @param string $v The default translate method to use. - */ - public function setDefaultTranslateMethod($v) - { - $this->defaultTranslateMethod = $v; - } - - /** - * Get the value of heavyIndexing. - * - * This is a synonym for getHeavyIndexing(). - * - * @return boolean Value of heavyIndexing. - * @see getHeavyIndexing() - */ - public function isHeavyIndexing() - { - return $this->getHeavyIndexing(); - } - - /** - * Get the value of heavyIndexing. - * - * @return boolean Value of heavyIndexing. - */ - public function getHeavyIndexing() - { - return $this->heavyIndexing; - } - - /** - * Set the value of heavyIndexing. - * @param boolean $v Value to assign to heavyIndexing. - */ - public function setHeavyIndexing($v) - { - $this->heavyIndexing = (boolean) $v; - } - - /** - * Return an array of all tables - */ - public function getTables() - { - return $this->tableList; - } - - /** - * Check whether the database has a table. - * @return boolean - */ - public function hasTable($name) - { - return array_key_exists($name, $this->tablesByName); - } - - /** - * Return the table with the specified name. - * @param string $name The name of the table (e.g. 'my_table') - * @return Table a Table object or null if it doesn't exist - */ - public function getTable($name) - { - if ($this->hasTable($name)) { - return $this->tablesByName[$name]; - } - return null; // just to be explicit - } - - /** - * Return the table with the specified phpName. - * @param string $phpName the PHP Name of the table (e.g. 'MyTable') - * @return Table a Table object or null if it doesn't exist - */ - public function getTableByPhpName($phpName) - { - if (isset($this->tablesByPhpName[$phpName])) { - return $this->tablesByPhpName[$phpName]; - } - return null; // just to be explicit - } - - /** - * An utility method to add a new table from an xml attribute. - */ - public function addTable($data) - { - if ($data instanceof Table) { - $tbl = $data; // alias - $tbl->setDatabase($this); - if (isset($this->tablesByName[$tbl->getName()])) { - throw new EngineException("Duplicate table declared: " . $tbl->getName()); - } - $this->tableList[] = $tbl; - $this->tablesByName[ $tbl->getName() ] = $tbl; - $this->tablesByPhpName[ $tbl->getPhpName() ] = $tbl; - if ($tbl->getPackage() === null) { - $tbl->setPackage($this->getPackage()); - } - return $tbl; - } else { - $tbl = new Table(); - $tbl->setDatabase($this); - $tbl->loadFromXML($data); - return $this->addTable($tbl); // call self w/ different param - } - } - - /** - * Set the parent of the database - */ - public function setAppData(AppData $parent) - { - $this->dbParent = $parent; - } - - /** - * Get the parent of the table - */ - public function getAppData() - { - return $this->dbParent; - } - - /** - * Adds Domain object from tag. - * @param mixed XML attributes (array) or Domain object. - */ - public function addDomain($data) { - - if ($data instanceof Domain) { - $domain = $data; // alias - $domain->setDatabase($this); - $this->domainMap[ $domain->getName() ] = $domain; - return $domain; - } else { - $domain = new Domain(); - $domain->setDatabase($this); - $domain->loadFromXML($data); - return $this->addDomain($domain); // call self w/ different param - } - } - - /** - * Get already configured Domain object by name. - * @return Domain - */ - public function getDomain($domainName) - { - if (isset($this->domainMap[$domainName])) { - return $this->domainMap[$domainName]; - } - return null; // just to be explicit - } - - public function getGeneratorConfig() - { - if ($this->getAppData() && $this->getAppData()->getPlatform()) { - return $this->getAppData()->getPlatform()->getGeneratorConfig(); - } else { - return null; - } - } - - public function getBuildProperty($key) - { - if($config = $this->getGeneratorConfig()) { - return $config->getBuildProperty($key); - } else { - return ''; - } - } - - /** - * Adds a new Behavior to the database - * @return Behavior A behavior instance - */ - public function addBehavior($bdata) - { - if ($bdata instanceof Behavior) { - $behavior = $bdata; - $behavior->setDatabase($this); - $this->behaviors[$behavior->getName()] = $behavior; - return $behavior; - } else { - $class = $this->getConfiguredBehavior($bdata['name']); - $behavior = new $class(); - $behavior->loadFromXML($bdata); - return $this->addBehavior($behavior); - } - } - - /** - * Get the database behaviors - * @return Array of Behavior objects - */ - public function getBehaviors() - { - return $this->behaviors; - } - - /** - * check if the database has a behavior by name - * - * @param string $name the behavior name - * @return boolean True if the behavior exists - */ - public function hasBehavior($name) - { - return array_key_exists($name, $this->behaviors); - } - - /** - * Get one database behavior by name - * @param string $name the behavior name - * @return Behavior a behavior object - */ - public function getBehavior($name) - { - return $this->behaviors[$name]; - } - - /** - * Get the table prefix for this database - * - * @return string the table prefix - */ - public function getTablePrefix() - { - return $this->tablePrefix; - } - - - public function doFinalInitialization() - { - if($defaultBehaviors = $this->getBuildProperty('behaviorDefault')) { - // add generic behaviors from build.properties - $defaultBehaviors = explode(',', $defaultBehaviors); - foreach ($defaultBehaviors as $behavior) { - $this->addBehavior(array('name' => trim($behavior))); - } - } - - // execute behavior database modifiers - foreach ($this->getBehaviors() as $behavior) { - $behavior->modifyDatabase(); - } - - $tables = $this->getTables(); - - // execute early table behaviors - foreach ($tables as $table) { - foreach ($table->getEarlyBehaviors() as $behavior) { - if (!$behavior->isTableModified()) { - $behavior->getTableModifier()->modifyTable(); - $behavior->setTableModified(true); - } - } - } - - for ($i=0,$size=count($tables); $i < $size; $i++) { - $currTable = $tables[$i]; - - // check schema integrity - // if idMethod="autoincrement", make sure a column is - // specified as autoIncrement="true" - // FIXME: Handle idMethod="native" via DB adapter. - /* - - --- REMOVING THIS BECAUSE IT'S ANNOYING - - if ($currTable->getIdMethod() == IDMethod::NATIVE ) { - $columns = $currTable->getColumns(); - $foundOne = false; - for ($j=0, $cLen=count($columns); $j < $cLen && !$foundOne; $j++) { - $foundOne = $columns[$j]->isAutoIncrement(); - } - - if (!$foundOne) { - $errorMessage = "Table '" . $currTable->getName() - . "' is set to use native id generation, but it does not " - . "have a column which declared as the one to " - . "auto increment (i.e. autoIncrement=\"true\")"; - - throw new BuildException($errorMessage); - } - } - */ - - $currTable->doFinalInitialization(); - - // setup reverse fk relations - $fks = $currTable->getForeignKeys(); - for ($j=0, $fksLen=count($fks); $j < $fksLen; $j++) { - $currFK = $fks[$j]; - $foreignTable = $this->getTable($currFK->getForeignTableName()); - if ($foreignTable === null) { - throw new BuildException("ERROR!! Attempt to set foreign" - . " key to nonexistent table, " - . $currFK->getForeignTableName() . "!"); - } - - $referrers = $foreignTable->getReferrers(); - if ($referrers === null || !in_array($currFK, $referrers, true) ) { - $foreignTable->addReferrer($currFK); - } - - // local column references - $localColumnNames = $currFK->getLocalColumns(); - - for ($k=0,$lcnLen=count($localColumnNames); $k < $lcnLen; $k++) { - - $local = $currTable->getColumn($localColumnNames[$k]); - - // give notice of a schema inconsistency. - // note we do not prevent the npe as there is nothing - // that we can do, if it is to occur. - if ($local === null) { - throw new BuildException("ERROR!! Attempt to define foreign" - . " key with nonexistent column, " - . $localColumnNames[$k] . ", in table, " - . $currTable->getName() . "!"); - } - - //check for foreign pk's - if ($local->isPrimaryKey()) { - $currTable->setContainsForeignPK(true); - } - - } // for each local col name - - // foreign column references - $foreignColumnNames = $currFK->getForeignColumns(); - for ($k=0,$fcnLen=count($localColumnNames); $k < $fcnLen; $k++) { - $foreign = $foreignTable->getColumn($foreignColumnNames[$k]); - // if the foreign column does not exist, we may have an - // external reference or a misspelling - if ($foreign === null) { - throw new BuildException("ERROR!! Attempt to set foreign" - . " key to nonexistent column, " - . $foreignColumnNames[$k] . ", in table, " - . $foreignTable->getName() . "!"); - } else { - $foreign->addReferrer($currFK); - } - } // for each foreign col ref - } - } - - // Behaviors may have added behaviors of their own - // These behaviors must launch their modifyTable() method, - // Until there is no behavior left - $behaviorsLeft = true; - while ($behaviorsLeft) { - $behaviorsLeft = false; - foreach ($tables as $table) { - foreach ($table->getBehaviors() as $behavior) { - if (!$behavior->isTableModified()) { - $behavior->getTableModifier()->modifyTable(); - $behavior->setTableModified(true); - $behaviorsLeft = true; - } - } - } - } - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $dbNode = $node->appendChild($doc->createElement('database')); - - $dbNode->setAttribute('name', $this->name); - - if ($this->pkg) { - $dbNode->setAttribute('package', $this->pkg); - } - - if ($this->defaultIdMethod) { - $dbNode->setAttribute('defaultIdMethod', $this->defaultIdMethod); - } - - if ($this->baseClass) { - $dbNode->setAttribute('baseClass', $this->baseClass); - } - - if ($this->basePeer) { - $dbNode->setAttribute('basePeer', $this->basePeer); - } - - if ($this->defaultPhpNamingMethod) { - $dbNode->setAttribute('defaultPhpNamingMethod', $this->defaultPhpNamingMethod); - } - - if ($this->defaultTranslateMethod) { - $dbNode->setAttribute('defaultTranslateMethod', $this->defaultTranslateMethod); - } - - /* - - FIXME - Before we can add support for domains in the schema, we need - to have a method of the Column that indicates whether the column was mapped - to a SPECIFIC domain (since Column->getDomain() will always return a Domain object) - - foreach ($this->domainMap as $domain) { - $domain->appendXml($dbNode); - } - */ - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($dbNode); - } - - foreach ($this->tableList as $table) { - $table->appendXml($dbNode); - } - - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Domain.php b/airtime_mvc/library/propel/generator/lib/model/Domain.php deleted file mode 100644 index 632e3f374..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Domain.php +++ /dev/null @@ -1,386 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Domain extends XMLElement -{ - - /** - * @var string The name of this domain - */ - private $name; - - /** - * @var string Description for this domain. - */ - private $description; - - /** - * @var int Size - */ - private $size; - - /** - * @var int Scale - */ - private $scale; - - /** - * @var int Propel type from schema - */ - private $propelType; - - /** - * @var string The SQL type to use for this column - */ - private $sqlType; - - /** - * @var ColumnDefaultValue A default value - */ - private $defaultValue; - - /** - * @var Database - */ - private $database; - - /** - * Creates a new Domain object. - * If this domain needs a name, it must be specified manually. - * - * @param string $type Propel type. - * @param string $sqlType SQL type. - * @param string $size - * @param string $scale - */ - public function __construct($type = null, $sqlType = null, $size = null, $scale = null) - { - $this->propelType = $type; - $this->sqlType = ($sqlType !== null) ? $sqlType : $type; - $this->size = $size; - $this->scale = $scale; - } - - /** - * Copy the values from current object into passed-in Domain. - * @param Domain $domain Domain to copy values into. - */ - public function copy(Domain $domain) - { - $this->defaultValue = $domain->getDefaultValue(); - $this->description = $domain->getDescription(); - $this->name = $domain->getName(); - $this->scale = $domain->getScale(); - $this->size = $domain->getSize(); - $this->sqlType = $domain->getSqlType(); - $this->propelType = $domain->getType(); - } - - /** - * Sets up the Domain object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $schemaType = strtoupper($this->getAttribute("type")); - $this->copy($this->getDatabase()->getPlatform()->getDomainForType($schemaType)); - - //Name - $this->name = $this->getAttribute("name"); - - // Default value - $defval = $this->getAttribute("defaultValue", $this->getAttribute("default")); - if ($defval !== null) { - $this->setDefaultValue(new ColumnDefaultValue($defval, ColumnDefaultValue::TYPE_VALUE)); - } elseif ($this->getAttribute("defaultExpr") !== null) { - $this->setDefaultValue(new ColumnDefaultValue($this->getAttribute("defaultExpr"), ColumnDefaultValue::TYPE_EXPR)); - } - - $this->size = $this->getAttribute("size"); - $this->scale = $this->getAttribute("scale"); - $this->description = $this->getAttribute("description"); - } - - /** - * Sets the owning database object (if this domain is being setup via XML). - * @param Database $database - */ - public function setDatabase(Database $database) - { - $this->database = $database; - } - - /** - * Gets the owning database object (if this domain was setup via XML). - * @return Database - */ - public function getDatabase() - { - return $this->database; - } - - /** - * @return string Returns the description. - */ - public function getDescription() - { - return $this->description; - } - - /** - * @param string $description The description to set. - */ - public function setDescription($description) - { - $this->description = $description; - } - - /** - * @return string Returns the name. - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name The name to set. - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return string Returns the scale. - */ - public function getScale() - { - return $this->scale; - } - - /** - * @param string $scale The scale to set. - */ - public function setScale($scale) - { - $this->scale = $scale; - } - - /** - * Replaces the size if the new value is not null. - * - * @param string $value The size to set. - */ - public function replaceScale($value) - { - if ($value !== null) { - $this->scale = $value; - } - } - - /** - * @return int Returns the size. - */ - public function getSize() - { - return $this->size; - } - - /** - * @param int $size The size to set. - */ - public function setSize($size) - { - $this->size = $size; - } - - /** - * Replaces the size if the new value is not null. - * - * @param int $value The size to set. - */ - public function replaceSize($value) - { - if ($value !== null) { - $this->size = $value; - } - } - - /** - * @return string Returns the propelType. - */ - public function getType() - { - return $this->propelType; - } - - /** - * @param string $propelType The PropelTypes type to set. - */ - public function setType($propelType) - { - $this->propelType = $propelType; - } - - /** - * Replaces the type if the new value is not null. - * - * @param string $value The tyep to set. - */ - public function replaceType($value) - { - if ($value !== null) { - $this->propelType = $value; - } - } - - /** - * Gets the default value object. - * @return ColumnDefaultValue The default value object for this domain. - */ - public function getDefaultValue() - { - return $this->defaultValue; - } - - /** - * Gets the default value, type-casted for use in PHP OM. - * @return mixed - * @see getDefaultValue() - */ - public function getPhpDefaultValue() - { - if ($this->defaultValue === null) { - return null; - } else { - if ($this->defaultValue->isExpression()) { - throw new EngineException("Cannot get PHP version of default value for default value EXPRESSION."); - } - if ($this->propelType === PropelTypes::BOOLEAN || $this->propelType === PropelTypes::BOOLEAN_EMU) { - return $this->booleanValue($this->defaultValue->getValue()); - } else { - return $this->defaultValue->getValue(); - } - } - } - - /** - * @param ColumnDefaultValue $value The column default value to set. - */ - public function setDefaultValue(ColumnDefaultValue $value) - { - $this->defaultValue = $value; - } - - /** - * Replaces the default value if the new value is not null. - * - * @param ColumnDefaultValue $value The defualt value object - */ - public function replaceDefaultValue(ColumnDefaultValue $value = null) - { - if ($value !== null) { - $this->defaultValue = $value; - } - } - - /** - * @return string Returns the sqlType. - */ - public function getSqlType() - { - return $this->sqlType; - } - - /** - * @param string $sqlType The sqlType to set. - */ - public function setSqlType($sqlType) - { - $this->sqlType = $sqlType; - } - - /** - * Replaces the SQL type if the new value is not null. - * @param string $sqlType The native SQL type to use for this domain. - */ - public function replaceSqlType($sqlType) - { - if ($sqlType !== null) { - $this->sqlType = $sqlType; - } - } - - /** - * Return the size and scale in brackets for use in an sql schema. - * - * @return string Size and scale or an empty String if there are no values - * available. - */ - public function printSize() - { - if ($this->size !== null && $this->scale !== null) { - return '(' . $this->size . ',' . $this->scale . ')'; - } elseif ($this->size !== null) { - return '(' . $this->size . ')'; - } else { - return ""; - } - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $domainNode = $node->appendChild($doc->createElement('domain')); - $domainNode->setAttribute('type', $this->getType()); - $domainNode->setAttribute('name', $this->getName()); - - if ($this->sqlType !== $this->getType()) { - $domainNode->setAttribute('sqlType', $this->sqlType); - } - - $def = $this->getDefaultValue(); - if ($def) { - if ($def->isExpression()) { - $domainNode->setAttribute('defaultExpr', $def->getValue()); - } else { - $domainNode->setAttribute('defaultValue', $def->getValue()); - } - } - - if ($this->size) { - $domainNode->setAttribute('size', $this->size); - } - - if ($this->scale) { - $domainNode->setAttribute('scale', $this->scale); - } - - if ($this->description) { - $domainNode->setAttribute('description', $this->description); - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/model/ForeignKey.php b/airtime_mvc/library/propel/generator/lib/model/ForeignKey.php deleted file mode 100644 index 75b11584e..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/ForeignKey.php +++ /dev/null @@ -1,509 +0,0 @@ - - * @author Fedor - * @author Daniel Rall - * @version $Revision: 1778 $ - * @package propel.generator.model - */ -class ForeignKey extends XMLElement -{ - - protected $foreignTableName; - protected $name; - protected $phpName; - protected $refPhpName; - protected $defaultJoin; - protected $onUpdate; - protected $onDelete; - protected $parentTable; - protected $localColumns = array(); - protected $foreignColumns = array(); - - // the uppercase equivalent of the onDelete/onUpdate values in the dtd - const NONE = ""; // No "ON [ DELETE | UPDATE]" behaviour specified. - const NOACTION = "NO ACTION"; - const CASCADE = "CASCADE"; - const RESTRICT = "RESTRICT"; - const SETDEFAULT = "SET DEFAULT"; - const SETNULL = "SET NULL"; - - /** - * Constructs a new ForeignKey object. - * - * @param string $name - */ - public function __construct($name=null) - { - $this->name = $name; - } - - /** - * Sets up the ForeignKey object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->foreignTableName = $this->getTable()->getDatabase()->getTablePrefix() . $this->getAttribute("foreignTable"); - $this->name = $this->getAttribute("name"); - $this->phpName = $this->getAttribute("phpName"); - $this->refPhpName = $this->getAttribute("refPhpName"); - $this->defaultJoin = $this->getAttribute('defaultJoin'); - $this->onUpdate = $this->normalizeFKey($this->getAttribute("onUpdate")); - $this->onDelete = $this->normalizeFKey($this->getAttribute("onDelete")); - } - - /** - * normalizes the input of onDelete, onUpdate attributes - */ - private function normalizeFKey($attrib) - { - if ($attrib === null || strtoupper($attrib) == "NONE") { - $attrib = self::NONE; - } - $attrib = strtoupper($attrib); - if ($attrib == "SETNULL") { - $attrib = self::SETNULL; - } - return $attrib; - } - - /** - * returns whether or not the onUpdate attribute is set - */ - public function hasOnUpdate() - { - return ($this->onUpdate !== self::NONE); - } - - /** - * returns whether or not the onDelete attribute is set - */ - public function hasOnDelete() - { - return ($this->onDelete !== self::NONE); - } - - /** - * returns the onUpdate attribute - * @return string - */ - public function getOnUpdate() - { - return $this->onUpdate; - } - - /** - * Returns the onDelete attribute - * @return string - */ - public function getOnDelete() - { - return $this->onDelete; - } - - /** - * sets the onDelete attribute - */ - public function setOnDelete($value) - { - $this->onDelete = $this->normalizeFKey($value); - } - - /** - * sets the onUpdate attribute - */ - public function setOnUpdate($value) - { - $this->onUpdate = $this->normalizeFKey($value); - } - - /** - * Returns the name attribute. - */ - public function getName() - { - return $this->name; - } - - /** - * Sets the name attribute. - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Gets the phpName for this foreign key (if any). - * @return string - */ - public function getPhpName() - { - return $this->phpName; - } - - /** - * Sets a phpName to use for this foreign key. - * @param string $name - */ - public function setPhpName($name) - { - $this->phpName = $name; - } - - /** - * Gets the refPhpName for this foreign key (if any). - * @return string - */ - public function getRefPhpName() - { - return $this->refPhpName; - } - - /** - * Sets a refPhpName to use for this foreign key. - * @param string $name - */ - public function setRefPhpName($name) - { - $this->refPhpName = $name; - } - - /** - * Gets the defaultJoin for this foreign key (if any). - * @return string - */ - public function getDefaultJoin() - { - return $this->defaultJoin; - } - - /** - * Sets a defaultJoin to use for this foreign key. - * @param string $name - */ - public function setDefaultJoin($defaultJoin) - { - $this->defaultJoin = $defaultJoin; - } - - /** - * Get the foreignTableName of the FK - */ - public function getForeignTableName() - { - return $this->foreignTableName; - } - - /** - * Set the foreignTableName of the FK - */ - public function setForeignTableName($tableName) - { - $this->foreignTableName = $tableName; - } - - /** - * Gets the resolved foreign Table model object. - * @return Table - */ - public function getForeignTable() - { - return $this->getTable()->getDatabase()->getTable($this->getForeignTableName()); - } - - /** - * Set the parent Table of the foreign key - */ - public function setTable(Table $parent) - { - $this->parentTable = $parent; - } - - /** - * Get the parent Table of the foreign key - */ - public function getTable() - { - return $this->parentTable; - } - - /** - * Returns the Name of the table the foreign key is in - */ - public function getTableName() - { - return $this->parentTable->getName(); - } - - /** - * Adds a new reference entry to the foreign key. - */ - public function addReference($p1, $p2 = null) - { - if (is_array($p1)) { - $this->addReference(@$p1["local"], @$p1["foreign"]); - } else { - if ($p1 instanceof Column) { - $p1 = $p1->getName(); - } - if ($p2 instanceof Column) { - $p2 = $p2->getName(); - } - $this->localColumns[] = $p1; - $this->foreignColumns[] = $p2; - } - } - - /** - * Clear the references of this foreign key - */ - public function clearReferences() - { - $this->localColumns[] = array(); - $this->foreignColumns[] = array(); - } - - /** - * Return a comma delimited string of local column names - * @deprecated because Column::makeList() is deprecated; use the array-returning getLocalColumns() and DDLBuilder->getColumnList() instead instead. - */ - public function getLocalColumnNames() - { - return Column::makeList($this->getLocalColumns(), $this->getTable()->getDatabase()->getPlatform()); - } - - /** - * Return a comma delimited string of foreign column names - * @deprecated because Column::makeList() is deprecated; use the array-returning getForeignColumns() and DDLBuilder->getColumnList() instead instead. - */ - public function getForeignColumnNames() - { - return Column::makeList($this->getForeignColumns(), $this->getTable()->getDatabase()->getPlatform()); - } - - /** - * Return an array of local column names. - * @return array string[] - */ - public function getLocalColumns() - { - return $this->localColumns; - } - - /** - * Utility method to get local column to foreign column - * mapping for this foreign key. - */ - public function getLocalForeignMapping() - { - $h = array(); - for ($i=0, $size=count($this->localColumns); $i < $size; $i++) { - $h[$this->localColumns[$i]] = $this->foreignColumns[$i]; - } - return $h; - } - - /** - * Utility method to get local column to foreign column - * mapping for this foreign key. - */ - public function getForeignLocalMapping() - { - $h = array(); - for ($i=0, $size=count($this->localColumns); $i < $size; $i++) { - $h[$this->foreignColumns[$i]] = $this->localColumns[$i]; - } - return $h; - } - - /** - * Utility method to get local and foreign column objects - * mapping for this foreign key. - */ - public function getColumnObjectsMapping() - { - $mapping = array(); - $localTable = $this->getTable(); - $foreignTable = $this->getForeignTable(); - for ($i=0, $size=count($this->localColumns); $i < $size; $i++) { - $mapping[]= array( - 'local' => $localTable->getColumn($this->localColumns[$i]), - 'foreign' => $foreignTable->getColumn($this->foreignColumns[$i]), - ); - } - return $mapping; - } - - /** - * Get the foreign column mapped to specified local column. - * @return string Column name. - */ - public function getMappedForeignColumn($local) - { - $m = $this->getLocalForeignMapping(); - if (isset($m[$local])) { - return $m[$local]; - } - return null; - } - - /** - * Get the local column mapped to specified foreign column. - * @return string Column name. - */ - public function getMappedLocalColumn($foreign) - { - $m = $this->getForeignLocalMapping(); - if (isset($m[$foreign])) { - return $m[$foreign]; - } - return null; - } - - /** - * Return an array of foreign column objects. - * @return array Column[] - */ - public function getForeignColumns() - { - return $this->foreignColumns; - } - - /** - * Whether this foreign key uses a required column, or a list or required columns. - * - * @return boolean - */ - public function isLocalColumnsRequired() - { - foreach ($this->getLocalColumns() as $columnName) { - if (!$this->getTable()->getColumn($columnName)->isNotNull()) { - return false; - } - } - return true; - } - - /** - * Whether this foreign key is also the primary key of the local table. - * - * @return boolean - */ - public function isLocalPrimaryKey() - { - $localCols = $this->getLocalColumns(); - - $localPKColumnObjs = $this->getTable()->getPrimaryKey(); - - $localPKCols = array(); - foreach ($localPKColumnObjs as $lPKCol) { - $localPKCols[] = $lPKCol->getName(); - } - - return (!array_diff($localPKCols, $localCols)); - } - - /** - * Whether this foreign key is matched by an invertes foreign key (on foreign table). - * - * This is to prevent duplicate columns being generated for a 1:1 relationship that is represented - * by foreign keys on both tables. I don't know if that's good practice ... but hell, why not - * support it. - * - * @param ForeignKey $fk - * @return boolean - * @link http://propel.phpdb.org/trac/ticket/549 - */ - public function isMatchedByInverseFK() - { - return (bool) $this->getInverseFK(); - } - - public function getInverseFK() - { - $foreignTable = $this->getForeignTable(); - $map = $this->getForeignLocalMapping(); - - foreach ($foreignTable->getForeignKeys() as $refFK) { - $fkMap = $refFK->getLocalForeignMapping(); - if ( ($refFK->getTableName() == $this->getTableName()) && ($map == $fkMap) ) { // compares keys and values, but doesn't care about order, included check to make sure it's the same table (fixes #679) - return $refFK; - } - } - } - - /** - * Get the other foreign keys starting on the same table - * Used in many-to-many relationships - * - * @return ForeignKey - */ - public function getOtherFks() - { - $fks = array(); - foreach ($this->getTable()->getForeignKeys() as $fk) { - if ($fk !== $this) { - $fks[]= $fk; - } - } - return $fks; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $fkNode = $node->appendChild($doc->createElement('foreign-key')); - - $fkNode->setAttribute('foreignTable', $this->getForeignTableName()); - $fkNode->setAttribute('name', $this->getName()); - - if ($this->getPhpName()) { - $fkNode->setAttribute('phpName', $this->getPhpName()); - } - - if ($this->getRefPhpName()) { - $fkNode->setAttribute('refPhpName', $this->getRefPhpName()); - } - - if ($this->getDefaultJoin()) { - $fkNode->setAttribute('defaultJoin', $this->getDefaultJoin()); - } - - if ($this->getOnDelete()) { - $fkNode->setAttribute('onDelete', $this->getOnDelete()); - } - - if ($this->getOnUpdate()) { - $fkNode->setAttribute('onUpdate', $this->getOnUpdate()); - } - - for ($i=0, $size=count($this->localColumns); $i < $size; $i++) { - $refNode = $fkNode->appendChild($doc->createElement('reference')); - $refNode->setAttribute('local', $this->localColumns[$i]); - $refNode->setAttribute('foreign', $this->foreignColumns[$i]); - } - - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($fkNode); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/IDMethod.php b/airtime_mvc/library/propel/generator/lib/model/IDMethod.php deleted file mode 100644 index 469ddfd85..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/IDMethod.php +++ /dev/null @@ -1,35 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -interface IDMethod -{ - - /** - * Key generation via database-specific ID method - * (i.e. auto-increment for MySQL, sequence for Oracle, etc.). - */ - const NATIVE = "native"; - - /** - * No RDBMS key generation (keys may be generated by the - * application). - */ - const NO_ID_METHOD = "none"; - -} diff --git a/airtime_mvc/library/propel/generator/lib/model/IdMethodParameter.php b/airtime_mvc/library/propel/generator/lib/model/IdMethodParameter.php deleted file mode 100644 index f9f1eb60c..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/IdMethodParameter.php +++ /dev/null @@ -1,108 +0,0 @@ - (Propel) - * @author John McNally (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class IdMethodParameter extends XMLElement -{ - - private $name; - private $value; - private $parentTable; - - /** - * Sets up the IdMethodParameter object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->name = $this->getAttribute("name"); - $this->value = $this->getAttribute("value"); - } - - /** - * Get the parameter name - */ - public function getName() - { - return $this->name; - } - - /** - * Set the parameter name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Get the parameter value - */ - public function getValue() - { - return $this->value; - } - - /** - * Set the parameter value - */ - public function setValue($value) - { - $this->value = $value; - } - - /** - * Set the parent Table of the id method - */ - public function setTable(Table $parent) - { - $this->parentTable = $parent; - } - - /** - * Get the parent Table of the id method - */ - public function getTable() - { - return $this->parentTable; - } - - /** - * Returns the Name of the table the id method is in - */ - public function getTableName() - { - return $this->parentTable->getName(); - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $paramNode = $node->appendChild($doc->createElement('id-method-parameter')); - if ($this->getName()) { - $paramNode->setAttribute('name', $this->getName()); - } - $paramNode->setAttribute('value', $this->getValue()); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Index.php b/airtime_mvc/library/propel/generator/lib/model/Index.php deleted file mode 100644 index 3e6add9a4..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Index.php +++ /dev/null @@ -1,285 +0,0 @@ - - * @author Daniel Rall - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Index extends XMLElement -{ - - /** enables debug output */ - const DEBUG = false; - - private $indexName; - private $parentTable; - - /** @var array string[] */ - private $indexColumns; - - /** @var array */ - private $indexColumnSizes = array(); - - /** - * Creates a new Index instance. - * - * @param string $name - */ - public function __construct($name=null) - { - $this->indexName = $name; - } - - private function createName() - { - $table = $this->getTable(); - $inputs = array(); - $inputs[] = $table->getDatabase(); - $inputs[] = $table->getName(); - if ($this->isUnique()) { - $inputs[] = "U"; - } else { - $inputs[] = "I"; - } - // ASSUMPTION: This Index not yet added to the list. - if ($this->isUnique()) { - $inputs[] = count($table->getUnices()) + 1; - } else { - $inputs[] = count($table->getIndices()) + 1; - } - - $this->indexName = NameFactory::generateName( - NameFactory::CONSTRAINT_GENERATOR, $inputs); - } - - /** - * Sets up the Index object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->indexName = $this->getAttribute("name"); - } - - /** - * @see #isUnique() - * @deprecated Use isUnique() instead. - */ - public function getIsUnique() - { - return $this->isUnique(); - } - - /** - * Returns the uniqueness of this index. - */ - public function isUnique() - { - return false; - } - - /** - * @see #getName() - * @deprecated Use getName() instead. - */ - public function getIndexName() - { - return $this->getName(); - } - - /** - * Gets the name of this index. - */ - public function getName() - { - if ($this->indexName === null) { - try { - // generate an index name if we don't have a supplied one - $this->createName(); - } catch (EngineException $e) { - // still no name - } - } - return substr($this->indexName, 0, $this->getTable()->getDatabase()->getPlatform()->getMaxColumnNameLength()); - } - - /** - * @see #setName(String name) - * @deprecated Use setName(String name) instead. - */ - public function setIndexName($name) - { - $this->setName($name); - } - - /** - * Set the name of this index. - */ - public function setName($name) - { - $this->indexName = $name; - } - - /** - * Set the parent Table of the index - */ - public function setTable(Table $parent) - { - $this->parentTable = $parent; - } - - /** - * Get the parent Table of the index - */ - public function getTable() - { - return $this->parentTable; - } - - /** - * Returns the Name of the table the index is in - */ - public function getTableName() - { - return $this->parentTable->getName(); - } - - /** - * Adds a new column to an index. - * @param mixed $data Column or attributes from XML. - */ - public function addColumn($data) - { - if ($data instanceof Column) { - $column = $data; - $this->indexColumns[] = $column->getName(); - if ($column->getSize()) { - $this->indexColumnSizes[$column->getName()] = $column->getSize(); - } - } else { - $attrib = $data; - $name = $attrib["name"]; - $this->indexColumns[] = $name; - if (isset($attrib["size"])) { - $this->indexColumnSizes[$name] = $attrib["size"]; - } - } - } - - /** - * Sets array of columns to use for index. - * - * @param array $indexColumns Column[] - */ - public function setColumns(array $indexColumns) - { - $this->indexColumns = array(); - $this->indexColumnSizes = array(); - foreach ($indexColumns as $col) { - $this->addColumn($col); - } - } - - /** - * Whether there is a size for the specified column. - * @param string $name - * @return boolean - */ - public function hasColumnSize($name) - { - return isset($this->indexColumnSizes[$name]); - } - - /** - * Returns the size for the specified column, if given. - * @param string $name - * @return numeric The size or NULL - */ - public function getColumnSize($name) - { - if (isset($this->indexColumnSizes[$name])) { - return $this->indexColumnSizes[$name]; - } - return null; // just to be explicit - } - - /** - * @see #getColumnList() - * @deprecated Use getColumnList() instead (which is not deprecated too!) - */ - public function getIndexColumnList() - { - return $this->getColumnList(); - } - - /** - * Return a comma delimited string of the columns which compose this index. - * @deprecated because Column::makeList() is deprecated; use the array-returning getColumns() and DDLBuilder->getColumnList() instead instead. - */ - public function getColumnList() - { - return Column::makeList($this->getColumns(), $this->getTable()->getDatabase()->getPlatform()); - } - - /** - * @see #getColumns() - * @deprecated Use getColumns() instead. - */ - public function getIndexColumns() - { - return $this->getColumns(); - } - - - /** - * Check whether the index has columns. - * @return boolean - */ - public function hasColumns() - { - return count($this->indexColumns) > 0; - } - - /** - * Return the list of local columns. You should not edit this list. - * @return array string[] - */ - public function getColumns() - { - return $this->indexColumns; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $idxNode = $node->appendChild($doc->createElement('index')); - $idxNode->setAttribute('name', $this->getName()); - - foreach ($this->indexColumns as $colname) { - $idxColNode = $idxNode->appendChild($doc->createElement('index-column')); - $idxColNode->setAttribute('name', $colname); - } - - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($idxNode); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Inheritance.php b/airtime_mvc/library/propel/generator/lib/model/Inheritance.php deleted file mode 100644 index d5dc0336a..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Inheritance.php +++ /dev/null @@ -1,147 +0,0 @@ - (Propel) - * @author John McNally (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Inheritance extends XMLElement -{ - - private $key; - private $className; - private $pkg; - private $ancestor; - private $parent; - - /** - * Sets up the Inheritance object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->key = $this->getAttribute("key"); - $this->className = $this->getAttribute("class"); - $this->pkg = $this->getAttribute("package"); - $this->ancestor = $this->getAttribute("extends"); - } - - /** - * Get the value of key. - * @return value of key. - */ - public function getKey() - { - return $this->key; - } - - /** - * Set the value of key. - * @param v Value to assign to key. - */ - public function setKey($v) - { - $this->key = $v; - } - - /** - * Get the value of parent. - * @return value of parent. - */ - public function getColumn() - { - return $this->parent; - } - - /** - * Set the value of parent. - * @param v Value to assign to parent. - */ - public function setColumn(Column $v) - { - $this->parent = $v; - } - - /** - * Get the value of className. - * @return value of className. - */ - public function getClassName() - { - return $this->className; - } - - /** - * Set the value of className. - * @param v Value to assign to className. - */ - public function setClassName($v) - { - $this->className = $v; - } - - /** - * Get the value of package. - * @return value of package. - */ - public function getPackage() - { - return $this->pkg; - } - - /** - * Set the value of package. - * @param v Value to assign to package. - */ - public function setPackage($v) - { - $this->pkg = $v; - } - - /** - * Get the value of ancestor. - * @return value of ancestor. - */ - public function getAncestor() - { - return $this->ancestor; - } - - /** - * Set the value of ancestor. - * @param v Value to assign to ancestor. - */ - public function setAncestor($v) - { - $this->ancestor = $v; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $inherNode = $node->appendChild($doc->createElement('inheritance')); - $inherNode->setAttribute('key', $this->key); - $inherNode->setAttribute('class', $this->className); - - if ($this->ancestor !== null) { - $inherNode->setAttribute('extends', $this->ancestor); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/NameFactory.php b/airtime_mvc/library/propel/generator/lib/model/NameFactory.php deleted file mode 100644 index dc78531eb..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/NameFactory.php +++ /dev/null @@ -1,77 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class NameFactory -{ - - /** - * The class name of the PHP name generator. - */ - const PHP_GENERATOR = 'PhpNameGenerator'; - - /** - * The fully qualified class name of the constraint name generator. - */ - const CONSTRAINT_GENERATOR = 'ConstraintNameGenerator'; - - /** - * The single instance of this class. - */ - private static $instance; - - /** - * The cache of NameGenerator algorithms in use for - * name generation, keyed by fully qualified class name. - */ - private static $algorithms = array(); - - /** - * Factory method which retrieves an instance of the named generator. - * - * @param name The fully qualified class name of the name - * generation algorithm to retrieve. - */ - protected static function getAlgorithm($name) - { - if (!isset(self::$algorithms[$name])) { - self::$algorithms[$name] = new $name(); - } - return self::$algorithms[$name]; - } - - /** - * Given a list of String objects, implements an - * algorithm which produces a name. - * - * @param string $algorithmName The fully qualified class name of the {@link NameGenerator} - * implementation to use to generate names. - * @param array $inputs Inputs used to generate a name. - * @return The generated name. - * @throws EngineException - */ - public static function generateName($algorithmName, $inputs) - { - $algorithm = self::getAlgorithm($algorithmName); - return $algorithm->generateName($inputs); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/NameGenerator.php b/airtime_mvc/library/propel/generator/lib/model/NameGenerator.php deleted file mode 100644 index 78b9077c2..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/NameGenerator.php +++ /dev/null @@ -1,73 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @author Byron Foster (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -interface NameGenerator -{ - - /** - * The character used by most implementations as the separator - * between name elements. - */ - const STD_SEPARATOR_CHAR = '_'; - - /** - * Traditional method for converting schema table and column names - * to PHP names. The CONV_METHOD_XXX constants - * define how names for columns and tables in the database schema - * will be converted to PHP source names. - * - * @see PhpNameGenerator::underscoreMethod() - */ - const CONV_METHOD_UNDERSCORE = "underscore"; - - /** - * Heavier method for converting schema table and column names - * to PHP names. Similar to {@link #CONV_METHOD_UNDERSCORE} but - * this one will pass only letters and numbers through and will - * use as separator any character that is not a letter or a number - * inside the string to be converted. The CONV_METHOD_XXX - * constants define how names for columns and tales in the - * database schema will be converted to PHP source names. - */ - const CONV_METHOD_CLEAN = "clean"; - - /** - * Similar to {@link #CONV_METHOD_UNDERSCORE} except nothing is - * converted to lowercase. - * - * @see PhpNameGenerator::phpnameMethod() - */ - const CONV_METHOD_PHPNAME = "phpname"; - - /** - * Specifies no modification when converting from a schema column - * or table name to a PHP name. - */ - const CONV_METHOD_NOCHANGE = "nochange"; - - /** - * Given a list of String objects, implements an - * algorithm which produces a name. - * - * @param inputs Inputs used to generate a name. - * @return The generated name. - * @throws EngineException - */ - public function generateName($inputs); -} diff --git a/airtime_mvc/library/propel/generator/lib/model/PhpNameGenerator.php b/airtime_mvc/library/propel/generator/lib/model/PhpNameGenerator.php deleted file mode 100644 index fc777ce02..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/PhpNameGenerator.php +++ /dev/null @@ -1,167 +0,0 @@ -NameGenerator implementation for PHP-esque names. - * - * @author Hans Lellelid (Propel) - * @author Daniel Rall (Torque) - * @author Byron Foster (Torque) - * @author Bernd Goldschmidt - * @version $Revision: 1793 $ - * @package propel.generator.model - */ -class PhpNameGenerator implements NameGenerator -{ - - /** - * inputs should consist of two (three) elements, the - * original name of the database element and the method for - * generating the name. - * The optional third element may contain a prefix that will be - * stript from name prior to generate the resulting name. - * There are currently three methods: - * CONV_METHOD_NOCHANGE - xml names are converted - * directly to php names without modification. - * CONV_METHOD_UNDERSCORE will capitalize the first - * letter, remove underscores, and capitalize each letter before - * an underscore. All other letters are lowercased. "phpname" - * works the same as the CONV_METHOD_PHPNAME method - * but will not lowercase any characters. - * - * @param inputs list expected to contain two (optional: three) parameters, - * element 0 contains name to convert, element 1 contains method for conversion, - * optional element 2 contains prefix to be striped from name - * @return The generated name. - * @see NameGenerator - */ - public function generateName($inputs) - { - $schemaName = $inputs[0]; - $method = $inputs[1]; - - if (count($inputs)>2) { - $prefix = $inputs[2]; - if ($prefix != '' && substr($schemaName, 0, strlen($prefix)) == $prefix) { - $schemaName = substr($schemaName, strlen($prefix)); - } - } - - $phpName = null; - - switch ($method) { - case self::CONV_METHOD_CLEAN: - $phpName = $this->cleanMethod($schemaName); - break; - case self::CONV_METHOD_PHPNAME: - $phpName = $this->phpnameMethod($schemaName); - break; - case self::CONV_METHOD_NOCHANGE: - $phpName = $this->nochangeMethod($schemaName); - break; - case self::CONV_METHOD_UNDERSCORE: - default: - $phpName = $this->underscoreMethod($schemaName); - } - - return $phpName; - } - - /** - * Converts a database schema name to php object name by Camelization. - * Removes STD_SEPARATOR_CHAR, capitilizes first letter - * of name and each letter after the STD_SEPERATOR, - * converts the rest of the letters to lowercase. - * - * This method should be named camelizeMethod() for clarity - * - * my_CLASS_name -> MyClassName - * - * @param string $schemaName name to be converted. - * @return string Converted name. - * @see NameGenerator - * @see #underscoreMethod() - */ - protected function underscoreMethod($schemaName) - { - $name = ""; - $tok = strtok($schemaName, self::STD_SEPARATOR_CHAR); - while ($tok) { - $name .= ucfirst(strtolower($tok)); - $tok = strtok(self::STD_SEPARATOR_CHAR); - } - return $name; - } - - /** - * Converts a database schema name to php object name. Removes - * any character that is not a letter or a number and capitilizes - * first letter of the name, the first letter of each alphanumeric - * block and converts the rest of the letters to lowercase. - * - * T$NAMA$RFO_max => TNamaRfoMax - * - * @param string $schemaName name to be converted. - * @return string Converted name. - * @see NameGenerator - * @see #underscoreMethod() - */ - protected function cleanMethod($schemaName) - { - $name = ""; - $regexp = '/([a-z0-9]+)/i'; - $matches = array(); - if (preg_match_all($regexp, $schemaName, $matches)) { - foreach($matches[1] AS $tok) { - $name .= ucfirst(strtolower($tok)); - } - } else { - return $schemaName; - } - return $name; - } - - /** - * Converts a database schema name to php object name. Operates - * same as underscoreMethod but does not convert anything to - * lowercase. - * - * my_CLASS_name -> MyCLASSName - * - * @param string $schemaName name to be converted. - * @return string Converted name. - * @see NameGenerator - * @see #underscoreMethod(String) - */ - protected function phpnameMethod($schemaName) - { - $name = ""; - $tok = strtok($schemaName, self::STD_SEPARATOR_CHAR); - while ($tok !== false) { - $name .= ucfirst($tok); - $tok = strtok(self::STD_SEPARATOR_CHAR); - } - return $name; - } - - /** - * Converts a database schema name to PHP object name. In this - * case no conversion is made. - * - * @param string $name name to be converted. - * @return string The name parameter, unchanged. - */ - protected function nochangeMethod($name) - { - return $name; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/PropelTypes.php b/airtime_mvc/library/propel/generator/lib/model/PropelTypes.php deleted file mode 100644 index 8a037f553..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/PropelTypes.php +++ /dev/null @@ -1,343 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class PropelTypes -{ - - const CHAR = "CHAR"; - const VARCHAR = "VARCHAR"; - const LONGVARCHAR = "LONGVARCHAR"; - const CLOB = "CLOB"; - const CLOB_EMU = "CLOB_EMU"; - const NUMERIC = "NUMERIC"; - const DECIMAL = "DECIMAL"; - const TINYINT = "TINYINT"; - const SMALLINT = "SMALLINT"; - const INTEGER = "INTEGER"; - const BIGINT = "BIGINT"; - const REAL = "REAL"; - const FLOAT = "FLOAT"; - const DOUBLE = "DOUBLE"; - const BINARY = "BINARY"; - const VARBINARY = "VARBINARY"; - const LONGVARBINARY = "LONGVARBINARY"; - const BLOB = "BLOB"; - const DATE = "DATE"; - const TIME = "TIME"; - const TIMESTAMP = "TIMESTAMP"; - const BU_DATE = "BU_DATE"; - const BU_TIMESTAMP = "BU_TIMESTAMP"; - const BOOLEAN = "BOOLEAN"; - const BOOLEAN_EMU = "BOOLEAN_EMU"; - - private static $TEXT_TYPES = array( - self::CHAR, self::VARCHAR, self::LONGVARCHAR, self::CLOB, self::DATE, self::TIME, self::TIMESTAMP, self::BU_DATE, self::BU_TIMESTAMP - ); - - private static $LOB_TYPES = array( - self::VARBINARY, self::LONGVARBINARY, self::BLOB - ); - - private static $TEMPORAL_TYPES = array( - self::DATE, self::TIME, self::TIMESTAMP, self::BU_DATE, self::BU_TIMESTAMP - ); - - private static $NUMERIC_TYPES = array( - self::SMALLINT, self::TINYINT, self::INTEGER, self::BIGINT, self::FLOAT, self::DOUBLE, self::NUMERIC, self::DECIMAL, self::REAL - ); - - private static $BOOLEAN_TYPES = array( - self::BOOLEAN, self::BOOLEAN_EMU - ); - - const CHAR_NATIVE_TYPE = "string"; - const VARCHAR_NATIVE_TYPE = "string"; - const LONGVARCHAR_NATIVE_TYPE = "string"; - const CLOB_NATIVE_TYPE = "string"; - const CLOB_EMU_NATIVE_TYPE = "resource"; - const NUMERIC_NATIVE_TYPE = "string"; - const DECIMAL_NATIVE_TYPE = "string"; - const TINYINT_NATIVE_TYPE = "int"; - const SMALLINT_NATIVE_TYPE = "int"; - const INTEGER_NATIVE_TYPE = "int"; - const BIGINT_NATIVE_TYPE = "string"; - const REAL_NATIVE_TYPE = "double"; - const FLOAT_NATIVE_TYPE = "double"; - const DOUBLE_NATIVE_TYPE = "double"; - const BINARY_NATIVE_TYPE = "string"; - const VARBINARY_NATIVE_TYPE = "string"; - const LONGVARBINARY_NATIVE_TYPE = "string"; - const BLOB_NATIVE_TYPE = "resource"; - const BU_DATE_NATIVE_TYPE = "string"; - const DATE_NATIVE_TYPE = "string"; - const TIME_NATIVE_TYPE = "string"; - const TIMESTAMP_NATIVE_TYPE = "string"; - const BU_TIMESTAMP_NATIVE_TYPE = "string"; - const BOOLEAN_NATIVE_TYPE = "boolean"; - const BOOLEAN_EMU_NATIVE_TYPE = "boolean"; - - /** - * Mapping between Propel types and PHP native types. - * - * @var array - */ - private static $propelToPHPNativeMap = array( - self::CHAR => self::CHAR_NATIVE_TYPE, - self::VARCHAR => self::VARCHAR_NATIVE_TYPE, - self::LONGVARCHAR => self::LONGVARCHAR_NATIVE_TYPE, - self::CLOB => self::CLOB_NATIVE_TYPE, - self::CLOB_EMU => self::CLOB_EMU_NATIVE_TYPE, - self::NUMERIC => self::NUMERIC_NATIVE_TYPE, - self::DECIMAL => self::DECIMAL_NATIVE_TYPE, - self::TINYINT => self::TINYINT_NATIVE_TYPE, - self::SMALLINT => self::SMALLINT_NATIVE_TYPE, - self::INTEGER => self::INTEGER_NATIVE_TYPE, - self::BIGINT => self::BIGINT_NATIVE_TYPE, - self::REAL => self::REAL_NATIVE_TYPE, - self::FLOAT => self::FLOAT_NATIVE_TYPE, - self::DOUBLE => self::DOUBLE_NATIVE_TYPE, - self::BINARY => self::BINARY_NATIVE_TYPE, - self::VARBINARY => self::VARBINARY_NATIVE_TYPE, - self::LONGVARBINARY => self::LONGVARBINARY_NATIVE_TYPE, - self::BLOB => self::BLOB_NATIVE_TYPE, - self::DATE => self::DATE_NATIVE_TYPE, - self::BU_DATE => self::BU_DATE_NATIVE_TYPE, - self::TIME => self::TIME_NATIVE_TYPE, - self::TIMESTAMP => self::TIMESTAMP_NATIVE_TYPE, - self::BU_TIMESTAMP => self::BU_TIMESTAMP_NATIVE_TYPE, - self::BOOLEAN => self::BOOLEAN_NATIVE_TYPE, - self::BOOLEAN_EMU => self::BOOLEAN_EMU_NATIVE_TYPE, - ); - - /** - * Mapping between Propel types and Creole types (for rev-eng task) - * - * @var array - */ - private static $propelTypeToCreoleTypeMap = array( - - self::CHAR => self::CHAR, - self::VARCHAR => self::VARCHAR, - self::LONGVARCHAR => self::LONGVARCHAR, - self::CLOB => self::CLOB, - self::NUMERIC => self::NUMERIC, - self::DECIMAL => self::DECIMAL, - self::TINYINT => self::TINYINT, - self::SMALLINT => self::SMALLINT, - self::INTEGER => self::INTEGER, - self::BIGINT => self::BIGINT, - self::REAL => self::REAL, - self::FLOAT => self::FLOAT, - self::DOUBLE => self::DOUBLE, - self::BINARY => self::BINARY, - self::VARBINARY => self::VARBINARY, - self::LONGVARBINARY => self::LONGVARBINARY, - self::BLOB => self::BLOB, - self::DATE => self::DATE, - self::TIME => self::TIME, - self::TIMESTAMP => self::TIMESTAMP, - self::BOOLEAN => self::BOOLEAN, - self::BOOLEAN_EMU => self::BOOLEAN_EMU, - - // These are pre-epoch dates, which we need to map to String type - // since they cannot be properly handled using strtotime() -- or even numeric - // timestamps on Windows. - self::BU_DATE => self::VARCHAR, - self::BU_TIMESTAMP => self::VARCHAR, - - ); - - /** - * Mapping between Propel types and PDO type contants (for prepared statement setting). - * - * @var array - */ - private static $propelTypeToPDOTypeMap = array( - self::CHAR => PDO::PARAM_STR, - self::VARCHAR => PDO::PARAM_STR, - self::LONGVARCHAR => PDO::PARAM_STR, - self::CLOB => PDO::PARAM_STR, - self::CLOB_EMU => PDO::PARAM_STR, - self::NUMERIC => PDO::PARAM_INT, - self::DECIMAL => PDO::PARAM_STR, - self::TINYINT => PDO::PARAM_INT, - self::SMALLINT => PDO::PARAM_INT, - self::INTEGER => PDO::PARAM_INT, - self::BIGINT => PDO::PARAM_INT, - self::REAL => PDO::PARAM_STR, - self::FLOAT => PDO::PARAM_STR, - self::DOUBLE => PDO::PARAM_STR, - self::BINARY => PDO::PARAM_STR, - self::VARBINARY => PDO::PARAM_LOB, - self::LONGVARBINARY => PDO::PARAM_LOB, - self::BLOB => PDO::PARAM_LOB, - self::DATE => PDO::PARAM_STR, - self::TIME => PDO::PARAM_STR, - self::TIMESTAMP => PDO::PARAM_STR, - self::BOOLEAN => PDO::PARAM_BOOL, - self::BOOLEAN_EMU => PDO::PARAM_INT, - - // These are pre-epoch dates, which we need to map to String type - // since they cannot be properly handled using strtotime() -- or even numeric - // timestamps on Windows. - self::BU_DATE => PDO::PARAM_STR, - self::BU_TIMESTAMP => PDO::PARAM_STR, - ); - - /** - * Return native PHP type which corresponds to the - * Creole type provided. Use in the base object class generation. - * - * @param $propelType The Propel type name. - * @return string Name of the native PHP type - */ - public static function getPhpNative($propelType) - { - return self::$propelToPHPNativeMap[$propelType]; - } - - /** - * Returns the correct Creole type _name_ for propel added types - * - * @param $type the propel added type. - * @return string Name of the the correct Creole type (e.g. "VARCHAR"). - */ - public static function getCreoleType($type) - { - return self::$propelTypeToCreoleTypeMap[$type]; - } - - /** - * Resturns the PDO type (PDO::PARAM_* constant) value. - * @return int - */ - public static function getPDOType($type) - { - return self::$propelTypeToPDOTypeMap[$type]; - } - - /** - * Returns Propel type constant corresponding to Creole type code. - * Used but Propel Creole task. - * - * @param int $sqlType The Creole SQL type constant. - * @return string The Propel type to use or NULL if none found. - */ - public static function getPropelType($sqlType) - { - if (isset(self::$creoleToPropelTypeMap[$sqlType])) { - return self::$creoleToPropelTypeMap[$sqlType]; - } - } - - /** - * Get array of Propel types. - * - * @return array string[] - */ - public static function getPropelTypes() - { - return array_keys(self::$propelTypeToCreoleTypeMap); - } - - /** - * Whether passed type is a temporal (date/time/timestamp) type. - * - * @param string $type Propel type - * @return boolean - */ - public static function isTemporalType($type) - { - return in_array($type, self::$TEMPORAL_TYPES); - } - - /** - * Returns true if values for the type need to be quoted. - * - * @param string $type The Propel type to check. - * @return boolean True if values for the type need to be quoted. - */ - public static function isTextType($type) - { - return in_array($type, self::$TEXT_TYPES); - } - - /** - * Returns true if values for the type are numeric. - * - * @param string $type The Propel type to check. - * @return boolean True if values for the type need to be quoted. - */ - public static function isNumericType($type) - { - return in_array($type, self::$NUMERIC_TYPES); - } - - /** - * Returns true if values for the type are boolean. - * - * @param string $type The Propel type to check. - * @return boolean True if values for the type need to be quoted. - */ - public static function isBooleanType($type) - { - return in_array($type, self::$BOOLEAN_TYPES); - } - - /** - * Returns true if type is a LOB type (i.e. would be handled by Blob/Clob class). - * @param string $type Propel type to check. - * @return boolean - */ - public static function isLobType($type) - { - return in_array($type, self::$LOB_TYPES); - } - - /** - * Convenience method to indicate whether a passed-in PHP type is a primitive. - * - * @param string $phpType The PHP type to check - * @return boolean Whether the PHP type is a primitive (string, int, boolean, float) - */ - public static function isPhpPrimitiveType($phpType) - { - return in_array($phpType, array("boolean", "int", "double", "float", "string")); - } - - /** - * Convenience method to indicate whether a passed-in PHP type is a numeric primitive. - * - * @param string $phpType The PHP type to check - * @return boolean Whether the PHP type is a primitive (string, int, boolean, float) - */ - public static function isPhpPrimitiveNumericType($phpType) - { - return in_array($phpType, array("boolean", "int", "double", "float")); - } - - /** - * Convenience method to indicate whether a passed-in PHP type is an object. - * - * @param string $phpType The PHP type to check - * @return boolean Whether the PHP type is a primitive (string, int, boolean, float) - */ - public static function isPhpObjectType($phpType) - { - return (!self::isPhpPrimitiveType($phpType) && !in_array($phpType, array("resource", "array"))); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Rule.php b/airtime_mvc/library/propel/generator/lib/model/Rule.php deleted file mode 100644 index d69e4e76b..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Rule.php +++ /dev/null @@ -1,194 +0,0 @@ - (Propel) - * @author John McNally (Intake) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Rule extends XMLElement -{ - - private $name; - private $value; - private $message; - private $validator; - private $classname; - - /** - * Sets up the Rule object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->name = $this->getAttribute("name"); - $this->value = $this->getAttribute("value"); - $this->classname = $this->getAttribute("class"); - - /* - * Set some default values if they are not specified. - * This is escpecially useful for maxLength; the size - * is already known by the column and this way it is - * not necessary to manage the same size two times. - * - * Currently there is only one such supported default: - * - maxLength value = column max length - * (this default cannot be easily set at runtime w/o changing - * design of class system in undesired ways) - */ - if ($this->value === null) { - switch($this->name) { - case 'maxLength': - $this->value = $this->validator->getColumn()->getSize(); - break; - } - } - - $this->message = $this->getAttribute("message"); - } - - /** - * Sets the owning validator for this rule. - * @param Validator $validator - * @see Validator::addRule() - */ - public function setValidator(Validator $validator) - { - $this->validator = $validator; - } - - /** - * Gets the owning validator for this rule. - * @return Validator - */ - public function getValidator() - { - return $this->validator; - } - - /** - * Sets the dot-path name of class to use for rule. - * If no class is specified in XML, then a classname will - * be built based on the 'name' attrib. - * @param string $classname dot-path classname (e.g. myapp.propel.MyValidator) - */ - public function setClass($classname) - { - $this->classname = $classname; - } - - /** - * Gets the dot-path name of class to use for rule. - * If no class was specified, this method will build a default classname - * based on the 'name' attribute. E.g. 'maxLength' -> 'propel.validator.MaxLengthValidator' - * @return string dot-path classname (e.g. myapp.propel.MyValidator) - */ - public function getClass() - { - if ($this->classname === null && $this->name !== null) { - return "propel.validator." . ucfirst($this->name) . "Validator"; - } - return $this->classname; - } - - /** - * Sets the name of the validator for this rule. - * This name is used to build the classname if none was specified. - * @param string $name Validator name for this rule (e.g. "maxLength", "required"). - * @see getClass() - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Gets the name of the validator for this rule. - * @return string Validator name for this rule (e.g. "maxLength", "required"). - */ - public function getName() - { - return $this->name; - } - - /** - * Sets the value parameter for this validator rule. - * Note: not all validators need a value parameter (e.g. 'required' validator - * does not). - * @param string $value - */ - public function setValue($value) - { - $this->value = $value; - } - - /** - * Gets the value parameter for this validator rule. - * @return string - */ - public function getValue() - { - return $this->value; - } - - /** - * Sets the message that will be displayed to the user if validation fails. - * This message may be a Gettext msgid (if translation="gettext") or some other - * id for an alternative not-yet-supported translation system. It may also - * be a simple, single-language string. - * @param string $message - * @see setTranslation() - */ - public function setMessage($message) - { - $this->message = $message; - } - - /** - * Gets the message that will be displayed to the user if validation fails. - * This message may be a Gettext msgid (if translation="gettext") or some other - * id for an alternative not-yet-supported translation system. It may also - * be a simple, single-language string. - * @return string - * @see setTranslation() - */ - public function getMessage() - { - $message = str_replace('${value}', $this->getValue(), $this->message); - return $message; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $ruleNode = $node->appendChild($doc->createElement('rule')); - $ruleNode->setAttribute('name', $this->getName()); - - if ($this->getValue() !== null) { - $ruleNode->setAttribute('value', $this->getValue()); - } - - if ($this->classname !== null) { - $ruleNode->setAttribute('class', $this->getClass()); - } - - $ruleNode->setAttribute('message', $this->getMessage()); - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Table.php b/airtime_mvc/library/propel/generator/lib/model/Table.php deleted file mode 100644 index 9198e27b1..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Table.php +++ /dev/null @@ -1,1579 +0,0 @@ - (Propel) - * @author Leon Messerschmidt (Torque) - * @author Jason van Zyl (Torque) - * @author Martin Poeschl (Torque) - * @author John McNally (Torque) - * @author Daniel Rall (Torque) - * @author Byron Foster (Torque) - * @version $Revision: 1802 $ - * @package propel.generator.model - */ -class Table extends XMLElement implements IDMethod -{ - - /** - * Enables some debug printing. - */ - const DEBUG = false; - - /** - * Columns for this table. - * - * @var array Column[] - */ - private $columnList = array(); - - /** - * Validators for this table. - * - * @var array Validator[] - */ - private $validatorList = array(); - - /** - * Foreign keys for this table. - * - * @var array ForeignKey[] - */ - private $foreignKeys = array(); - - /** - * Indexes for this table. - * - * @var array Index[] - */ - private $indices = array(); - - /** - * Unique indexes for this table. - * - * @var array Unique[] - */ - private $unices = array(); - - /** - * Any parameters for the ID method (currently supports changing sequence name). - * - * @var array - */ - private $idMethodParameters = array(); - - /** - * Table name. - * - * @var string - */ - private $name; - - /** - * Table description. - * - * @var string - */ - private $description; - - /** - * phpName for the table. - * - * @var string - */ - private $phpName; - - /** - * Namespace for the generated OM. - * - * @var string - */ - protected $namespace; - - /** - * ID method for the table (e.g. IDMethod::NATIVE, IDMethod::NONE). - * - * @var string - */ - private $idMethod; - - /** - * Wether an INSERT with set PK is allowed on tables with IDMethod::NATIVE - * - * @var boolean - */ - private $allowPkInsert; - - /** - * Strategry to use for converting column name to phpName. - * - * @var string - */ - private $phpNamingMethod; - - /** - * The Database that this table belongs to. - * - * @var Database - */ - private $database; - - /** - * Foreign Keys that refer to this table. - * - * @var array ForeignKey[] - */ - private $referrers = array(); - - /** - * Names of foreign tables. - * - * @var array string[] - */ - private $foreignTableNames; - - /** - * Whether this table contains a foreign primary key. - * - * @var boolean - */ - private $containsForeignPK; - - /** - * The inheritance column for this table (if any). - * - * @var Column - */ - private $inheritanceColumn; - - /** - * Whether to skip generation of SQL for this table. - * - * @var boolean - */ - private $skipSql; - - /** - * Whether this table is "read-only". - * - * @var boolean - */ - private $readOnly; - - /** - * Whether this table should result in abstract OM classes. - * - * @var boolean - */ - private $abstractValue; - - /** - * Whether this table is an alias for another table. - * - * @var string - */ - private $alias; - - /** - * The interface that the generated "object" class should implement. - * - * @var string - */ - private $enterface; - - /** - * The package for the generated OM. - * - * @var string - */ - private $pkg; - - /** - * The base class to extend for the generated "object" class. - * - * @var string - */ - private $baseClass; - - /** - * The base peer class to extend for generated "peer" class. - * - * @var string - */ - private $basePeer; - - /** - * Map of columns by name. - * - * @var array - */ - private $columnsByName = array(); - - /** - * Map of columns by phpName. - * - * @var array - */ - private $columnsByPhpName = array(); - - /** - * Whether this table needs to use transactions in Postgres. - * - * @var string - * @deprecated - */ - private $needsTransactionInPostgres; - - /** - * Whether to perform additional indexing on this table. - * - * @var boolean - */ - private $heavyIndexing; - - /** - * Whether this table is for reference only. - * - * @var boolean - */ - private $forReferenceOnly; - - /** - * The tree mode (nested set, etc.) implemented by this table. - * - * @var string - */ - private $treeMode; - - /** - * Whether to reload the rows in this table after insert. - * - * @var boolean - */ - private $reloadOnInsert; - - /** - * Whether to reload the rows in this table after update. - * - * @var boolean - */ - private $reloadOnUpdate; - - /** - * List of behaviors registered for this table - * - * @var array - */ - protected $behaviors = array(); - - /** - * Whether this table is a cross-reference table for a many-to-many relationship - * - * @var boolean - */ - protected $isCrossRef = false; - - /** - * Constructs a table object with a name - * - * @param string $name table name - */ - public function __construct($name = null) - { - $this->name = $name; - } - - /** - * Sets up the Rule object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - public function setupObject() - { - $this->name = $this->getDatabase()->getTablePrefix() . $this->getAttribute("name"); - // retrieves the method for converting from specified name to a PHP name. - $this->phpNamingMethod = $this->getAttribute("phpNamingMethod", $this->getDatabase()->getDefaultPhpNamingMethod()); - $this->phpName = $this->getAttribute("phpName", $this->buildPhpName($this->getAttribute('name'))); - - $namespace = $this->getAttribute("namespace", ''); - $package = $this->getAttribute("package"); - if ($namespace && !$package && $this->getDatabase()->getBuildProperty('namespaceAutoPackage')) { - $package = str_replace('\\', '.', $namespace); - } - $this->namespace = $namespace; - $this->pkg = $package; - - $this->namespace = $this->getAttribute("namespace"); - $this->idMethod = $this->getAttribute("idMethod", $this->getDatabase()->getDefaultIdMethod()); - $this->allowPkInsert = $this->booleanValue($this->getAttribute("allowPkInsert")); - - - $this->skipSql = $this->booleanValue($this->getAttribute("skipSql")); - $this->readOnly = $this->booleanValue($this->getAttribute("readOnly")); - - $this->abstractValue = $this->booleanValue($this->getAttribute("abstract")); - $this->baseClass = $this->getAttribute("baseClass"); - $this->basePeer = $this->getAttribute("basePeer"); - $this->alias = $this->getAttribute("alias"); - - $this->heavyIndexing = ( $this->booleanValue($this->getAttribute("heavyIndexing")) - || ("false" !== $this->getAttribute("heavyIndexing") - && $this->getDatabase()->isHeavyIndexing() ) ); - $this->description = $this->getAttribute("description"); - $this->enterface = $this->getAttribute("interface"); // sic ('interface' is reserved word) - $this->treeMode = $this->getAttribute("treeMode"); - - $this->reloadOnInsert = $this->booleanValue($this->getAttribute("reloadOnInsert")); - $this->reloadOnUpdate = $this->booleanValue($this->getAttribute("reloadOnUpdate")); - $this->isCrossRef = $this->getAttribute("isCrossRef", false); - } - - /** - *

A hook for the SAX XML parser to call when this table has - * been fully loaded from the XML, and all nested elements have - * been processed.

- * - *

Performs heavy indexing and naming of elements which weren't - * provided with a name.

- */ - public function doFinalInitialization() - { - // Heavy indexing must wait until after all columns composing - // a table's primary key have been parsed. - if ($this->heavyIndexing) { - $this->doHeavyIndexing(); - } - - // Name any indices which are missing a name using the - // appropriate algorithm. - $this->doNaming(); - - // execute behavior table modifiers - foreach ($this->getBehaviors() as $behavior) - { - if (!$behavior->isTableModified()) { - $behavior->getTableModifier()->modifyTable(); - $behavior->setTableModified(true); - } - } - - // if idMethod is "native" and in fact there are no autoIncrement - // columns in the table, then change it to "none" - $anyAutoInc = false; - foreach ($this->getColumns() as $col) { - if ($col->isAutoIncrement()) { - $anyAutoInc = true; - } - } - if ($this->getIdMethod() === IDMethod::NATIVE && !$anyAutoInc) { - $this->setIdMethod(IDMethod::NO_ID_METHOD); - } - - // If there is no PK, then throw an error. Propel 1.3 requires primary keys. - $pk = $this->getPrimaryKey(); - if (empty($pk)) { - throw new EngineException("Table '".$this->getName()."' does not have a primary key defined. Propel requires all tables to have a primary key."); - } - - } - - /** - *

Adds extra indices for multi-part primary key columns.

- * - *

For databases like MySQL, values in a where clause much - * match key part order from the left to right. So, in the key - * definition PRIMARY KEY (FOO_ID, BAR_ID), - * FOO_ID must be the first element used in - * the where clause of the SQL query used against - * this table for the primary key index to be used. This feature - * could cause problems under MySQL with heavily indexed tables, - * as MySQL currently only supports 16 indices per table (i.e. it - * might cause too many indices to be created).

- * - *

See the - * manual for a better description of why heavy indexing is - * useful for quickly searchable database tables.

- */ - private function doHeavyIndexing() - { - if (self::DEBUG) { - print("doHeavyIndex() called on table " . $this->name."\n"); - } - - $pk = $this->getPrimaryKey(); - $size = count($pk); - - // We start at an offset of 1 because the entire column - // list is generally implicitly indexed by the fact that - // it's a primary key. - for ($i=1; $i < $size; $i++) { - $idx = new Index(); - $idx->setColumns(array_slice($pk, $i, $size)); - $this->addIndex($idx); - } - } - - /** - * Names composing objects which haven't yet been named. This - * currently consists of foreign-key and index entities. - */ - public function doNaming() { - - // Assure names are unique across all databases. - try { - for ($i=0, $size = count($this->foreignKeys); $i < $size; $i++) { - $fk = $this->foreignKeys[$i]; - $name = $fk->getName(); - if (empty($name)) { - $name = $this->acquireConstraintName("FK", $i + 1); - $fk->setName($name); - } - } - - for ($i = 0, $size = count($this->indices); $i < $size; $i++) { - $index = $this->indices[$i]; - $name = $index->getName(); - if (empty($name)) { - $name = $this->acquireConstraintName("I", $i + 1); - $index->setName($name); - } - } - - for ($i = 0, $size = count($this->unices); $i < $size; $i++) { - $index = $this->unices[$i]; - $name = $index->getName(); - if (empty($name)) { - $name = $this->acquireConstraintName("U", $i + 1); - $index->setName($name); - } - } - - // NOTE: Most RDBMSes can apparently name unique column - // constraints/indices themselves (using MySQL and Oracle - // as test cases), so we'll assume that we needn't add an - // entry to the system name list for these. - } catch (EngineException $nameAlreadyInUse) { - print $nameAlreadyInUse->getMessage() . "\n"; - print $nameAlreadyInUse->getTraceAsString(); - } - } - - /** - * Macro to a constraint name. - * - * @param nameType constraint type - * @param nbr unique number for this constraint type - * @return unique name for constraint - * @throws EngineException - */ - private function acquireConstraintName($nameType, $nbr) - { - $inputs = array(); - $inputs[] = $this->getDatabase(); - $inputs[] = $this->getName(); - $inputs[] = $nameType; - $inputs[] = $nbr; - return NameFactory::generateName(NameFactory::CONSTRAINT_GENERATOR, $inputs); - } - - /** - * Gets the value of base class for classes produced from this table. - * - * @return The base class for classes produced from this table. - */ - public function getBaseClass() - { - if ($this->isAlias() && $this->baseClass === null) { - return $this->alias; - } elseif ($this->baseClass === null) { - return $this->getDatabase()->getBaseClass(); - } else { - return $this->baseClass; - } - } - - /** - * Set the value of baseClass. - * @param v Value to assign to baseClass. - */ - public function setBaseClass($v) - { - $this->baseClass = $v; - } - - /** - * Get the value of basePeer. - * @return value of basePeer. - */ - public function getBasePeer() - { - if ($this->isAlias() && $this->basePeer === null) { - return $this->alias . "Peer"; - } elseif ($this->basePeer === null) { - return $this->getDatabase()->getBasePeer(); - } else { - return $this->basePeer; - } - } - - /** - * Set the value of basePeer. - * @param v Value to assign to basePeer. - */ - public function setBasePeer($v) - { - $this->basePeer = $v; - } - - /** - * A utility function to create a new column from attrib and add it to this - * table. - * - * @param $coldata xml attributes or Column class for the column to add - * @return the added column - */ - public function addColumn($data) - { - if ($data instanceof Column) { - $col = $data; - $col->setTable($this); - if ($col->isInheritance()) { - $this->inheritanceColumn = $col; - } - if (isset($this->columnsByName[$col->getName()])) { - throw new EngineException('Duplicate column declared: ' . $col->getName()); - } - $this->columnList[] = $col; - $this->columnsByName[$col->getName()] = $col; - $this->columnsByPhpName[$col->getPhpName()] = $col; - $col->setPosition(count($this->columnList)); - $this->needsTransactionInPostgres |= $col->requiresTransactionInPostgres(); - return $col; - } else { - $col = new Column(); - $col->setTable($this); - $col->loadFromXML($data); - return $this->addColumn($col); // call self w/ different param - } - } - - /** - * Add a validator to this table. - * - * Supports two signatures: - * - addValidator(Validator $validator) - * - addValidator(array $attribs) - * - * @param mixed $data Validator object or XML attribs (array) from element. - * @return Validator The added Validator. - * @throws EngineException - */ - public function addValidator($data) - { - if ($data instanceof Validator) { - $validator = $data; - $col = $this->getColumn($validator->getColumnName()); - if ($col == null) { - throw new EngineException("Failed adding validator to table '" . $this->getName() . - "': column '" . $validator->getColumnName() . "' does not exist !"); - } - $validator->setColumn($col); - $validator->setTable($this); - $this->validatorList[] = $validator; - return $validator; - } else { - $validator = new Validator(); - $validator->setTable($this); - $validator->loadFromXML($data); - return $this->addValidator($validator); - } - } - - /** - * A utility function to create a new foreign key - * from attrib and add it to this table. - */ - public function addForeignKey($fkdata) - { - if ($fkdata instanceof ForeignKey) { - $fk = $fkdata; - $fk->setTable($this); - $this->foreignKeys[] = $fk; - - if ($this->foreignTableNames === null) { - $this->foreignTableNames = array(); - } - if (!in_array($fk->getForeignTableName(), $this->foreignTableNames)) { - $this->foreignTableNames[] = $fk->getForeignTableName(); - } - return $fk; - } else { - $fk = new ForeignKey(); - $fk->setTable($this); - $fk->loadFromXML($fkdata); - return $this->addForeignKey($fk); - } - } - - /** - * Gets the column that subclasses of the class representing this - * table can be produced from. - * @return Column - */ - public function getChildrenColumn() - { - return $this->inheritanceColumn; - } - - /** - * Get the subclasses that can be created from this table. - * @return array string[] Class names - */ - public function getChildrenNames() - { - if ($this->inheritanceColumn === null - || !$this->inheritanceColumn->isEnumeratedClasses()) { - return null; - } - $children = $this->inheritanceColumn->getChildren(); - $names = array(); - for ($i = 0, $size=count($children); $i < $size; $i++) { - $names[] = get_class($children[$i]); - } - return $names; - } - - /** - * Adds the foreign key from another table that refers to this table. - */ - public function addReferrer(ForeignKey $fk) - { - if ($this->referrers === null) { - $this->referrers = array(); - } - $this->referrers[] = $fk; - } - - /** - * Get list of references to this table. - */ - public function getReferrers() - { - return $this->referrers; - } - - public function getCrossFks() - { - $crossFks = array(); - foreach ($this->getReferrers() as $refFK) { - if ($refFK->getTable()->getIsCrossRef()) { - foreach ($refFK->getOtherFks() as $crossFK) { - $crossFks[]= array($refFK, $crossFK); - } - } - } - return $crossFks; - } - - /** - * Set whether this table contains a foreign PK - */ - public function setContainsForeignPK($b) - { - $this->containsForeignPK = (boolean) $b; - } - - /** - * Determine if this table contains a foreign PK - */ - public function getContainsForeignPK() - { - return $this->containsForeignPK; - } - - /** - * A list of tables referenced by foreign keys in this table - */ - public function getForeignTableNames() - { - if ($this->foreignTableNames === null) { - $this->foreignTableNames = array(); - } - return $this->foreignTableNames; - } - - /** - * Return true if the column requires a transaction in Postgres - */ - public function requiresTransactionInPostgres() - { - return $this->needsTransactionInPostgres; - } - - /** - * A utility function to create a new id method parameter - * from attrib or object and add it to this table. - */ - public function addIdMethodParameter($impdata) - { - if ($impdata instanceof IdMethodParameter) { - $imp = $impdata; - $imp->setTable($this); - if ($this->idMethodParameters === null) { - $this->idMethodParameters = array(); - } - $this->idMethodParameters[] = $imp; - return $imp; - } else { - $imp = new IdMethodParameter(); - $imp->loadFromXML($impdata); - return $this->addIdMethodParameter($imp); // call self w/ diff param - } - } - - /** - * Adds a new index to the index list and set the - * parent table of the column to the current table - */ - public function addIndex($idxdata) - { - if ($idxdata instanceof Index) { - $index = $idxdata; - $index->setTable($this); - $index->getName(); // we call this method so that the name is created now if it doesn't already exist. - $this->indices[] = $index; - return $index; - } else { - $index = new Index($this); - $index->loadFromXML($idxdata); - return $this->addIndex($index); - } - } - - /** - * Adds a new Unique to the Unique list and set the - * parent table of the column to the current table - */ - public function addUnique($unqdata) - { - if ($unqdata instanceof Unique) { - $unique = $unqdata; - $unique->setTable($this); - $unique->getName(); // we call this method so that the name is created now if it doesn't already exist. - $this->unices[] = $unique; - return $unique; - } else { - $unique = new Unique($this); - $unique->loadFromXML($unqdata); - return $this->addUnique($unique); - } - } - - /** - * Retrieves the configuration object, filled by build.properties - * - * @return GeneratorConfig - */ - public function getGeneratorConfig() - { - return $this->getDatabase()->getAppData()->getPlatform()->getGeneratorConfig(); - } - - /** - * Adds a new Behavior to the table - * @return Behavior A behavior instance - */ - public function addBehavior($bdata) - { - if ($bdata instanceof Behavior) { - $behavior = $bdata; - $behavior->setTable($this); - $this->behaviors[$behavior->getName()] = $behavior; - return $behavior; - } else { - $class = $this->getConfiguredBehavior($bdata['name']); - $behavior = new $class(); - $behavior->loadFromXML($bdata); - return $this->addBehavior($behavior); - } - } - - /** - * Get the table behaviors - * @return Array of Behavior objects - */ - public function getBehaviors() - { - return $this->behaviors; - } - - /** - * Get the early table behaviors - * @return Array of Behavior objects - */ - public function getEarlyBehaviors() - { - $behaviors = array(); - foreach ($this->behaviors as $name => $behavior) { - if ($behavior->isEarly()) { - $behaviors[$name] = $behavior; - } - } - return $behaviors; - } - - /** - * check if the table has a behavior by name - * - * @param string $name the behavior name - * @return boolean True if the behavior exists - */ - public function hasBehavior($name) - { - return array_key_exists($name, $this->behaviors); - } - - /** - * Get one table behavior by name - * - * @param string $name the behavior name - * @return Behavior a behavior object - */ - public function getBehavior($name) - { - return $this->behaviors[$name]; - } - - /** - * Get the name of the Table - */ - public function getName() - { - return $this->name; - } - - /** - * Set the name of the Table - */ - public function setName($newName) - { - $this->name = $newName; - } - - /** - * Get the description for the Table - */ - public function getDescription() - { - return $this->description; - } - - /** - * Set the description for the Table - * - * @param newDescription description for the Table - */ - public function setDescription($newDescription) - { - $this->description = $newDescription; - } - - /** - * Get name to use in PHP sources - * @return string - */ - public function getPhpName() - { - if ($this->phpName === null) { - $inputs = array(); - $inputs[] = $this->name; - $inputs[] = $this->phpNamingMethod; - try { - $this->phpName = NameFactory::generateName(NameFactory::PHP_GENERATOR, $inputs); - } catch (EngineException $e) { - print $e->getMessage() . "\n"; - print $e->getTraceAsString(); - } - } - return $this->phpName; - } - - /** - * Set name to use in PHP sources - * @param string $phpName - */ - public function setPhpName($phpName) - { - $this->phpName = $phpName; - } - - public function buildPhpName($name) - { - return NameFactory::generateName(NameFactory::PHP_GENERATOR, array($name, $this->phpNamingMethod)); - } - - /** - * Get studly version of PHP name. - * - * The studly name is the PHP name with the first character lowercase. - * - * @return string - */ - public function getStudlyPhpName() - { - $phpname = $this->getPhpName(); - if (strlen($phpname) > 1) { - return strtolower(substr($phpname, 0, 1)) . substr($phpname, 1); - } else { // 0 or 1 chars (I suppose that's rare) - return strtolower($phpname); - } - } - - /** - * Get the value of the namespace. - * @return value of namespace. - */ - public function getNamespace() - { - if (strpos($this->namespace, '\\') === 0) { - // absolute table namespace - return substr($this->namespace, 1); - } elseif ($this->namespace && $this->getDatabase() && $this->getDatabase()->getNamespace()) { - return $this->getDatabase()->getNamespace() . '\\' . $this->namespace; - } elseif ($this->getDatabase() && $this->getDatabase()->getNamespace()) { - return $this->getDatabase()->getNamespace(); - } else { - return $this->namespace; - } - } - - /** - * Set the value of the namespace. - * @param v Value to assign to namespace. - */ - public function setNamespace($v) - { - $this->namespace = $v; - } - - /** - * Get the method for generating pk's - * [HL] changing behavior so that Database default method is returned - * if no method has been specified for the table. - * - * @return string - */ - public function getIdMethod() - { - if ($this->idMethod === null) { - return IDMethod::NO_ID_METHOD; - } else { - return $this->idMethod; - } - } - - /** - * Whether we allow to insert primary keys on tables with - * idMethod=native - * - * @return boolean - */ - public function isAllowPkInsert() - { - return $this->allowPkInsert; - } - - - /** - * Set the method for generating pk's - */ - public function setIdMethod($idMethod) - { - $this->idMethod = $idMethod; - } - - /** - * Skip generating sql for this table (in the event it should - * not be created from scratch). - * @return boolean Value of skipSql. - */ - public function isSkipSql() - { - return ($this->skipSql || $this->isAlias() || $this->isForReferenceOnly()); - } - - /** - * Is table read-only, in which case only accessors (and relationship setters) - * will be created. - * @return boolan Value of readOnly. - */ - public function isReadOnly() - { - return $this->readOnly; - } - - /** - * Set whether this table should have its creation sql generated. - * @param boolean $v Value to assign to skipSql. - */ - public function setSkipSql($v) - { - $this->skipSql = $v; - } - - /** - * Whether to force object to reload on INSERT. - * @return boolean - */ - public function isReloadOnInsert() - { - return $this->reloadOnInsert; - } - - /** - * Whether to force object to reload on UPDATE. - * @return boolean - */ - public function isReloadOnUpdate() - { - return $this->reloadOnUpdate; - } - - /** - * PhpName of om object this entry references. - * @return value of external. - */ - public function getAlias() - { - return $this->alias; - } - - /** - * Is this table specified in the schema or is there just - * a foreign key reference to it. - * @return value of external. - */ - public function isAlias() - { - return ($this->alias !== null); - } - - /** - * Set whether this table specified in the schema or is there just - * a foreign key reference to it. - * @param v Value to assign to alias. - */ - public function setAlias($v) - { - $this->alias = $v; - } - - - /** - * Interface which objects for this table will implement - * @return value of interface. - */ - public function getInterface() - { - return $this->enterface; - } - - /** - * Interface which objects for this table will implement - * @param v Value to assign to interface. - */ - public function setInterface($v) - { - $this->enterface = $v; - } - - /** - * When a table is abstract, it marks the business object class that is - * generated as being abstract. If you have a table called "FOO", then the - * Foo BO will be public abstract class Foo - * This helps support class hierarchies - * - * @return value of abstractValue. - */ - public function isAbstract() - { - return $this->abstractValue; - } - - /** - * When a table is abstract, it marks the business object - * class that is generated as being abstract. If you have a - * table called "FOO", then the Foo BO will be - * public abstract class Foo - * This helps support class hierarchies - * - * @param v Value to assign to abstractValue. - */ - public function setAbstract($v) - { - $this->abstractValue = (boolean) $v; - } - - /** - * Get the value of package. - * @return value of package. - */ - public function getPackage() - { - return $this->pkg; - } - - /** - * Set the value of package. - * @param v Value to assign to package. - */ - public function setPackage($v) - { - $this->pkg = $v; - } - - /** - * Returns an Array containing all the columns in the table - * @return array Column[] - */ - public function getColumns() - { - return $this->columnList; - } - - /** - * Utility method to get the number of columns in this table - */ - public function getNumColumns() - { - return count($this->columnList); - } - - /** - * Utility method to get the number of columns in this table - */ - public function getNumLazyLoadColumns() - { - $count = 0; - foreach ($this->columnList as $col) { - if ($col->isLazyLoad()) { - $count++; - } - } - return $count; - } - - /** - * Returns an Array containing all the validators in the table - * @return array Validator[] - */ - public function getValidators() - { - return $this->validatorList; - } - - /** - * Returns an Array containing all the FKs in the table. - * @return array ForeignKey[] - */ - public function getForeignKeys() - { - return $this->foreignKeys; - } - - /** - * Returns a Collection of parameters relevant for the chosen - * id generation method. - */ - public function getIdMethodParameters() - { - return $this->idMethodParameters; - } - - /** - * Returns an Array containing all the FKs in the table - * @return array Index[] - */ - public function getIndices() - { - return $this->indices; - } - - /** - * Returns an Array containing all the UKs in the table - * @return array Unique[] - */ - public function getUnices() - { - return $this->unices; - } - - /** - * Check whether the table has a column. - * @return boolean - */ - public function hasColumn($name) - { - return array_key_exists($name, $this->columnsByName); - } - - /** - * Returns a specified column. - * @return Column Return a Column object or null if it does not exist. - */ - public function getColumn($name) - { - return @$this->columnsByName[$name]; - } - - /** - * Returns a specified column. - * @return Column Return a Column object or null if it does not exist. - */ - public function getColumnByPhpName($phpName) - { - return @$this->columnsByPhpName[$phpName]; - } - - /** - * Get all the foreign keys from this table to the specified table. - * @return array ForeignKey[] - */ - public function getForeignKeysReferencingTable($tablename) - { - $matches = array(); - $keys = $this->getForeignKeys(); - foreach ($keys as $fk) { - if ($fk->getForeignTableName() === $tablename) { - $matches[] = $fk; - } - } - return $matches; - } - - /** - * Return the foreign keys that includes col in it's list of local columns. - * Eg. Foreign key (a,b,c) refrences tbl(x,y,z) will be returned of col is either a,b or c. - * @param string $col - * @return array ForeignKey[] or null if there is no FK for specified column. - */ - public function getColumnForeignKeys($colname) - { - $matches = array(); - foreach ($this->foreignKeys as $fk) { - if (in_array($colname, $fk->getLocalColumns())) { - $matches[] = $fk; - } - } - return $matches; - } - - /** - * Returns true if the table contains a specified column - * @param mixed $col Column or column name. - */ - public function containsColumn($col) - { - if ($col instanceof Column) { - return in_array($col, $this->columnList); - } else { - return ($this->getColumn($col) !== null); - } - } - - /** - * Set the database that contains this table. - * - * @param Database $db - */ - public function setDatabase(Database $db) - { - $this->database = $db; - } - - /** - * Get the database that contains this table. - * - * @return Database - */ - public function getDatabase() - { - return $this->database; - } - - /** - * Flag to determine if code/sql gets created for this table. - * Table will be skipped, if return true. - * @return boolean - */ - public function isForReferenceOnly() - { - return $this->forReferenceOnly; - } - - /** - * Flag to determine if code/sql gets created for this table. - * Table will be skipped, if set to true. - * @param boolean $v - */ - public function setForReferenceOnly($v) - { - $this->forReferenceOnly = (boolean) $v; - } - - /** - * Flag to determine if tree node class should be generated for this table. - * @return valur of treeMode - */ - public function treeMode() - { - return $this->treeMode; - } - - /** - * Flag to determine if tree node class should be generated for this table. - * @param v Value to assign to treeMode. - */ - public function setTreeMode($v) - { - $this->treeMode = $v; - } - - /** - * Appends XML nodes to passed-in DOMNode. - * - * @param DOMNode $node - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $tableNode = $node->appendChild($doc->createElement('table')); - $tableNode->setAttribute('name', $this->getName()); - - if ($this->phpName !== null) { - $tableNode->setAttribute('phpName', $this->phpName); - } - - if ($this->idMethod !== null) { - $tableNode->setAttribute('idMethod', $this->idMethod); - } - - if ($this->skipSql !== null) { - $tableNode->setAttribute('idMethod', var_export($this->skipSql, true)); - } - - if ($this->readOnly !== null) { - $tableNode->setAttribute('readOnly', var_export($this->readOnly, true)); - } - - if ($this->treeMode !== null) { - $tableNode->setAttribute('treeMode', $this->treeMode); - } - - if ($this->reloadOnInsert !== null) { - $tableNode->setAttribute('reloadOnInsert', var_export($this->reloadOnInsert, true)); - } - - if ($this->reloadOnUpdate !== null) { - $tableNode->setAttribute('reloadOnUpdate', var_export($this->reloadOnUpdate, true)); - } - - if ($this->forReferenceOnly !== null) { - $tableNode->setAttribute('forReferenceOnly', var_export($this->forReferenceOnly, true)); - } - - if ($this->abstractValue !== null) { - $tableNode->setAttribute('abstract', var_export($this->abstractValue, true)); - } - - if ($this->enterface !== null) { - $tableNode->setAttribute('interface', $this->enterface); - } - - if ($this->description !== null) { - $tableNode->setAttribute('description', $this->description); - } - - if ($this->baseClass !== null) { - $tableNode->setAttribute('baseClass', $this->baseClass); - } - - if ($this->basePeer !== null) { - $tableNode->setAttribute('basePeer', $this->basePeer); - } - - if ($this->getIsCrossRef()) { - $tableNode->setAttribute('isCrossRef', $this->getIsCrossRef()); - } - - - foreach ($this->columnList as $col) { - $col->appendXml($tableNode); - } - - foreach ($this->validatorList as $validator) { - $validator->appendXml($tableNode); - } - - foreach ($this->foreignKeys as $fk) { - $fk->appendXml($tableNode); - } - - foreach ($this->idMethodParameters as $param) { - $param->appendXml($tableNode); - } - - foreach ($this->indices as $index) { - $index->appendXml($tableNode); - } - - foreach ($this->unices as $unique) { - $unique->appendXml($tableNode); - } - - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($tableNode); - } - - } - - /** - * Returns the collection of Columns which make up the single primary - * key for this table. - * - * @return array Column[] A list of the primary key parts. - */ - public function getPrimaryKey() - { - $pk = array(); - foreach ($this->columnList as $col) { - if ($col->isPrimaryKey()) { - $pk[] = $col; - } - } - return $pk; - } - - /** - * Determine whether this table has a primary key. - * - * @return boolean Whether this table has any primary key parts. - */ - public function hasPrimaryKey() - { - return (count($this->getPrimaryKey()) > 0); - } - - /** - * Determine whether this table has a composite primary key. - * - * @return boolean Whether this table has more than one primary key parts. - */ - public function hasCompositePrimaryKey() - { - return (count($this->getPrimaryKey()) > 1); - } - - /** - * Determine whether this table has any auto-increment primary key(s). - * - * @return boolean Whether this table has a non-"none" id method and has a primary key column that is auto-increment. - */ - public function hasAutoIncrementPrimaryKey() - { - if ($this->getIdMethod() != IDMethod::NO_ID_METHOD) { - $pks =$this->getPrimaryKey(); - foreach ($pks as $pk) { - if ($pk->isAutoIncrement()) { - return true; - } - } - } - return false; - } - - /** - * Gets the auto increment PK - * - * @return Column if any auto increment PK column - */ - public function getAutoIncrementPrimaryKey() - { - if ($this->getIdMethod() != IDMethod::NO_ID_METHOD) { - $pks =$this->getPrimaryKey(); - foreach ($pks as $pk) { - if ($pk->isAutoIncrement()) { - return $pk; - } - } - } - return null; - } - - /** - * Returns all parts of the primary key, separated by commas. - * - * @return A CSV list of primary key parts. - * @deprecated Use the DDLBuilder->getColumnList() with the #getPrimaryKey() method. - */ - public function printPrimaryKey() - { - return $this->printList($this->columnList); - } - - /** - * Gets the crossRef status for this foreign key - * @return boolean - */ - public function getIsCrossRef() - { - return $this->isCrossRef; - } - - /** - * Sets a crossref status for this foreign key. - * @param boolean $isCrossRef - */ - public function setIsCrossRef($isCrossRef) - { - $this->isCrossRef = (bool) $isCrossRef; - } - - /** - * Returns the elements of the list, separated by commas. - * @param array $list - * @return A CSV list. - * @deprecated Use the DDLBuilder->getColumnList() with the #getPrimaryKey() method. - */ - private function printList($list){ - $result = ""; - $comma = 0; - for ($i=0,$_i=count($list); $i < $_i; $i++) { - $col = $list[$i]; - if ($col->isPrimaryKey()) { - $result .= ($comma++ ? ',' : '') . $this->getDatabase()->getPlatform()->quoteIdentifier($col->getName()); - } - } - return $result; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Unique.php b/airtime_mvc/library/propel/generator/lib/model/Unique.php deleted file mode 100644 index feec89fcd..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Unique.php +++ /dev/null @@ -1,58 +0,0 @@ - (Propel) - * @author Jason van Zyl (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Unique extends Index -{ - - /** - * Returns true. - */ - public function isUnique() - { - return true; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $uniqueNode = $node->appendChild($doc->createElement('unique')); - $uniqueNode->setAttribute('name', $this->getName()); - $columns = $this->getColumns(); - foreach ($this->getColumns() as $colname) { - $uniqueColNode = $uniqueNode->appendChild($doc->createElement('unique-column')); - $uniqueColNode->setAttribute('name', $colname); - } - - foreach ($this->vendorInfos as $vi) { - $vi->appendXml($uniqueNode); - } - } - - -} diff --git a/airtime_mvc/library/propel/generator/lib/model/Validator.php b/airtime_mvc/library/propel/generator/lib/model/Validator.php deleted file mode 100644 index 10e3d8575..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/Validator.php +++ /dev/null @@ -1,184 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class Validator extends XMLElement -{ - - const TRANSLATE_NONE = "none"; - const TRANSLATE_GETTEXT = "gettext"; - - /** - * The column this validator applies to. - * - * @var Column - */ - private $column; - - /** - * The rules for the validation. - * - * @var array Rule[] - */ - private $ruleList = array(); - - /** - * The translation mode. - * - * @var string - */ - private $translate; - - /** - * Parent table. - * - * @var Table - */ - private $table; - - /** - * Sets up the Validator object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->column = $this->getTable()->getColumn($this->getAttribute("column")); - $this->translate = $this->getAttribute("translate", $this->getTable()->getDatabase()->getDefaultTranslateMethod());; - } - - /** - * Add a Rule to this validator. - * Supports two signatures: - * - addRule(Rule $rule) - * - addRule(array $attribs) - * @param mixed $data Rule object or XML attribs (array) from element. - * @return Rule The added Rule. - */ - public function addRule($data) - { - if ($data instanceof Rule) { - $rule = $data; // alias - $rule->setValidator($this); - $this->ruleList[] = $rule; - return $rule; - } - else { - $rule = new Rule(); - $rule->setValidator($this); - $rule->loadFromXML($data); - return $this->addRule($rule); // call self w/ different param - } - } - - /** - * Gets an array of all added rules for this validator. - * @return array Rule[] - */ - public function getRules() - { - return $this->ruleList; - } - - /** - * Gets the name of the column that this Validator applies to. - * @return string - */ - public function getColumnName() - { - return $this->column->getName(); - } - - /** - * Sets the Column object that this validator applies to. - * @param Column $column - * @see Table::addValidator() - */ - public function setColumn(Column $column) - { - $this->column = $column; - } - - /** - * Gets the Column object that this validator applies to. - * @return Column - */ - public function getColumn() - { - return $this->column; - } - - /** - * Set the owning Table. - * @param Table $table - */ - public function setTable(Table $table) - { - $this->table = $table; - } - - /** - * Get the owning Table. - * @return Table - */ - public function getTable() - { - return $this->table; - } - - /** - * Set the translation mode to use for the message. - * Currently only "gettext" and "none" are supported. The default is "none". - * @param string $method Translation method ("gettext", "none"). - */ - public function setTranslate($method) - { - $this->translate = $method; - } - - /** - * Get the translation mode to use for the message. - * Currently only "gettext" and "none" are supported. The default is "none". - * @return string Translation method ("gettext", "none"). - */ - public function getTranslate() - { - return $this->translate; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $valNode = $node->appendChild($doc->createElement('validator')); - $valNode->setAttribute('column', $this->getColumnName()); - - if ($this->translate !== null) { - $valNode->setAttribute('translate', $this->translate); - } - - foreach ($this->ruleList as $rule) { - $rule->appendXml($valNode); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/VendorInfo.php b/airtime_mvc/library/propel/generator/lib/model/VendorInfo.php deleted file mode 100644 index 9f4f19f39..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/VendorInfo.php +++ /dev/null @@ -1,172 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -class VendorInfo extends XMLElement -{ - - /** - * The vendor RDBMS type. - * - * @var string - */ - private $type; - - /** - * Vendor parameters. - * - * @var array - */ - private $parameters = array(); - - /** - * Creates a new VendorInfo instance. - * - * @param string $type RDBMS type (optional) - */ - public function __construct($type = null) - { - $this->type = $type; - } - - /** - * Sets up this object based on the attributes that were passed to loadFromXML(). - * @see parent::loadFromXML() - */ - protected function setupObject() - { - $this->type = $this->getAttribute("type"); - } - - /** - * Set RDBMS type for this vendor-specific info. - * - * @param string $v - */ - public function setType($v) - { - $this->type = $v; - } - - /** - * Get RDBMS type for this vendor-specific info. - * - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Adds a new vendor parameter to this object. - * @param array $attrib Attributes from XML. - */ - public function addParameter($attrib) - { - $name = $attrib["name"]; - $this->parameters[$name] = $attrib["value"]; - } - - /** - * Sets parameter value. - * - * @param string $name - * @param mixed $value The value for the parameter. - */ - public function setParameter($name, $value) - { - $this->parameters[$name] = $value; - } - - /** - * Gets parameter value. - * - * @param string $name - * @return mixed Paramter value. - */ - public function getParameter($name) - { - if (isset($this->parameters[$name])) { - return $this->parameters[$name]; - } - return null; // just to be explicit - } - - /** - * Whether parameter exists. - * - * @param string $name - */ - public function hasParameter($name) - { - return isset($this->parameters[$name]); - } - - /** - * Sets assoc array of parameters for venfor specific info. - * - * @param array $params Paramter data. - */ - public function setParameters(array $params = array()) - { - $this->parameters = $params; - } - - /** - * Gets assoc array of parameters for venfor specific info. - * - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * Gets a new merged VendorInfo object. - * @param VendorInfo $info - * @return VendorInfo new object with merged parameters - */ - public function getMergedVendorInfo(VendorInfo $merge) - { - $newParams = array_merge($this->getParameters(), $merge->getParameters()); - $newInfo = new VendorInfo($this->getType()); - $newInfo->setParameters($newParams); - return $newInfo; - } - - /** - * @see XMLElement::appendXml(DOMNode) - */ - public function appendXml(DOMNode $node) - { - $doc = ($node instanceof DOMDocument) ? $node : $node->ownerDocument; - - $vendorNode = $node->appendChild($doc->createElement("vendor")); - $vendorNode->setAttribute("type", $this->getType()); - - foreach ($this->parameters as $key => $value) { - $parameterNode = $doc->createElement("parameter"); - $parameterNode->setAttribute("name", $key); - $parameterNode->setAttribute("value", $value); - $vendorNode->appendChild($parameterNode); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/model/XMLElement.php b/airtime_mvc/library/propel/generator/lib/model/XMLElement.php deleted file mode 100644 index cb8008c40..000000000 --- a/airtime_mvc/library/propel/generator/lib/model/XMLElement.php +++ /dev/null @@ -1,182 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.model - */ -abstract class XMLElement -{ - - /** - * The name => value attributes from XML. - * - * @var array - */ - protected $attributes = array(); - - /** - * Any associated vendor-specific information objects. - * - * @var array VendorInfo[] - */ - protected $vendorInfos = array(); - - /** - * Replaces the old loadFromXML() so that we can use loadFromXML() to load the attribs into the class. - */ - abstract protected function setupObject(); - - /** - * This is the entry point method for loading data from XML. - * It calls a setupObject() method that must be implemented by the child class. - * @param array $attributes The attributes for the XML tag. - */ - public function loadFromXML($attributes) - { - $this->attributes = array_change_key_case($attributes, CASE_LOWER); - $this->setupObject(); - } - - /** - * Returns the assoc array of attributes. - * All attribute names (keys) are lowercase. - * @return array - */ - public function getAttributes() - { - return $this->attributes; - } - - /** - * Gets a particular attribute by [case-insensitive] name. - * If attribute is not set then the $defaultValue is returned. - * @param string $name The [case-insensitive] name of the attribute to lookup. - * @param mixed $defaultValue The default value to use in case the attribute is not set. - * @return mixed The value of the attribute or $defaultValue if not set. - */ - public function getAttribute($name, $defaultValue = null) - { - $name = strtolower($name); - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } else { - return $defaultValue; - } - } - - /** - * Converts value specified in XML to a boolean value. - * This is to support the default value when used w/ a boolean column. - * @return value - */ - protected function booleanValue($val) - { - if (is_numeric($val)) { - return (bool) $val; - } else { - return (in_array(strtolower($val), array('true', 't', 'y', 'yes'), true) ? true : false); - } - } - - /** - * Appends DOM elements to represent this object in XML. - * @param DOMNode $node - */ - abstract public function appendXml(DOMNode $node); - - /** - * Sets an associated VendorInfo object. - * - * @param mixed $data VendorInfo object or XML attrib data (array) - * @return VendorInfo - */ - public function addVendorInfo($data) - { - if ($data instanceof VendorInfo) { - $vi = $data; - $this->vendorInfos[$vi->getType()] = $vi; - return $vi; - } else { - $vi = new VendorInfo(); - $vi->loadFromXML($data); - return $this->addVendorInfo($vi); // call self w/ different param - } - } - - /** - * Gets the any associated VendorInfo object. - * @return VendorInfo - */ - public function getVendorInfoForType($type) - { - if (isset($this->vendorInfos[$type])) { - return $this->vendorInfos[$type]; - } else { - // return an empty object - return new VendorInfo(); - } - } - - /** - * Find the best class name for a given behavior - * Looks in build.properties for path like propel.behavior.[bname].class - * If not found, tries to autoload [Bname]Behavior - * If no success, returns 'Behavior' - * - * @param string $bname behavior name, e.g. 'timestampable' - * @return string behavior class name, e.g. 'TimestampableBehavior' - */ - public function getConfiguredBehavior($bname) - { - if ($config = $this->getGeneratorConfig()) { - if ($class = $config->getConfiguredBehavior($bname)) { - return $class; - } - } - // first fallback: maybe the behavior is loaded or autoloaded - $gen = new PhpNameGenerator(); - if(class_exists($class = $gen->generateName($bname, PhpNameGenerator::CONV_METHOD_PHPNAME) . 'Behavior')) { - return $class; - } - // second fallback: use parent behavior class (mostly for unit tests) - return 'Behavior'; - } - - /** - * String representation of the current object. - * - * This is an xml representation with the XML declaration removed. - * - * @see appendXml() - */ - public function toString() - { - $doc = new DOMDocument('1.0'); - $doc->formatOutput = true; - $this->appendXml($doc); - $xmlstr = $doc->saveXML(); - return trim(preg_replace('/<\?xml.*?\?>/', '', $xmlstr)); - } - - /** - * Magic string method - * @see toString() - */ - public function __toString() - { - return $this->toString(); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/DefaultPlatform.php b/airtime_mvc/library/propel/generator/lib/platform/DefaultPlatform.php deleted file mode 100644 index 889d55ec9..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/DefaultPlatform.php +++ /dev/null @@ -1,299 +0,0 @@ - (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class DefaultPlatform implements Platform -{ - - /** - * Mapping from Propel types to Domain objects. - * - * @var array - */ - protected $schemaDomainMap; - - /** - * GeneratorConfig object holding build properties. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * @var PDO Database connection. - */ - private $con; - - /** - * Default constructor. - * @param PDO $con Optional database connection to use in this platform. - */ - public function __construct(PDO $con = null) - { - if ($con) $this->setConnection($con); - $this->initialize(); - } - - /** - * Set the database connection to use for this Platform class. - * @param PDO $con Database connection to use in this platform. - */ - public function setConnection(PDO $con = null) - { - $this->con = $con; - } - - /** - * Sets the GeneratorConfig to use in the parsing. - * - * @param GeneratorConfig $config - */ - public function setGeneratorConfig(GeneratorConfig $config) - { - $this->generatorConfig = $config; - } - - /** - * Gets the GeneratorConfig option. - * - * @return GeneratorConfig - */ - public function getGeneratorConfig() - { - return $this->generatorConfig; - } - - /** - * Gets a specific propel (renamed) property from the build. - * - * @param string $name - * @return mixed - */ - protected function getBuildProperty($name) - { - if ($this->generatorConfig !== null) { - return $this->generatorConfig->getBuildProperty($name); - } - return null; - } - - /** - * Returns the database connection to use for this Platform class. - * @return PDO The database connection or NULL if none has been set. - */ - public function getConnection() - { - return $this->con; - } - - /** - * Initialize the type -> Domain mapping. - */ - protected function initialize() - { - $this->schemaDomainMap = array(); - foreach (PropelTypes::getPropelTypes() as $type) { - $this->schemaDomainMap[$type] = new Domain($type); - } - // BU_* no longer needed, so map these to the DATE/TIMESTAMP domains - $this->schemaDomainMap[PropelTypes::BU_DATE] = new Domain(PropelTypes::DATE); - $this->schemaDomainMap[PropelTypes::BU_TIMESTAMP] = new Domain(PropelTypes::TIMESTAMP); - - // Boolean is a bit special, since typically it must be mapped to INT type. - $this->schemaDomainMap[PropelTypes::BOOLEAN] = new Domain(PropelTypes::BOOLEAN, "INTEGER"); - } - - /** - * Adds a mapping entry for specified Domain. - * @param Domain $domain - */ - protected function setSchemaDomainMapping(Domain $domain) - { - $this->schemaDomainMap[$domain->getType()] = $domain; - } - - /** - * Returns the short name of the database type that this platform represents. - * For example MysqlPlatform->getDatabaseType() returns 'mysql'. - * @return string - */ - public function getDatabaseType() - { - $clazz = get_class($this); - $pos = strpos($clazz, 'Platform'); - return strtolower(substr($clazz,0,$pos)); - } - - /** - * @see Platform::getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 64; - } - - /** - * @see Platform::getNativeIdMethod() - */ - public function getNativeIdMethod() - { - return Platform::IDENTITY; - } - - /** - * @see Platform::getDomainForType() - */ - public function getDomainForType($propelType) - { - if (!isset($this->schemaDomainMap[$propelType])) { - throw new EngineException("Cannot map unknown Propel type " . var_export($propelType, true) . " to native database type."); - } - return $this->schemaDomainMap[$propelType]; - } - - /** - * @return string Returns the SQL fragment to use if null values are disallowed. - * @see Platform::getNullString(boolean) - */ - public function getNullString($notNull) - { - return ($notNull ? "NOT NULL" : ""); - } - - /** - * @see Platform::getAutoIncrement() - */ - public function getAutoIncrement() - { - return "IDENTITY"; - } - - /** - * @see Platform::hasScale(String) - */ - public function hasScale($sqlType) - { - return true; - } - - /** - * @see Platform::hasSize(String) - */ - public function hasSize($sqlType) - { - return true; - } - - /** - * @see Platform::quote() - */ - public function quote($text) - { - if ($this->getConnection()) { - return $this->getConnection()->quote($text); - } else { - return "'" . $this->disconnectedEscapeText($text) . "'"; - } - } - - /** - * Method to escape text when no connection has been set. - * - * The subclasses can implement this using string replacement functions - * or native DB methods. - * - * @param string $text Text that needs to be escaped. - * @return string - */ - protected function disconnectedEscapeText($text) - { - return str_replace("'", "''", $text); - } - - /** - * @see Platform::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '"' . $text . '"'; - } - - /** - * @see Platform::supportsNativeDeleteTrigger() - */ - public function supportsNativeDeleteTrigger() - { - return false; - } - - /** - * @see Platform::supportsInsertNullPk() - */ - public function supportsInsertNullPk() - { - return true; - } - - /** - * Whether the underlying PDO driver for this platform returns BLOB columns as streams (instead of strings). - * @return boolean - */ - public function hasStreamBlobImpl() - { - return false; - } - - /** - * @see Platform::getBooleanString() - */ - public function getBooleanString($b) - { - $b = ($b === true || strtolower($b) === 'true' || $b === 1 || $b === '1' || strtolower($b) === 'y' || strtolower($b) === 'yes'); - return ($b ? '1' : '0'); - } - - /** - * Gets the preferred timestamp formatter for setting date/time values. - * @return string - */ - public function getTimestampFormatter() - { - return DateTime::ISO8601; - } - - /** - * Gets the preferred time formatter for setting date/time values. - * @return string - */ - public function getTimeFormatter() - { - return 'H:i:s'; - } - - /** - * Gets the preferred date formatter for setting date/time values. - * @return string - */ - public function getDateFormatter() - { - return 'Y-m-d'; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/MssqlPlatform.php b/airtime_mvc/library/propel/generator/lib/platform/MssqlPlatform.php deleted file mode 100644 index b8330d9b8..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/MssqlPlatform.php +++ /dev/null @@ -1,107 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class MssqlPlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, "INT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, "INT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, "FLOAT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "TEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_DATE, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_TIMESTAMP, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BINARY(7132)")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "IMAGE")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "IMAGE")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "IMAGE")); - } - - /** - * @see Platform#getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 128; - } - - /** - * @return Explicitly returns NULL if null values are - * allowed (as recomended by Microsoft). - * @see Platform#getNullString(boolean) - */ - public function getNullString($notNull) - { - return ($notNull ? "NOT NULL" : "NULL"); - } - - /** - * @see Platform::supportsNativeDeleteTrigger() - */ - public function supportsNativeDeleteTrigger() - { - return true; - } - - /** - * @see Platform::supportsInsertNullPk() - */ - public function supportsInsertNullPk() - { - return false; - } - - /** - * @see Platform::hasSize(String) - */ - public function hasSize($sqlType) - { - return !("INT" == $sqlType || "TEXT" == $sqlType); - } - - /** - * @see Platform::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - /** - * Gets the preferred timestamp formatter for setting date/time values. - * @return string - */ - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s'; - } - - -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/MysqlPlatform.php b/airtime_mvc/library/propel/generator/lib/platform/MysqlPlatform.php deleted file mode 100644 index 8bbc0b9db..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/MysqlPlatform.php +++ /dev/null @@ -1,110 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class MysqlPlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, "TINYINT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, "DECIMAL")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "MEDIUMBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "LONGTEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, "DATETIME")); - } - - /** - * @see Platform#getAutoIncrement() - */ - public function getAutoIncrement() - { - return "AUTO_INCREMENT"; - } - - /** - * @see Platform#getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 64; - } - - /** - * @see Platform::supportsNativeDeleteTrigger() - */ - public function supportsNativeDeleteTrigger() - { - $usingInnoDB = false; - if (class_exists('DataModelBuilder', false)) - { - $usingInnoDB = strtolower($this->getBuildProperty('mysqlTableType')) == 'innodb'; - } - return $usingInnoDB || false; - } - - /** - * @see Platform#hasSize(String) - */ - public function hasSize($sqlType) - { - return !("MEDIUMTEXT" == $sqlType || "LONGTEXT" == $sqlType - || "BLOB" == $sqlType || "MEDIUMBLOB" == $sqlType - || "LONGBLOB" == $sqlType); - } - - /** - * Escape the string for RDBMS. - * @param string $text - * @return string - */ - public function disconnectedEscapeText($text) - { - if (function_exists('mysql_escape_string')) { - return mysql_escape_string($text); - } else { - return addslashes($text); - } - } - - /** - * @see Platform::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '`' . $text . '`'; - } - - /** - * Gets the preferred timestamp formatter for setting date/time values. - * @return string - */ - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s'; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/OraclePlatform.php b/airtime_mvc/library/propel/generator/lib/platform/OraclePlatform.php deleted file mode 100644 index 7ecf100b7..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/OraclePlatform.php +++ /dev/null @@ -1,113 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class OraclePlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->schemaDomainMap[PropelTypes::BOOLEAN] = new Domain(PropelTypes::BOOLEAN_EMU, "NUMBER", "1", "0"); - $this->schemaDomainMap[PropelTypes::CLOB] = new Domain(PropelTypes::CLOB_EMU, "CLOB"); - $this->schemaDomainMap[PropelTypes::CLOB_EMU] = $this->schemaDomainMap[PropelTypes::CLOB]; - $this->setSchemaDomainMapping(new Domain(PropelTypes::TINYINT, "NUMBER", "3", "0")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::SMALLINT, "NUMBER", "5", "0")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, "NUMBER")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BIGINT, "NUMBER", "20", "0")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::REAL, "NUMBER")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, "FLOAT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DECIMAL, "NUMBER")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, "NUMBER")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARCHAR, "NVARCHAR2")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "NVARCHAR2", "2000")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, "DATE")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, "DATE")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, "TIMESTAMP")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "LONG RAW")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "BLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "LONG RAW")); - } - - /** - * @see Platform#getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 30; - } - - /** - * @see Platform#getNativeIdMethod() - */ - public function getNativeIdMethod() - { - return Platform::SEQUENCE; - } - - /** - * @see Platform#getAutoIncrement() - */ - public function getAutoIncrement() - { - return ""; - } - - /** - * @see Platform::supportsNativeDeleteTrigger() - */ - public function supportsNativeDeleteTrigger() - { - return true; - } - - /** - * Whether the underlying PDO driver for this platform returns BLOB columns as streams (instead of strings). - * @return boolean - */ - public function hasStreamBlobImpl() - { - return true; - } - - /** - * Quotes identifiers used in database SQL. - * @see Platform::quoteIdentifier() - * @param string $text - * @return string Quoted identifier. - */ - public function quoteIdentifier($text) - { - return $text; - } - - /** - * Gets the preferred timestamp formatter for setting date/time values. - * @see Platform::getTimestampFormatter() - * @return string - */ - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s'; - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/PgsqlPlatform.php b/airtime_mvc/library/propel/generator/lib/platform/PgsqlPlatform.php deleted file mode 100644 index 8e8511b9e..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/PgsqlPlatform.php +++ /dev/null @@ -1,118 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class PgsqlPlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, "BOOLEAN")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TINYINT, "INT2")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::SMALLINT, "INT2")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BIGINT, "INT8")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::REAL, "FLOAT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, "DOUBLE PRECISION")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BYTEA")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "BYTEA")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "BYTEA")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "BYTEA")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "TEXT")); - } - - /** - * @see Platform#getNativeIdMethod() - */ - public function getNativeIdMethod() - { - return Platform::SERIAL; - } - - /** - * @see Platform#getAutoIncrement() - */ - public function getAutoIncrement() - { - return ""; - } - - /** - * @see Platform#getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 32; - } - - /** - * Escape the string for RDBMS. - * @param string $text - * @return string - */ - public function disconnectedEscapeText($text) - { - if (function_exists('pg_escape_string')) { - return pg_escape_string($text); - } else { - return parent::disconnectedEscapeText($text); - } - } - - /** - * @see Platform::getBooleanString() - */ - public function getBooleanString($b) - { - // parent method does the checking for allowes tring - // representations & returns integer - $b = parent::getBooleanString($b); - return ($b ? "'t'" : "'f'"); - } - - /** - * @see Platform::supportsNativeDeleteTrigger() - */ - public function supportsNativeDeleteTrigger() - { - return true; - } - - /** - * @see Platform::hasSize(String) - * TODO collect info for all platforms - */ - public function hasSize($sqlType) - { - return !("BYTEA" == $sqlType || "TEXT" == $sqlType); - } - - /** - * Whether the underlying PDO driver for this platform returns BLOB columns as streams (instead of strings). - * @return boolean - */ - public function hasStreamBlobImpl() - { - return true; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/Platform.php b/airtime_mvc/library/propel/generator/lib/platform/Platform.php deleted file mode 100644 index 184116ce2..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/Platform.php +++ /dev/null @@ -1,182 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -interface Platform -{ - - /** - * Constant for auto-increment id method. - */ - const IDENTITY = "identity"; - - /** - * Constant for sequence id method. - */ - const SEQUENCE = "sequence"; - - /** - * Constant for serial id method (postgresql). - */ - const SERIAL = "serial"; - - /** - * Sets a database connection to use (for quoting, etc.). - * @param PDO $con The database connection to use in this Platform class. - */ - public function setConnection(PDO $con = null); - - /** - * Returns the database connection to use for this Platform class. - * @return PDO The database connection or NULL if none has been set. - */ - public function getConnection(); - - /** - * Sets the GeneratorConfig which contains any generator build properties. - * - * @param GeneratorConfig $config - */ - public function setGeneratorConfig(GeneratorConfig $config); - - /** - * Gets the GeneratorConfig object. - * - * @return GeneratorConfig - */ - public function getGeneratorConfig(); - - /** - * Returns the short name of the database type that this platform represents. - * For example MysqlPlatform->getDatabaseType() returns 'mysql'. - * @return string - */ - public function getDatabaseType(); - - /** - * Returns the native IdMethod (sequence|identity) - * - * @return string The native IdMethod (Platform:IDENTITY, Platform::SEQUENCE). - */ - public function getNativeIdMethod(); - - /** - * Returns the max column length supported by the db. - * - * @return int The max column length - */ - public function getMaxColumnNameLength(); - - /** - * Returns the db specific domain for a propelType. - * - * @param string $propelType the Propel type name. - * @return Domain The db specific domain. - */ - public function getDomainForType($propelType); - - /** - * @return string The RDBMS-specific SQL fragment for NULL - * or NOT NULL. - */ - public function getNullString($notNull); - - /** - * @return The RDBMS-specific SQL fragment for autoincrement. - */ - public function getAutoIncrement(); - - /** - * Returns if the RDBMS-specific SQL type has a size attribute. - * - * @param string $sqlType the SQL type - * @return boolean True if the type has a size attribute - */ - public function hasSize($sqlType); - - /** - * Returns if the RDBMS-specific SQL type has a scale attribute. - * - * @param string $sqlType the SQL type - * @return boolean True if the type has a scale attribute - */ - public function hasScale($sqlType); - - /** - * Quote and escape needed characters in the string for unerlying RDBMS. - * @param string $text - * @return string - */ - public function quote($text); - - /** - * Quotes identifiers used in database SQL. - * @param string $text - * @return string Quoted identifier. - */ - public function quoteIdentifier($text); - - /** - * Whether RDBMS supports native ON DELETE triggers (e.g. ON DELETE CASCADE). - * @return boolean - */ - public function supportsNativeDeleteTrigger(); - - /** - * Whether RDBMS supports INSERT null values in autoincremented primary keys - * @return boolean - */ - public function supportsInsertNullPk(); - - /** - * Returns the boolean value for the RDBMS. - * - * This value should match the boolean value that is set - * when using Propel's PreparedStatement::setBoolean(). - * - * This function is used to set default column values when building - * SQL. - * - * @param mixed $tf A boolean or string representation of boolean ('y', 'true'). - * @return mixed - */ - public function getBooleanString($tf); - - /** - * Whether the underlying PDO driver for this platform returns BLOB columns as streams (instead of strings). - * @return boolean - */ - public function hasStreamBlobImpl(); - - /** - * Gets the preferred timestamp formatter for setting date/time values. - * @return string - */ - public function getTimestampFormatter(); - - /** - * Gets the preferred date formatter for setting time values. - * @return string - */ - public function getDateFormatter(); - - /** - * Gets the preferred time formatter for setting time values. - * @return string - */ - public function getTimeFormatter(); -} diff --git a/airtime_mvc/library/propel/generator/lib/platform/SqlitePlatform.php b/airtime_mvc/library/propel/generator/lib/platform/SqlitePlatform.php deleted file mode 100644 index d42dcb978..000000000 --- a/airtime_mvc/library/propel/generator/lib/platform/SqlitePlatform.php +++ /dev/null @@ -1,87 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.platform - */ -class SqlitePlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, "DECIMAL")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "MEDIUMTEXT")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, "DATETIME")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "MEDIUMBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "LONGBLOB")); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "LONGTEXT")); - } - - /** - * @see Platform#getAutoIncrement() - * @link http://www.sqlite.org/autoinc.html - */ - public function getAutoIncrement() - { - - return "PRIMARY KEY"; - } - - /** - * @see Platform#getMaxColumnNameLength() - */ - public function getMaxColumnNameLength() - { - return 1024; - } - - /** - * @see Platform#hasSize(String) - */ - public function hasSize($sqlType) { - return !("MEDIUMTEXT" == $sqlType || "LONGTEXT" == $sqlType - || "BLOB" == $sqlType || "MEDIUMBLOB" == $sqlType - || "LONGBLOB" == $sqlType); - } - - /** - * Escape the string for RDBMS. - * @param string $text - * @return string - */ - public function disconnectedEscapeText($text) - { - if (function_exists('sqlite_escape_string')) { - return sqlite_escape_string($text); - } else { - return parent::disconnectedEscapeText($text); - } - } - - /** - * @see Platform::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/BaseSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/BaseSchemaParser.php deleted file mode 100644 index ae80621d9..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/BaseSchemaParser.php +++ /dev/null @@ -1,188 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.reverse - */ -abstract class BaseSchemaParser implements SchemaParser -{ - - /** - * The database connection. - * @var PDO - */ - protected $dbh; - - /** - * Stack of warnings. - * - * @var array string[] - */ - protected $warnings = array(); - - /** - * GeneratorConfig object holding build properties. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * Map native DB types to Propel types. - * (Override in subclasses.) - * @var array - */ - protected $nativeToPropelTypeMap; - - /** - * Map to hold reverse type mapping (initialized on-demand). - * - * @var array - */ - protected $reverseTypeMap; - - /** - * @param PDO $dbh Optional database connection - */ - public function __construct(PDO $dbh = null) - { - if ($dbh) $this->setConnection($dbh); - } - - /** - * Sets the database connection. - * - * @param PDO $dbh - */ - public function setConnection(PDO $dbh) - { - $this->dbh = $dbh; - } - - /** - * Gets the database connection. - * @return PDO - */ - public function getConnection() - { - return $this->dbh; - } - - /** - * Pushes a message onto the stack of warnings. - * - * @param string $msg The warning message. - */ - protected function warn($msg) - { - $this->warnings[] = $msg; - } - - /** - * Gets array of warning messages. - * - * @return array string[] - */ - public function getWarnings() - { - return $this->warnings; - } - - /** - * Sets the GeneratorConfig to use in the parsing. - * - * @param GeneratorConfig $config - */ - public function setGeneratorConfig(GeneratorConfig $config) - { - $this->generatorConfig = $config; - } - - /** - * Gets the GeneratorConfig option. - * - * @return GeneratorConfig - */ - public function getGeneratorConfig() - { - return $this->generatorConfig; - } - - /** - * Gets a specific propel (renamed) property from the build. - * - * @param string $name - * @return mixed - */ - public function getBuildProperty($name) - { - if ($this->generatorConfig !== null) { - return $this->generatorConfig->getBuildProperty($name); - } - return null; - } - - /** - * Gets a type mapping from native type to Propel type. - * - * @return array The mapped Propel type. - */ - abstract protected function getTypeMapping(); - - /** - * Gets a mapped Propel type for specified native type. - * - * @param string $nativeType - * @return string The mapped Propel type. - */ - protected function getMappedPropelType($nativeType) - { - if ($this->nativeToPropelTypeMap === null) { - $this->nativeToPropelTypeMap = $this->getTypeMapping(); - } - if (isset($this->nativeToPropelTypeMap[$nativeType])) { - return $this->nativeToPropelTypeMap[$nativeType]; - } - return null; - } - - /** - * Give a best guess at the native type. - * - * @param string $propelType - * @return string The native SQL type that best matches the specified Propel type. - */ - protected function getMappedNativeType($propelType) - { - if ($this->reverseTypeMap === null) { - $this->reverseTypeMap = array_flip($this->getTypeMapping()); - } - return isset($this->reverseTypeMap[$propelType]) ? $this->reverseTypeMap[$propelType] : null; - } - - /** - * Gets a new VendorInfo object for this platform with specified params. - * - * @param array $params - */ - protected function getNewVendorInfoObject(array $params) - { - $type = $this->getGeneratorConfig()->getConfiguredPlatform()->getDatabaseType(); - $vi = new VendorInfo($type); - $vi->setParameters($params); - return $vi; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/SchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/SchemaParser.php deleted file mode 100644 index 4f6366767..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/SchemaParser.php +++ /dev/null @@ -1,63 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.reverse - */ -interface SchemaParser -{ - - /** - * Gets the database connection. - * @return PDO - */ - public function getConnection(); - - /** - * Sets the database connection. - * - * @param PDO $dbh - */ - public function setConnection(PDO $dbh); - - /** - * Sets the GeneratorConfig to use in the parsing. - * - * @param GeneratorConfig $config - */ - public function setGeneratorConfig(GeneratorConfig $config); - - /** - * Gets a specific propel (renamed) property from the build. - * - * @param string $name - * @return mixed - */ - public function getBuildProperty($name); - - /** - * Gets array of warning messages. - * @return array string[] - */ - public function getWarnings(); - - /** - * Parse the schema and populate passed-in Database model object. - * - * @param Database $database - * - * @return int number of generated tables - */ - public function parse(Database $database, PDOTask $task = null); -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/mssql/MssqlSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/mssql/MssqlSchemaParser.php deleted file mode 100644 index d28c3973d..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/mssql/MssqlSchemaParser.php +++ /dev/null @@ -1,240 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.reverse.mssql - */ -class MssqlSchemaParser extends BaseSchemaParser -{ - - /** - * Map MSSQL native types to Propel types. - * @var array - */ - private static $mssqlTypeMap = array( - "binary" => PropelTypes::BINARY, - "bit" => PropelTypes::BOOLEAN, - "char" => PropelTypes::CHAR, - "datetime" => PropelTypes::TIMESTAMP, - "decimal() identity" => PropelTypes::DECIMAL, - "decimal" => PropelTypes::DECIMAL, - "image" => PropelTypes::LONGVARBINARY, - "int" => PropelTypes::INTEGER, - "int identity" => PropelTypes::INTEGER, - "integer" => PropelTypes::INTEGER, - "money" => PropelTypes::DECIMAL, - "nchar" => PropelTypes::CHAR, - "ntext" => PropelTypes::LONGVARCHAR, - "numeric() identity" => PropelTypes::NUMERIC, - "numeric" => PropelTypes::NUMERIC, - "nvarchar" => PropelTypes::VARCHAR, - "real" => PropelTypes::REAL, - "float" => PropelTypes::FLOAT, - "smalldatetime" => PropelTypes::TIMESTAMP, - "smallint" => PropelTypes::SMALLINT, - "smallint identity" => PropelTypes::SMALLINT, - "smallmoney" => PropelTypes::DECIMAL, - "sysname" => PropelTypes::VARCHAR, - "text" => PropelTypes::LONGVARCHAR, - "timestamp" => PropelTypes::BINARY, - "tinyint identity" => PropelTypes::TINYINT, - "tinyint" => PropelTypes::TINYINT, - "uniqueidentifier" => PropelTypes::CHAR, - "varbinary" => PropelTypes::VARBINARY, - "varchar" => PropelTypes::VARCHAR, - "uniqueidentifier" => PropelTypes::CHAR, - // SQL Server 2000 only - "bigint identity" => PropelTypes::BIGINT, - "bigint" => PropelTypes::BIGINT, - "sql_variant" => PropelTypes::VARCHAR, - ); - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$mssqlTypeMap; - } - - /** - * - */ - public function parse(Database $database, PDOTask $task = null) - { - $stmt = $this->dbh->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'dtproperties'"); - - // First load the tables (important that this happen before filling out details of tables) - $tables = array(); - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $row[0]; - $table = new Table($name); - $database->addTable($table); - $tables[] = $table; - } - - // Now populate only columns. - foreach ($tables as $table) { - $this->addColumns($table); - } - - // Now add indexes and constraints. - foreach ($tables as $table) { - $this->addForeignKeys($table); - $this->addIndexes($table); - $this->addPrimaryKey($table); - } - - return count($tables); - - } - - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("sp_columns '" . $table->getName() . "'"); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['COLUMN_NAME']; - $type = $row['TYPE_NAME']; - $size = $row['LENGTH']; - $is_nullable = $row['NULLABLE']; - $default = $row['COLUMN_DEF']; - $precision = $row['PRECISION']; - $scale = $row['SCALE']; - $autoincrement = false; - if (strtolower($type) == "int identity") { - $autoincrement = true; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$type.") that Propel does not support."); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull(!$is_nullable); - - $table->addColumn($column); - } - - - } // addColumn() - - /** - * Load foreign keys for this table. - */ - protected function addForeignKeys(Table $table) - { - $database = $table->getDatabase(); - - $stmt = $this->dbh->query("SELECT ccu1.TABLE_NAME, ccu1.COLUMN_NAME, ccu2.TABLE_NAME AS FK_TABLE_NAME, ccu2.COLUMN_NAME AS FK_COLUMN_NAME - FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu1 INNER JOIN - INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc1 ON tc1.CONSTRAINT_NAME = ccu1.CONSTRAINT_NAME AND - CONSTRAINT_TYPE = 'Foreign Key' INNER JOIN - INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1 ON rc1.CONSTRAINT_NAME = tc1.CONSTRAINT_NAME INNER JOIN - INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu2 ON ccu2.CONSTRAINT_NAME = rc1.UNIQUE_CONSTRAINT_NAME - WHERE (ccu1.table_name = '".$table->getName()."')"); - - $row = $stmt->fetch(PDO::FETCH_NUM); - - $foreignKeys = array(); // local store to avoid duplicates - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $lcol = $row['COLUMN_NAME']; - $ftbl = $row['FK_TABLE_NAME']; - $fcol = $row['FK_COLUMN_NAME']; - - - $foreignTable = $database->getTable($ftbl); - $foreignColumn = $foreignTable->getColumn($fcol); - $localColumn = $table->getColumn($lcol); - - if (!isset($foreignKeys[$name])) { - $fk = new ForeignKey($name); - $fk->setForeignTableName($foreignTable->getName()); - //$fk->setOnDelete($fkactions['ON DELETE']); - //$fk->setOnUpdate($fkactions['ON UPDATE']); - $table->addForeignKey($fk); - $foreignKeys[$name] = $fk; - } - $foreignKeys[$name]->addReference($localColumn, $foreignColumn); - } - - } - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("sp_indexes_rowset " . $table->getName()); - - $indexes = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $colName = $row["COLUMN_NAME"]; - $name = $row['INDEX_NAME']; - - // FIXME -- Add UNIQUE support - if (!isset($indexes[$name])) { - $indexes[$name] = new Index($name); - $table->addIndex($indexes[$name]); - } - - $indexes[$name]->addColumn($table->getColumn($colName)); - } - } - - /** - * Loads the primary key for this table. - */ - protected function addPrimaryKey(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME - FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS - INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ON - INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.constraint_name - WHERE (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'PRIMARY KEY') AND - (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME = '".$table->getName()."')"); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $row[0]; - $table->getColumn($name)->setPrimaryKey(true); - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/mysql/MysqlSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/mysql/MysqlSchemaParser.php deleted file mode 100644 index e88f5634e..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/mysql/MysqlSchemaParser.php +++ /dev/null @@ -1,340 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.reverse.mysql - */ -class MysqlSchemaParser extends BaseSchemaParser -{ - - /** - * @var boolean - */ - private $addVendorInfo = false; - - /** - * Map MySQL native types to Propel types. - * @var array - */ - private static $mysqlTypeMap = array( - 'tinyint' => PropelTypes::TINYINT, - 'smallint' => PropelTypes::SMALLINT, - 'mediumint' => PropelTypes::SMALLINT, - 'int' => PropelTypes::INTEGER, - 'integer' => PropelTypes::INTEGER, - 'bigint' => PropelTypes::BIGINT, - 'int24' => PropelTypes::BIGINT, - 'real' => PropelTypes::REAL, - 'float' => PropelTypes::FLOAT, - 'decimal' => PropelTypes::DECIMAL, - 'numeric' => PropelTypes::NUMERIC, - 'double' => PropelTypes::DOUBLE, - 'char' => PropelTypes::CHAR, - 'varchar' => PropelTypes::VARCHAR, - 'date' => PropelTypes::DATE, - 'time' => PropelTypes::TIME, - 'year' => PropelTypes::INTEGER, - 'datetime' => PropelTypes::TIMESTAMP, - 'timestamp' => PropelTypes::TIMESTAMP, - 'tinyblob' => PropelTypes::BINARY, - 'blob' => PropelTypes::BLOB, - 'mediumblob' => PropelTypes::BLOB, - 'longblob' => PropelTypes::BLOB, - 'longtext' => PropelTypes::CLOB, - 'tinytext' => PropelTypes::VARCHAR, - 'mediumtext' => PropelTypes::LONGVARCHAR, - 'text' => PropelTypes::LONGVARCHAR, - 'enum' => PropelTypes::CHAR, - 'set' => PropelTypes::CHAR, - ); - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$mysqlTypeMap; - } - - /** - * - */ - public function parse(Database $database, PDOTask $task = null) - { - $this->addVendorInfo = $this->getGeneratorConfig()->getBuildProperty('addVendorInfo'); - - $stmt = $this->dbh->query("SHOW TABLES"); - - // First load the tables (important that this happen before filling out details of tables) - $tables = array(); - $task->log("Reverse Engineering Tables"); - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $row[0]; - $task->log(" Adding table '" . $name . "'"); - $table = new Table($name); - $database->addTable($table); - $tables[] = $table; - } - - // Now populate only columns. - $task->log("Reverse Engineering Columns"); - foreach ($tables as $table) { - $task->log(" Adding columns for table '" . $table->getName() . "'"); - $this->addColumns($table); - } - - // Now add indices and constraints. - $task->log("Reverse Engineering Indices And Constraints"); - foreach ($tables as $table) { - $task->log(" Adding indices and constraints for table '" . $table->getName() . "'"); - $this->addForeignKeys($table); - $this->addIndexes($table); - $this->addPrimaryKey($table); - if ($this->addVendorInfo) { - $this->addTableVendorInfo($table); - } - } - - return count($tables); - } - - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("SHOW COLUMNS FROM `" . $table->getName() . "`"); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['Field']; - $is_nullable = ($row['Null'] == 'YES'); - $autoincrement = (strpos($row['Extra'], 'auto_increment') !== false); - $size = null; - $precision = null; - $scale = null; - - if (preg_match('/^(\w+)[\(]?([\d,]*)[\)]?( |$)/', $row['Type'], $matches)) { - // colname[1] size/precision[2] - $nativeType = $matches[1]; - if ($matches[2]) { - if ( ($cpos = strpos($matches[2], ',')) !== false) { - $size = (int) substr($matches[2], 0, $cpos); - $precision = $size; - $scale = (int) substr($matches[2], $cpos + 1); - } else { - $size = (int) $matches[2]; - } - } - } elseif (preg_match('/^(\w+)\(/', $row['Type'], $matches)) { - $nativeType = $matches[1]; - } else { - $nativeType = $row['Type']; - } - - //BLOBs can't have any default values in MySQL - $default = preg_match('~blob|text~', $nativeType) ? null : $row['Default']; - - $propelType = $this->getMappedPropelType($nativeType); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$nativeType.") that Propel does not support."); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - if (in_array($default, array('CURRENT_TIMESTAMP'))) { - $type = ColumnDefaultValue::TYPE_EXPR; - } else { - $type = ColumnDefaultValue::TYPE_VALUE; - } - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, $type)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull(!$is_nullable); - - if ($this->addVendorInfo) { - $vi = $this->getNewVendorInfoObject($row); - $column->addVendorInfo($vi); - } - - $table->addColumn($column); - } - - - } // addColumn() - - /** - * Load foreign keys for this table. - */ - protected function addForeignKeys(Table $table) - { - $database = $table->getDatabase(); - - $stmt = $this->dbh->query("SHOW CREATE TABLE `" . $table->getName(). "`"); - $row = $stmt->fetch(PDO::FETCH_NUM); - - $foreignKeys = array(); // local store to avoid duplicates - - // Get the information on all the foreign keys - $regEx = '/CONSTRAINT `([^`]+)` FOREIGN KEY \((.+)\) REFERENCES `([^`]*)` \((.+)\)(.*)/'; - if (preg_match_all($regEx,$row[1],$matches)) { - $tmpArray = array_keys($matches[0]); - foreach ($tmpArray as $curKey) { - $name = $matches[1][$curKey]; - $rawlcol = $matches[2][$curKey]; - $ftbl = $matches[3][$curKey]; - $rawfcol = $matches[4][$curKey]; - $fkey = $matches[5][$curKey]; - - $lcols = array(); - foreach(preg_split('/`, `/', $rawlcol) as $piece) { - $lcols[] = trim($piece, '` '); - } - - $fcols = array(); - foreach(preg_split('/`, `/', $rawfcol) as $piece) { - $fcols[] = trim($piece, '` '); - } - - //typical for mysql is RESTRICT - $fkactions = array( - 'ON DELETE' => ForeignKey::RESTRICT, - 'ON UPDATE' => ForeignKey::RESTRICT, - ); - - if ($fkey) { - //split foreign key information -> search for ON DELETE and afterwords for ON UPDATE action - foreach (array_keys($fkactions) as $fkaction) { - $result = NULL; - preg_match('/' . $fkaction . ' (' . ForeignKey::CASCADE . '|' . ForeignKey::SETNULL . ')/', $fkey, $result); - if ($result && is_array($result) && isset($result[1])) { - $fkactions[$fkaction] = $result[1]; - } - } - } - - $localColumns = array(); - $foreignColumns = array(); - - $foreignTable = $database->getTable($ftbl); - - foreach($fcols as $fcol) { - $foreignColumns[] = $foreignTable->getColumn($fcol); - } - foreach($lcols as $lcol) { - $localColumns[] = $table->getColumn($lcol); - } - - if (!isset($foreignKeys[$name])) { - $fk = new ForeignKey($name); - $fk->setForeignTableName($foreignTable->getName()); - $fk->setOnDelete($fkactions['ON DELETE']); - $fk->setOnUpdate($fkactions['ON UPDATE']); - $table->addForeignKey($fk); - $foreignKeys[$name] = $fk; - } - - for($i=0; $i < count($localColumns); $i++) { - $foreignKeys[$name]->addReference($localColumns[$i], $foreignColumns[$i]); - } - - } - - } - - } - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("SHOW INDEX FROM `" . $table->getName() . "`"); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - - $indexes = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $colName = $row["Column_name"]; - $name = $row["Key_name"]; - - if ($name == "PRIMARY") { - continue; - } - - if (!isset($indexes[$name])) { - $isUnique = ($row["Non_unique"] == 0); - if ($isUnique) { - $indexes[$name] = new Unique($name); - } else { - $indexes[$name] = new Index($name); - } - if ($this->addVendorInfo) { - $vi = $this->getNewVendorInfoObject($row); - $indexes[$name]->addVendorInfo($vi); - } - $table->addIndex($indexes[$name]); - } - - $indexes[$name]->addColumn($table->getColumn($colName)); - } - } - - /** - * Loads the primary key for this table. - */ - protected function addPrimaryKey(Table $table) - { - $stmt = $this->dbh->query("SHOW KEYS FROM `" . $table->getName() . "`"); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - // Skip any non-primary keys. - if ($row['Key_name'] !== 'PRIMARY') { - continue; - } - $name = $row["Column_name"]; - $table->getColumn($name)->setPrimaryKey(true); - } - } - - /** - * Adds vendor-specific info for table. - * - * @param Table $table - */ - protected function addTableVendorInfo(Table $table) - { - $stmt = $this->dbh->query("SHOW TABLE STATUS LIKE '" . $table->getName() . "'"); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $vi = $this->getNewVendorInfoObject($row); - $table->addVendorInfo($vi); - } -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/oracle/OracleSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/oracle/OracleSchemaParser.php deleted file mode 100644 index 0e30a7c7d..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/oracle/OracleSchemaParser.php +++ /dev/null @@ -1,249 +0,0 @@ - - * @author Guillermo Gutierrez (Adaptation) - * @version $Revision: 1612 $ - * @package propel.generator.reverse.oracle - */ -class OracleSchemaParser extends BaseSchemaParser -{ - - /** - * Map Oracle native types to Propel types. - * - * There really aren't any Oracle native types, so we're just - * using the MySQL ones here. - * - * Left as unsupported: - * BFILE, - * RAW, - * ROWID - * - * Supported but non existant as a specific type in Oracle: - * DECIMAL (NUMBER with scale), - * DOUBLE (FLOAT with precision = 126) - * - * @var array - */ - private static $oracleTypeMap = array( - 'BLOB' => PropelTypes::BLOB, - 'CHAR' => PropelTypes::CHAR, - 'CLOB' => PropelTypes::CLOB, - 'DATE' => PropelTypes::DATE, - 'DECIMAL' => PropelTypes::DECIMAL, - 'DOUBLE' => PropelTypes::DOUBLE, - 'FLOAT' => PropelTypes::FLOAT, - 'LONG' => PropelTypes::LONGVARCHAR, - 'NCHAR' => PropelTypes::CHAR, - 'NCLOB' => PropelTypes::CLOB, - 'NUMBER' => PropelTypes::BIGINT, - 'NVARCHAR2' => PropelTypes::VARCHAR, - 'TIMESTAMP' => PropelTypes::TIMESTAMP, - 'VARCHAR2' => PropelTypes::VARCHAR, - ); - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$oracleTypeMap; - } - - /** - * Searches for tables in the database. Maybe we want to search also the views. - * @param Database $database The Database model class to add tables to. - */ - public function parse(Database $database, PDOTask $task = null) - { - $tables = array(); - $stmt = $this->dbh->query("SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE'"); - - $task->log("Reverse Engineering Table Structures"); - // First load the tables (important that this happen before filling out details of tables) - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if (strpos($row['OBJECT_NAME'], '$') !== false) { - // this is an Oracle internal table or materialized view - prune - continue; - } - $table = new Table($row['OBJECT_NAME']); - $task->log("Adding table '" . $table->getName() . "'"); - $database->addTable($table); - // Add columns, primary keys and indexes. - $this->addColumns($table); - $this->addPrimaryKey($table); - $this->addIndexes($table); - $tables[] = $table; - } - - $task->log("Reverse Engineering Foreign Keys"); - - foreach ($tables as $table) { - $task->log("Adding foreign keys for table '" . $table->getName() . "'"); - $this->addForeignKeys($table); - } - - return count($tables); - } - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_LENGTH, DATA_SCALE, DATA_DEFAULT FROM USER_TAB_COLS WHERE TABLE_NAME = '" . $table->getName() . "'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if (strpos($row['COLUMN_NAME'], '$') !== false) { - // this is an Oracle internal column - prune - continue; - } - $size = $row["DATA_LENGTH"]; - $scale = $row["DATA_SCALE"]; - $default = $row['DATA_DEFAULT']; - $type = $row["DATA_TYPE"]; - $isNullable = ($row['NULLABLE'] == 'Y'); - if ($type == "NUMBER" && $row["DATA_SCALE"] > 0) { - $type = "DECIMAL"; - } - if ($type == "FLOAT"&& $row["DATA_PRECISION"] == 126) { - $type = "DOUBLE"; - } - if (strpos($type, 'TIMESTAMP(') !== false) { - $type = substr($type, 0, strpos($type, '(')); - $default = "0000-00-00 00:00:00"; - $size = null; - $scale = null; - } - if ($type == "DATE") { - $default = "0000-00-00"; - $size = null; - $scale = null; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn("Column [" . $table->getName() . "." . $row['COLUMN_NAME']. "] has a column type (".$row["DATA_TYPE"].") that Propel does not support."); - } - - $column = new Column($row['COLUMN_NAME']); - $column->setPhpName(); // Prevent problems with strange col names - $column->setTable($table); - $column->setDomainForType($propelType); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE)); - } - $column->setAutoIncrement(false); // Not yet supported - $column->setNotNull(!$isNullable); - $table->addColumn($column); - } - - } // addColumn() - - /** - * Adds Indexes to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME, INDEX_NAME FROM USER_IND_COLUMNS WHERE TABLE_NAME = '" . $table->getName() . "' ORDER BY COLUMN_NAME"); - $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - - $indices = array(); - foreach ($rows as $row) { - $indices[$row['INDEX_NAME']][]= $row['COLUMN_NAME']; - } - - foreach ($indices as $indexName => $columnNames) { - $index = new Index($indexName); - foreach($columnNames AS $columnName) { - // Oracle deals with complex indices using an internal reference, so... - // let's ignore this kind of index - if ($table->hasColumn($columnName)) { - $index->addColumn($table->getColumn($columnName)); - } - } - // since some of the columns are pruned above, we must only add an index if it has columns - if ($index->hasColumns()) { - $table->addIndex($index); - } - } - } - - /** - * Load foreign keys for this table. - * - * @param Table $table The Table model class to add FKs to - */ - protected function addForeignKeys(Table $table) - { - // local store to avoid duplicates - $foreignKeys = array(); - - $stmt = $this->dbh->query("SELECT CONSTRAINT_NAME, DELETE_RULE, R_CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'R' AND TABLE_NAME = '" . $table->getName(). "'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - // Local reference - $stmt2 = $this->dbh->query("SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '".$row['CONSTRAINT_NAME']."' AND TABLE_NAME = '" . $table->getName(). "'"); - /* @var stmt2 PDOStatement */ - $localReferenceInfo = $stmt2->fetch(PDO::FETCH_ASSOC); - - // Foreign reference - $stmt2 = $this->dbh->query("SELECT TABLE_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '".$row['R_CONSTRAINT_NAME']."'"); - $foreignReferenceInfo = $stmt2->fetch(PDO::FETCH_ASSOC); - - if (!isset($foreignKeys[$row["CONSTRAINT_NAME"]])) { - $fk = new ForeignKey($row["CONSTRAINT_NAME"]); - $fk->setForeignTableName($foreignReferenceInfo['TABLE_NAME']); - $onDelete = ($row["DELETE_RULE"] == 'NO ACTION') ? 'NONE' : $row["DELETE_RULE"]; - $fk->setOnDelete($onDelete); - $fk->setOnUpdate($onDelete); - $fk->addReference(array("local" => $localReferenceInfo['COLUMN_NAME'], "foreign" => $foreignReferenceInfo['COLUMN_NAME'])); - $table->addForeignKey($fk); - $foreignKeys[$row["CONSTRAINT_NAME"]] = $fk; - } - } - } - - /** - * Loads the primary key for this table. - * - * @param Table $table The Table model class to add PK to. - */ - protected function addPrimaryKey(Table $table) - { - $stmt = $this->dbh->query("SELECT COLS.COLUMN_NAME FROM USER_CONSTRAINTS CONS, USER_CONS_COLUMNS COLS WHERE CONS.CONSTRAINT_NAME = COLS.CONSTRAINT_NAME AND CONS.TABLE_NAME = '".$table->getName()."' AND CONS.CONSTRAINT_TYPE = 'P'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - // This fixes a strange behavior by PDO. Sometimes the - // row values are inside an index 0 of an array - if (array_key_exists(0, $row)) { - $row = $row[0]; - } - $table->getColumn($row['COLUMN_NAME'])->setPrimaryKey(true); - } - } - -} - diff --git a/airtime_mvc/library/propel/generator/lib/reverse/pgsql/PgsqlSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/pgsql/PgsqlSchemaParser.php deleted file mode 100644 index 8acfb1885..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/pgsql/PgsqlSchemaParser.php +++ /dev/null @@ -1,548 +0,0 @@ - - * @version $Revision: 1667 $ - * @package propel.generator.reverse.pgsql - */ -class PgsqlSchemaParser extends BaseSchemaParser -{ - - /** - * Map PostgreSQL native types to Propel types. - * @var array - */ - /** Map MySQL native types to Propel (JDBC) types. */ - private static $pgsqlTypeMap = array( - 'bool' => PropelTypes::BOOLEAN, - 'boolean' => PropelTypes::BOOLEAN, - 'tinyint' => PropelTypes::TINYINT, - 'smallint' => PropelTypes::SMALLINT, - 'mediumint' => PropelTypes::SMALLINT, - 'int' => PropelTypes::INTEGER, - 'int4' => PropelTypes::INTEGER, - 'integer' => PropelTypes::INTEGER, - 'int8' => PropelTypes::BIGINT, - 'bigint' => PropelTypes::BIGINT, - 'int24' => PropelTypes::BIGINT, - 'real' => PropelTypes::REAL, - 'float' => PropelTypes::FLOAT, - 'decimal' => PropelTypes::DECIMAL, - 'numeric' => PropelTypes::NUMERIC, - 'double' => PropelTypes::DOUBLE, - 'char' => PropelTypes::CHAR, - 'varchar' => PropelTypes::VARCHAR, - 'date' => PropelTypes::DATE, - 'time' => PropelTypes::TIME, - 'timetz' => PropelTypes::TIME, - //'year' => PropelTypes::YEAR, PropelTypes::YEAR does not exist... does this need to be mapped to a different propel type? - 'datetime' => PropelTypes::TIMESTAMP, - 'timestamp' => PropelTypes::TIMESTAMP, - 'timestamptz' => PropelTypes::TIMESTAMP, - 'bytea' => PropelTypes::BLOB, - 'text' => PropelTypes::LONGVARCHAR, - ); - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$pgsqlTypeMap; - } - - /** - * - */ - public function parse(Database $database, PDOTask $task = null) - { - $stmt = $this->dbh->query("SELECT version() as ver"); - $nativeVersion = $stmt->fetchColumn(); - - if (!$nativeVersion) { - throw new EngineException("Failed to get database version"); - } - - $arrVersion = sscanf ($nativeVersion, '%*s %d.%d'); - $version = sprintf ("%d.%d", $arrVersion[0], $arrVersion[1]); - - // Clean up - $stmt = null; - - $stmt = $this->dbh->query("SELECT c.oid, - case when n.nspname='public' then c.relname else n.nspname||'.'||c.relname end as relname - FROM pg_class c join pg_namespace n on (c.relnamespace=n.oid) - WHERE c.relkind = 'r' - AND n.nspname NOT IN ('information_schema','pg_catalog') - AND n.nspname NOT LIKE 'pg_temp%' - AND n.nspname NOT LIKE 'pg_toast%' - ORDER BY relname"); - - $tableWraps = array(); - - // First load the tables (important that this happen before filling out details of tables) - $task->log("Reverse Engineering Tables"); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $name = $row['relname']; - $task->log(" Adding table '" . $name . "'"); - $oid = $row['oid']; - $table = new Table($name); - $database->addTable($table); - - // Create a wrapper to hold these tables and their associated OID - $wrap = new stdClass; - $wrap->table = $table; - $wrap->oid = $oid; - $tableWraps[] = $wrap; - } - - // Now populate only columns. - $task->log("Reverse Engineering Columns"); - foreach ($tableWraps as $wrap) { - $task->log(" Adding columns for table '" . $wrap->table->getName() . "'"); - $this->addColumns($wrap->table, $wrap->oid, $version); - } - - // Now add indexes and constraints. - $task->log("Reverse Engineering Indices And Constraints"); - foreach ($tableWraps as $wrap) { - $task->log(" Adding indices and constraints for table '" . $wrap->table->getName() . "'"); - $this->addForeignKeys($wrap->table, $wrap->oid, $version); - $this->addIndexes($wrap->table, $wrap->oid, $version); - $this->addPrimaryKey($wrap->table, $wrap->oid, $version); - } - - // TODO - Handle Sequences ... - - return count($tableWraps); - - } - - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - * @param int $oid The table OID - * @param string $version The database version. - */ - protected function addColumns(Table $table, $oid, $version) - { - - // Get the columns, types, etc. - // Based on code from pgAdmin3 (http://www.pgadmin.org/) - $stmt = $this->dbh->prepare("SELECT - att.attname, - att.atttypmod, - att.atthasdef, - att.attnotnull, - def.adsrc, - CASE WHEN att.attndims > 0 THEN 1 ELSE 0 END AS isarray, - CASE - WHEN ty.typname = 'bpchar' - THEN 'char' - WHEN ty.typname = '_bpchar' - THEN '_char' - ELSE - ty.typname - END AS typname, - ty.typtype - FROM pg_attribute att - JOIN pg_type ty ON ty.oid=att.atttypid - LEFT OUTER JOIN pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum - WHERE att.attrelid = ? AND att.attnum > 0 - AND att.attisdropped IS FALSE - ORDER BY att.attnum"); - - $stmt->bindValue(1, $oid, PDO::PARAM_INT); - $stmt->execute(); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $size = null; - $precision = null; - $scale = null; - - // Check to ensure that this column isn't an array data type - if (((int) $row['isarray']) === 1) { - throw new EngineException (sprintf ("Array datatypes are not currently supported [%s.%s]", $this->name, $row['attname'])); - } // if (((int) $row['isarray']) === 1) - - $name = $row['attname']; - - // If they type is a domain, Process it - if (strtolower ($row['typtype']) == 'd') { - $arrDomain = $this->processDomain ($row['typname']); - $type = $arrDomain['type']; - $size = $arrDomain['length']; - $precision = $size; - $scale = $arrDomain['scale']; - $boolHasDefault = (strlen (trim ($row['atthasdef'])) > 0) ? $row['atthasdef'] : $arrDomain['hasdefault']; - $default = (strlen (trim ($row['adsrc'])) > 0) ? $row['adsrc'] : $arrDomain['default']; - $is_nullable = (strlen (trim ($row['attnotnull'])) > 0) ? $row['attnotnull'] : $arrDomain['notnull']; - $is_nullable = (($is_nullable == 't') ? false : true); - } else { - $type = $row['typname']; - $arrLengthPrecision = $this->processLengthScale ($row['atttypmod'], $type); - $size = $arrLengthPrecision['length']; - $precision = $size; - $scale = $arrLengthPrecision['scale']; - $boolHasDefault = $row['atthasdef']; - $default = $row['adsrc']; - $is_nullable = (($row['attnotnull'] == 't') ? false : true); - } // else (strtolower ($row['typtype']) == 'd') - - $autoincrement = null; - - // if column has a default - if (($boolHasDefault == 't') && (strlen (trim ($default)) > 0)) { - if (!preg_match('/^nextval\(/', $default)) { - $strDefault= preg_replace ('/::[\W\D]*/', '', $default); - $default = str_replace ("'", '', $strDefault); - } else { - $autoincrement = true; - $default = null; - } - } else { - $default = null; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$type.") that Propel does not support."); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - if (in_array($default, array('now()'))) { - $type = ColumnDefaultValue::TYPE_EXPR; - } else { - $type = ColumnDefaultValue::TYPE_VALUE; - } - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, $type)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull(!$is_nullable); - - $table->addColumn($column); - } - - - } // addColumn() - - private function processLengthScale($intTypmod, $strName) - { - // Define the return array - $arrRetVal = array ('length'=>null, 'scale'=>null); - - // Some datatypes don't have a Typmod - if ($intTypmod == -1) - { - return $arrRetVal; - } // if ($intTypmod == -1) - - // Numeric Datatype? - if ($strName == $this->getMappedNativeType(PropelTypes::NUMERIC)) { - $intLen = ($intTypmod - 4) >> 16; - $intPrec = ($intTypmod - 4) & 0xffff; - $intLen = sprintf ("%ld", $intLen); - if ($intPrec) - { - $intPrec = sprintf ("%ld", $intPrec); - } // if ($intPrec) - $arrRetVal['length'] = $intLen; - $arrRetVal['scale'] = $intPrec; - } // if ($strName == $this->getMappedNativeType(PropelTypes::NUMERIC)) - elseif ($strName == $this->getMappedNativeType(PropelTypes::TIME) || $strName == 'timetz' - || $strName == $this->getMappedNativeType(PropelTypes::TIMESTAMP) || $strName == 'timestamptz' - || $strName == 'interval' || $strName == 'bit') - { - $arrRetVal['length'] = sprintf ("%ld", $intTypmod); - } // elseif (TIME, TIMESTAMP, INTERVAL, BIT) - else - { - $arrRetVal['length'] = sprintf ("%ld", ($intTypmod - 4)); - } // else - return $arrRetVal; - } // private function processLengthScale ($intTypmod, $strName) - - private function processDomain($strDomain) - { - if (strlen(trim ($strDomain)) < 1) { - throw new EngineException ("Invalid domain name [" . $strDomain . "]"); - } - - $stmt = $this->dbh->prepare("SELECT - d.typname as domname, - b.typname as basetype, - d.typlen, - d.typtypmod, - d.typnotnull, - d.typdefault - FROM pg_type d - INNER JOIN pg_type b ON b.oid = CASE WHEN d.typndims > 0 then d.typelem ELSE d.typbasetype END - WHERE - d.typtype = 'd' - AND d.typname = ? - ORDER BY d.typname"); - $stmt->bindValue(1, $strDomain); - $stmt->execute(); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) { - throw new EngineException ("Domain [" . $strDomain . "] not found."); - } - - $arrDomain = array (); - $arrDomain['type'] = $row['basetype']; - $arrLengthPrecision = $this->processLengthScale($row['typtypmod'], $row['basetype']); - $arrDomain['length'] = $arrLengthPrecision['length']; - $arrDomain['scale'] = $arrLengthPrecision['scale']; - $arrDomain['notnull'] = $row['typnotnull']; - $arrDomain['default'] = $row['typdefault']; - $arrDomain['hasdefault'] = (strlen (trim ($row['typdefault'])) > 0) ? 't' : 'f'; - - $stmt = null; // cleanup - return $arrDomain; - } // private function processDomain($strDomain) - - /** - * Load foreign keys for this table. - */ - protected function addForeignKeys(Table $table, $oid, $version) - { - $database = $table->getDatabase(); - $stmt = $this->dbh->prepare("SELECT - conname, - confupdtype, - confdeltype, - CASE nl.nspname WHEN 'public' THEN cl.relname ELSE nl.nspname||'.'||cl.relname END as fktab, - a2.attname as fkcol, - CASE nr.nspname WHEN 'public' THEN cr.relname ELSE nr.nspname||'.'||cr.relname END as reftab, - a1.attname as refcol - FROM pg_constraint ct - JOIN pg_class cl ON cl.oid=conrelid - JOIN pg_class cr ON cr.oid=confrelid - JOIN pg_namespace nl ON nl.oid = cl.relnamespace - JOIN pg_namespace nr ON nr.oid = cr.relnamespace - LEFT JOIN pg_catalog.pg_attribute a1 ON a1.attrelid = ct.confrelid - LEFT JOIN pg_catalog.pg_attribute a2 ON a2.attrelid = ct.conrelid - WHERE - contype='f' - AND conrelid = ? - AND a2.attnum = ct.conkey[1] - AND a1.attnum = ct.confkey[1] - ORDER BY conname"); - $stmt->bindValue(1, $oid); - $stmt->execute(); - - $foreignKeys = array(); // local store to avoid duplicates - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['conname']; - $local_table = $row['fktab']; - $local_column = $row['fkcol']; - $foreign_table = $row['reftab']; - $foreign_column = $row['refcol']; - - // On Update - switch ($row['confupdtype']) { - case 'c': - $onupdate = ForeignKey::CASCADE; break; - case 'd': - $onupdate = ForeignKey::SETDEFAULT; break; - case 'n': - $onupdate = ForeignKey::SETNULL; break; - case 'r': - $onupdate = ForeignKey::RESTRICT; break; - default: - case 'a': - //NOACTION is the postgresql default - $onupdate = ForeignKey::NONE; break; - } - // On Delete - switch ($row['confdeltype']) { - case 'c': - $ondelete = ForeignKey::CASCADE; break; - case 'd': - $ondelete = ForeignKey::SETDEFAULT; break; - case 'n': - $ondelete = ForeignKey::SETNULL; break; - case 'r': - $ondelete = ForeignKey::RESTRICT; break; - default: - case 'a': - //NOACTION is the postgresql default - $ondelete = ForeignKey::NONE; break; - } - - $foreignTable = $database->getTable($foreign_table); - $foreignColumn = $foreignTable->getColumn($foreign_column); - - $localTable = $database->getTable($local_table); - $localColumn = $localTable->getColumn($local_column); - - if (!isset($foreignKeys[$name])) { - $fk = new ForeignKey($name); - $fk->setForeignTableName($foreignTable->getName()); - $fk->setOnDelete($ondelete); - $fk->setOnUpdate($onupdate); - $table->addForeignKey($fk); - $foreignKeys[$name] = $fk; - } - - $foreignKeys[$name]->addReference($localColumn, $foreignColumn); - } - } - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table, $oid, $version) - { - $stmt = $this->dbh->prepare("SELECT - DISTINCT ON(cls.relname) - cls.relname as idxname, - indkey, - indisunique - FROM pg_index idx - JOIN pg_class cls ON cls.oid=indexrelid - WHERE indrelid = ? AND NOT indisprimary - ORDER BY cls.relname"); - - $stmt->bindValue(1, $oid); - $stmt->execute(); - - $stmt2 = $this->dbh->prepare("SELECT a.attname - FROM pg_catalog.pg_class c JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid - WHERE c.oid = ? AND a.attnum = ? AND NOT a.attisdropped - ORDER BY a.attnum"); - - $indexes = array(); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $name = $row["idxname"]; - $unique = ($row["indisunique"] == 't') ? true : false; - if (!isset($indexes[$name])) { - if ($unique) { - $indexes[$name] = new Unique($name); - } else { - $indexes[$name] = new Index($name); - } - $table->addIndex($indexes[$name]); - } - - $arrColumns = explode (' ', $row['indkey']); - foreach ($arrColumns as $intColNum) - { - $stmt2->bindValue(1, $oid); - $stmt2->bindValue(2, $intColNum); - $stmt2->execute(); - - $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); - - $indexes[$name]->addColumn($table->getColumn($row2['attname'])); - - } // foreach ($arrColumns as $intColNum) - - } - - } - - /** - * Loads the primary key for this table. - */ - protected function addPrimaryKey(Table $table, $oid, $version) - { - - $stmt = $this->dbh->prepare("SELECT - DISTINCT ON(cls.relname) - cls.relname as idxname, - indkey, - indisunique - FROM pg_index idx - JOIN pg_class cls ON cls.oid=indexrelid - WHERE indrelid = ? AND indisprimary - ORDER BY cls.relname"); - $stmt->bindValue(1, $oid); - $stmt->execute(); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $arrColumns = explode (' ', $row['indkey']); - foreach ($arrColumns as $intColNum) { - $stmt2 = $this->dbh->prepare("SELECT a.attname - FROM pg_catalog.pg_class c JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid - WHERE c.oid = ? AND a.attnum = ? AND NOT a.attisdropped - ORDER BY a.attnum"); - $stmt2->bindValue(1, $oid); - $stmt2->bindValue(2, $intColNum); - $stmt2->execute(); - - $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); - $table->getColumn($row2['attname'])->setPrimaryKey(true); - - } // foreach ($arrColumns as $intColNum) - } - - } - - /** - * Adds the sequences for this database. - * - * @return void - * @throws SQLException - */ - protected function addSequences(Database $database) - { - /* - -- WE DON'T HAVE ANY USE FOR THESE YET IN REVERSE ENGINEERING ... - $this->sequences = array(); - $result = pg_query($this->conn->getResource(), "SELECT c.oid, - case when n.nspname='public' then c.relname else n.nspname||'.'||c.relname end as relname - FROM pg_class c join pg_namespace n on (c.relnamespace=n.oid) - WHERE c.relkind = 'S' - AND n.nspname NOT IN ('information_schema','pg_catalog') - AND n.nspname NOT LIKE 'pg_temp%' - AND n.nspname NOT LIKE 'pg_toast%' - ORDER BY relname"); - - if (!$result) { - throw new SQLException("Could not list sequences", pg_last_error($this->dblink)); - } - - while ($row = pg_fetch_assoc($result)) { - // FIXME -- decide what info we need for sequences & then create a SequenceInfo object (if needed) - $obj = new stdClass; - $obj->name = $row['relname']; - $obj->oid = $row['oid']; - $this->sequences[strtoupper($row['relname'])] = $obj; - } - */ - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/reverse/sqlite/SqliteSchemaParser.php b/airtime_mvc/library/propel/generator/lib/reverse/sqlite/SqliteSchemaParser.php deleted file mode 100644 index 518d0d049..000000000 --- a/airtime_mvc/library/propel/generator/lib/reverse/sqlite/SqliteSchemaParser.php +++ /dev/null @@ -1,195 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.generator.reverse.sqlite - */ -class SqliteSchemaParser extends BaseSchemaParser -{ - - /** - * Map Sqlite native types to Propel types. - * - * There really aren't any SQLite native types, so we're just - * using the MySQL ones here. - * - * @var array - */ - private static $sqliteTypeMap = array( - 'tinyint' => PropelTypes::TINYINT, - 'smallint' => PropelTypes::SMALLINT, - 'mediumint' => PropelTypes::SMALLINT, - 'int' => PropelTypes::INTEGER, - 'integer' => PropelTypes::INTEGER, - 'bigint' => PropelTypes::BIGINT, - 'int24' => PropelTypes::BIGINT, - 'real' => PropelTypes::REAL, - 'float' => PropelTypes::FLOAT, - 'decimal' => PropelTypes::DECIMAL, - 'numeric' => PropelTypes::NUMERIC, - 'double' => PropelTypes::DOUBLE, - 'char' => PropelTypes::CHAR, - 'varchar' => PropelTypes::VARCHAR, - 'date' => PropelTypes::DATE, - 'time' => PropelTypes::TIME, - 'year' => PropelTypes::INTEGER, - 'datetime' => PropelTypes::TIMESTAMP, - 'timestamp' => PropelTypes::TIMESTAMP, - 'tinyblob' => PropelTypes::BINARY, - 'blob' => PropelTypes::BLOB, - 'mediumblob' => PropelTypes::BLOB, - 'longblob' => PropelTypes::BLOB, - 'longtext' => PropelTypes::CLOB, - 'tinytext' => PropelTypes::VARCHAR, - 'mediumtext' => PropelTypes::LONGVARCHAR, - 'text' => PropelTypes::LONGVARCHAR, - 'enum' => PropelTypes::CHAR, - 'set' => PropelTypes::CHAR, - ); - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$sqliteTypeMap; - } - - /** - * - */ - public function parse(Database $database, PDOTask $task = null) - { - $stmt = $this->dbh->query("SELECT name FROM sqlite_master WHERE type='table' UNION ALL SELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name;"); - - // First load the tables (important that this happen before filling out details of tables) - $tables = array(); - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $row[0]; - $table = new Table($name); - $database->addTable($table); - $tables[] = $table; - } - - // Now populate only columns. - foreach ($tables as $table) { - $this->addColumns($table); - } - - // Now add indexes and constraints. - foreach ($tables as $table) { - $this->addIndexes($table); - } - - return count($tables); - - } - - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - * @param int $oid The table OID - * @param string $version The database version. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("PRAGMA table_info('" . $table->getName() . "')"); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['name']; - - $fulltype = $row['type']; - $size = null; - $precision = null; - $scale = null; - - if (preg_match('/^([^\(]+)\(\s*(\d+)\s*,\s*(\d+)\s*\)$/', $fulltype, $matches)) { - $type = $matches[1]; - $precision = $matches[2]; - $scale = $matches[3]; // aka precision - } elseif (preg_match('/^([^\(]+)\(\s*(\d+)\s*\)$/', $fulltype, $matches)) { - $type = $matches[1]; - $size = $matches[2]; - } else { - $type = $fulltype; - } - // If column is primary key and of type INTEGER, it is auto increment - // See: http://sqlite.org/faq.html#q1 - $autoincrement = ($row['pk'] == 1 && strtolower($type) == 'integer'); - $not_null = $row['notnull']; - $default = $row['dflt_value']; - - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$type.") that Propel does not support."); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull($not_null); - - - if (($row['pk'] == 1) || (strtolower($type) == 'integer')) { - $column->setPrimaryKey(true); - } - - $table->addColumn($column); - - } - - - } // addColumn() - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("PRAGMA index_list('" . $table->getName() . "')"); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['name']; - $index = new Index($name); - - $stmt2 = $this->dbh->query("PRAGMA index_info('".$name."')"); - while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)) { - $colname = $row2['name']; - $index->addColumn($table->getColumn($colname)); - } - - $table->addIndex($index); - - } - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/task/AbstractPropelDataModelTask.php b/airtime_mvc/library/propel/generator/lib/task/AbstractPropelDataModelTask.php deleted file mode 100644 index 597efff24..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/AbstractPropelDataModelTask.php +++ /dev/null @@ -1,593 +0,0 @@ - (Propel) - * @author Jason van Zyl (Torque) - * @author Daniel Rall (Torque) - * @package propel.generator.task - */ -abstract class AbstractPropelDataModelTask extends Task -{ - - /** - * Fileset of XML schemas which represent our data models. - * @var array Fileset[] - */ - protected $schemaFilesets = array(); - - /** - * Data models that we collect. One from each XML schema file. - */ - protected $dataModels = array(); - - /** - * Have datamodels been initialized? - * @var boolean - */ - private $dataModelsLoaded = false; - - /** - * Map of data model name to database name. - * Should probably stick to the convention - * of them being the same but I know right now - * in a lot of cases they won't be. - */ - protected $dataModelDbMap; - - /** - * The target database(s) we are generating SQL - * for. Right now we can only deal with a single - * target, but we will support multiple targets - * soon. - */ - protected $targetDatabase; - - /** - * DB encoding to use for XmlToAppData object - */ - protected $dbEncoding = 'iso-8859-1'; - - /** - * Target PHP package to place the generated files in. - */ - protected $targetPackage; - - /** - * @var Mapper - */ - protected $mapperElement; - - /** - * Destination directory for results of template scripts. - * @var PhingFile - */ - protected $outputDirectory; - - /** - * Whether to package the datamodels or not - * @var PhingFile - */ - protected $packageObjectModel; - - /** - * Whether to perform validation (XSD) on the schema.xml file(s). - * @var boolean - */ - protected $validate; - - /** - * The XSD schema file to use for validation. - * @var PhingFile - */ - protected $xsdFile; - - /** - * XSL file to use to normalize (or otherwise transform) schema before validation. - * @var PhingFile - */ - protected $xslFile; - - /** - * Optional database connection url. - * @var string - */ - private $url = null; - - /** - * Optional database connection user name. - * @var string - */ - private $userId = null; - - /** - * Optional database connection password. - * @var string - */ - private $password = null; - - /** - * PDO Connection. - * @var PDO - */ - private $conn = false; - - /** - * An initialized GeneratorConfig object containing the converted Phing props. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * Return the data models that have been - * processed. - * - * @return List data models - */ - public function getDataModels() - { - if (!$this->dataModelsLoaded) { - $this->loadDataModels(); - } - return $this->dataModels; - } - - /** - * Return the data model to database name map. - * - * @return Hashtable data model name to database name map. - */ - public function getDataModelDbMap() - { - if (!$this->dataModelsLoaded) { - $this->loadDataModels(); - } - return $this->dataModelDbMap; - } - - /** - * Adds a set of xml schema files (nested fileset attribute). - * - * @param set a Set of xml schema files - */ - public function addSchemaFileset(Fileset $set) - { - $this->schemaFilesets[] = $set; - } - - /** - * Get the current target database. - * - * @return String target database(s) - */ - public function getTargetDatabase() - { - return $this->targetDatabase; - } - - /** - * Set the current target database. (e.g. mysql, oracle, ..) - * - * @param v target database(s) - */ - public function setTargetDatabase($v) - { - $this->targetDatabase = $v; - } - - /** - * Get the current target package. - * - * @return string target PHP package. - */ - public function getTargetPackage() - { - return $this->targetPackage; - } - - /** - * Set the current target package. This is where generated PHP classes will - * live. - * - * @param string $v target PHP package. - */ - public function setTargetPackage($v) - { - $this->targetPackage = $v; - } - - /** - * Set the packageObjectModel switch on/off - * - * @param string $v The build.property packageObjectModel - */ - public function setPackageObjectModel($v) - { - $this->packageObjectModel = ($v === '1' ? true : false); - } - - /** - * Set whether to perform validation on the datamodel schema.xml file(s). - * @param boolean $v - */ - public function setValidate($v) - { - $this->validate = $v; - } - - /** - * Set the XSD schema to use for validation of any datamodel schema.xml file(s). - * @param $v PhingFile - */ - public function setXsd(PhingFile $v) - { - $this->xsdFile = $v; - } - - /** - * Set the normalization XSLT to use to transform datamodel schema.xml file(s) before validation and parsing. - * @param $v PhingFile - */ - public function setXsl(PhingFile $v) - { - $this->xslFile = $v; - } - - /** - * [REQUIRED] Set the output directory. It will be - * created if it doesn't exist. - * @param PhingFile $outputDirectory - * @return void - * @throws Exception - */ - public function setOutputDirectory(PhingFile $outputDirectory) { - try { - if (!$outputDirectory->exists()) { - $this->log("Output directory does not exist, creating: " . $outputDirectory->getPath(),Project::MSG_VERBOSE); - if (!$outputDirectory->mkdirs()) { - throw new IOException("Unable to create Ouptut directory: " . $outputDirectory->getAbsolutePath()); - } - } - $this->outputDirectory = $outputDirectory->getCanonicalPath(); - } catch (IOException $ioe) { - throw new BuildException($ioe); - } - } - - /** - * Set the current target database encoding. - * - * @param v target database encoding - */ - public function setDbEncoding($v) - { - $this->dbEncoding = $v; - } - - /** - * Set the DB connection url. - * - * @param string $url connection url - */ - public function setUrl($url) - { - $this->url = $url; - } - - /** - * Set the user name for the DB connection. - * - * @param string $userId database user - */ - public function setUserid($userId) - { - $this->userId = $userId; - } - - /** - * Set the password for the DB connection. - * - * @param string $password database password - */ - public function setPassword($password) - { - $this->password = $password; - } - - /** - * Get the output directory. - * @return string - */ - public function getOutputDirectory() { - return $this->outputDirectory; - } - - /** - * Nested creator, creates one Mapper for this task. - * - * @return Mapper The created Mapper type object. - * @throws BuildException - */ - public function createMapper() { - if ($this->mapperElement !== null) { - throw new BuildException("Cannot define more than one mapper.", $this->location); - } - $this->mapperElement = new Mapper($this->project); - return $this->mapperElement; - } - - /** - * Maps the passed in name to a new filename & returns resolved File object. - * @param string $from - * @return PhingFile Resolved File object. - * @throws BuilException - if no Mapper element se - * - if unable to map new filename. - */ - protected function getMappedFile($from) - { - if (!$this->mapperElement) { - throw new BuildException("This task requires you to use a element to describe how filename changes should be handled."); - } - - $mapper = $this->mapperElement->getImplementation(); - $mapped = $mapper->main($from); - if (!$mapped) { - throw new BuildException("Cannot create new filename based on: " . $from); - } - // Mappers always return arrays since it's possible for some mappers to map to multiple names. - $outFilename = array_shift($mapped); - $outFile = new PhingFile($this->getOutputDirectory(), $outFilename); - return $outFile; - } - - /** - * Gets the PDO connection, if URL specified. - * @return PDO Connection to use (for quoting, Platform class, etc.) or NULL if no connection params were specified. - */ - public function getConnection() - { - if ($this->conn === false) { - $this->conn = null; - if ($this->url) { - $buf = "Using database settings:\n" - . " URL: " . $this->url . "\n" - . ($this->userId ? " user: " . $this->userId . "\n" : "") - . ($this->password ? " password: " . $this->password . "\n" : ""); - - $this->log($buf, Project::MSG_VERBOSE); - - // Set user + password to null if they are empty strings - if (!$this->userId) { $this->userId = null; } - if (!$this->password) { $this->password = null; } - try { - $this->conn = new PDO($this->url, $this->userId, $this->password); - $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } catch (PDOException $x) { - $this->log("Unable to create a PDO connection: " . $x->getMessage(), Project::MSG_WARN); - } - } - } - return $this->conn; - } - - /** - * Gets all matching XML schema files and loads them into data models for class. - * @return void - */ - protected function loadDataModels() - { - $ads = array(); - - // Get all matched files from schemaFilesets - foreach ($this->schemaFilesets as $fs) { - $ds = $fs->getDirectoryScanner($this->project); - $srcDir = $fs->getDir($this->project); - - $dataModelFiles = $ds->getIncludedFiles(); - - $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); - - // Make a transaction for each file - foreach ($dataModelFiles as $dmFilename) { - - $this->log("Processing: ".$dmFilename); - $xmlFile = new PhingFile($srcDir, $dmFilename); - - $dom = new DomDocument('1.0', 'UTF-8'); - $dom->load($xmlFile->getAbsolutePath()); - - // modify schema to include any external schemas (and remove the external-schema nodes) - $this->includeExternalSchemas($dom, $srcDir); - - // normalize (or transform) the XML document using XSLT - if ($this->getGeneratorConfig()->getBuildProperty('schemaTransform') && $this->xslFile) { - $this->log("Transforming " . $xmlFile->getPath() . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE); - if (!class_exists('XSLTProcessor')) { - $this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR); - } else { - // normalize the document using normalizer stylesheet - $xslDom = new DomDocument('1.0', 'UTF-8'); - $xslDom->load($this->xslFile->getAbsolutePath()); - $xsl = new XsltProcessor(); - $xsl->importStyleSheet($xslDom); - $dom = $xsl->transformToDoc($dom); - } - } - - // validate the XML document using XSD schema - if ($this->validate && $this->xsdFile) { - $this->log("Validating XML doc (".$xmlFile->getPath().") using schema file " . $this->xsdFile->getPath(), Project::MSG_VERBOSE); - if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) { - throw new EngineException("XML schema file (".$xmlFile->getPath().") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation()); - } - } - - $xmlParser = new XmlToAppData($platform, $this->getTargetPackage(), $this->dbEncoding); - $ad = $xmlParser->parseString($dom->saveXML(), $xmlFile->getAbsolutePath()); - - $ad->setName($dmFilename); - $ads[] = $ad; - } - } - - if (empty($ads)) { - throw new BuildException("No schema files were found (matching your schema fileset definition)."); - } - - foreach ($ads as $ad) { - // map schema filename with database name - $this->dataModelDbMap[$ad->getName()] = $ad->getDatabase(null, false)->getName(); - } - - if (count($ads)>1 && $this->packageObjectModel) { - $ad = $this->joinDataModels($ads); - $this->dataModels = array($ad); - } else { - $this->dataModels = $ads; - } - - foreach ($this->dataModels as &$ad) { - $ad->doFinalInitialization(); - } - - $this->dataModelsLoaded = true; - } - - /** - * Replaces all external-schema nodes with the content of xml schema that node refers to - * - * Recurses to include any external schema referenced from in an included xml (and deeper) - * Note: this function very much assumes at least a reasonable XML schema, maybe it'll proof - * users don't have those and adding some more informative exceptions would be better - * - * @param DomDocument $dom - * @param string $srcDir - * @return void (objects, DomDocument, are references by default in PHP 5, so returning it is useless) - **/ - protected function includeExternalSchemas(DomDocument $dom, $srcDir) { - $databaseNode = $dom->getElementsByTagName("database")->item(0); - $externalSchemaNodes = $dom->getElementsByTagName("external-schema"); - $fs = FileSystem::getFileSystem(); - $nbIncludedSchemas = 0; - while ($externalSchema = $externalSchemaNodes->item(0)) { - $include = $externalSchema->getAttribute("filename"); - $this->log("Processing external schema: ".$include); - $externalSchema->parentNode->removeChild($externalSchema); - if ($fs->prefixLength($include) != 0) { - $externalSchemaFile = new PhingFile($include); - } else { - $externalSchemaFile = new PhingFile($srcDir, $include); - } - $externalSchemaDom = new DomDocument('1.0', 'UTF-8'); - $externalSchemaDom->load($externalSchemaFile->getAbsolutePath()); - // The external schema may have external schemas of its own ; recurse - $this->includeExternalSchemas($externalSchemaDom, $srcDir); - foreach ($externalSchemaDom->getElementsByTagName("table") as $tableNode) { // see xsd, datatase may only have table or external-schema, the latter was just deleted so this should cover everything - $databaseNode->appendChild($dom->importNode($tableNode, true)); - } - $nbIncludedSchemas++; - } - return $nbIncludedSchemas; - } - - /** - * Joins the datamodels collected from schema.xml files into one big datamodel. - * We need to join the datamodels in this case to allow for foreign keys - * that point to tables in different packages. - * - * @param array[AppData] $ads The datamodels to join - * @return AppData The single datamodel with all other datamodels joined in - */ - protected function joinDataModels($ads) - { - $mainAppData = null; - foreach ($ads as $appData) { - if (null === $mainAppData) { - $mainAppData = $appData; - $appData->setName('JoinedDataModel'); - continue; - } - // merge subsequent schemas to the first one - foreach ($appData->getDatabases(false) as $addDb) { - $addDbName = $addDb->getName(); - if ($mainAppData->hasDatabase($addDbName)) { - $db = $mainAppData->getDatabase($addDbName, false); - // join tables - foreach ($addDb->getTables() as $addTable) { - if ($db->getTable($addTable->getName())) { - throw new BuildException('Duplicate table found: ' . $addDbName . '.'); - } - $db->addTable($addTable); - } - // join database behaviors - foreach ($addDb->getBehaviors() as $addBehavior) { - if (!$db->hasBehavior($addBehavior->getName())) { - $db->addBehavior($addBehavior); - } - } - } else { - $mainAppData->addDatabase($addDb); - } - } - } - return $mainAppData; - } - - /** - * Gets the GeneratorConfig object for this task or creates it on-demand. - * @return GeneratorConfig - */ - protected function getGeneratorConfig() - { - if ($this->generatorConfig === null) { - $this->generatorConfig = new GeneratorConfig(); - $this->generatorConfig->setBuildProperties($this->getProject()->getProperties()); - } - return $this->generatorConfig; - } - - /** - * Checks this class against Basic requrements of any propel datamodel task. - * - * @throws BuildException - if schema fileset was not defined - * - if no output directory was specified - */ - protected function validate() - { - if (empty($this->schemaFilesets)) { - throw new BuildException("You must specify a fileset of XML schemas.", $this->getLocation()); - } - - // Make sure the output directory is set. - if ($this->outputDirectory === null) { - throw new BuildException("The output directory needs to be defined!", $this->getLocation()); - } - - if ($this->validate) { - if (!$this->xsdFile) { - throw new BuildException("'validate' set to TRUE, but no XSD specified (use 'xsd' attribute).", $this->getLocation()); - } - } - - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelConvertConfTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelConvertConfTask.php deleted file mode 100644 index 53865c0d6..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelConvertConfTask.php +++ /dev/null @@ -1,344 +0,0 @@ - - * @package propel.generator.task - */ -class PropelConvertConfTask extends AbstractPropelDataModelTask -{ - - /** - * @var PhingFile The XML runtime configuration file to be converted. - */ - private $xmlConfFile; - - /** - * @var string This is the file where the converted conf array dump will be placed. - */ - private $outputFile; - - /** - * @var string This is the file where the classmap manifest converted conf array dump will be placed. - */ - private $outputClassmapFile; - - /** - * [REQUIRED] Set the input XML runtime conf file. - * @param PhingFile $v The XML runtime configuration file to be converted. - */ - public function setXmlConfFile(PhingFile $v) - { - $this->xmlConfFile = $v; - } - - /** - * [REQUIRED] Set the output filename for the converted runtime conf. - * The directory is specified using AbstractPropelDataModelTask#setOutputDirectory(). - * @param string $outputFile - * @see AbstractPropelDataModelTask#setOutputDirectory() - */ - public function setOutputFile($outputFile) - { - // this is a string, not a file - $this->outputFile = $outputFile; - } - - /** - * [REQUIRED] Set the output filename for the autoload classmap. - * The directory is specified using AbstractPropelDataModelTask#setOutputDirectory(). - * @param string $outputFile - * @see AbstractPropelDataModelTask#setOutputDirectory() - */ - public function setOutputClassmapFile($outputFile) - { - // this is a string, not a file - $this->outputClassmapFile = $outputFile; - } - - /** - * The main method does the work of the task. - */ - public function main() - { - // Check to make sure the input and output files were specified and that the input file exists. - - if (!$this->xmlConfFile || !$this->xmlConfFile->exists()) { - throw new BuildException("No valid xmlConfFile specified.", $this->getLocation()); - } - - if (!$this->outputFile) { - throw new BuildException("No outputFile specified.", $this->getLocation()); - } - - // Create a PHP array from the runtime-conf.xml file - - $xmlDom = new DOMDocument(); - $xmlDom->load($this->xmlConfFile->getAbsolutePath()); - $xml = simplexml_load_string($xmlDom->saveXML()); - $phpconf = self::simpleXmlToArray($xml); - - /* For some reason the array generated from runtime-conf.xml has separate - * 'log' section and 'propel' sections. To maintain backward compatibility - * we need to put 'log' back into the 'propel' section. - */ - $log = array(); - if (isset($phpconf['log'])) { - $phpconf['propel']['log'] = $phpconf['log']; - unset($phpconf['log']); - } - - if(isset($phpconf['propel'])) { - $phpconf = $phpconf['propel']; - } - - // add generator version - $phpconf['generator_version'] = $this->getGeneratorConfig()->getBuildProperty('version'); - - if (!$this->outputClassmapFile) { - // We'll create a default one for BC - $this->outputClassmapFile = 'classmap-' . $this->outputFile; - } - - // Write resulting PHP data to output file - $outfile = new PhingFile($this->outputDirectory, $this->outputFile); - $output = "getGeneratorConfig()->getBuildProperty('addTimestamp') ? " on " . strftime("%c") : '') . "\n"; - $output .= "// from XML runtime conf file " . $this->xmlConfFile->getPath() . "\n"; - $output .= "\$conf = "; - $output .= var_export($phpconf, true); - $output .= ";\n"; - $output .= "\$conf['classmap'] = include(dirname(__FILE__) . DIRECTORY_SEPARATOR . '".$this->outputClassmapFile."');\n"; - $output .= "return \$conf;"; - - - $this->log("Creating PHP runtime conf file: " . $outfile->getPath()); - if (!file_put_contents($outfile->getAbsolutePath(), $output)) { - throw new BuildException("Error creating output file: " . $outfile->getAbsolutePath(), $this->getLocation()); - } - - // add classmap - $phpconfClassmap = $this->getClassMap(); - $outfile = new PhingFile($this->outputDirectory, $this->outputClassmapFile); - $output = '<' . '?' . "php\n"; - $output .= "// This file generated by Propel " . $phpconf['generator_version'] . " convert-conf target".($this->getGeneratorConfig()->getBuildProperty('addTimestamp') ? " on " . strftime("%c") : '') . "\n"; - $output .= "return "; - $output .= var_export($phpconfClassmap, true); - $output .= ";"; - $this->log("Creating PHP classmap runtime file: " . $outfile->getPath()); - if (!file_put_contents($outfile->getAbsolutePath(), $output)) { - throw new BuildException("Error creating output file: " . $outfile->getAbsolutePath(), $this->getLocation()); - } - - } // main() - - /** - * Recursive function that converts an SimpleXML object into an array. - * @author Christophe VG (based on code form php.net manual comment) - * @param object SimpleXML object. - * @return array Array representation of SimpleXML object. - */ - private static function simpleXmlToArray($xml) - { - $ar = array(); - - foreach ( $xml->children() as $k => $v ) { - - // recurse the child - $child = self::simpleXmlToArray( $v ); - - //print "Recursed down and found: " . var_export($child, true) . "\n"; - - // if it's not an array, then it was empty, thus a value/string - if ( count($child) == 0 ) { - $child = self::getConvertedXmlValue($v); - - } - - // add the childs attributes as if they where children - foreach ( $v->attributes() as $ak => $av ) { - - // if the child is not an array, transform it into one - if ( !is_array( $child ) ) { - $child = array( "value" => $child ); - } - - if ($ak == 'id') { - // special exception: if there is a key named 'id' - // then we will name the current key after that id - $k = self::getConvertedXmlValue($av); - } else { - // otherwise, just add the attribute like a child element - $child[$ak] = self::getConvertedXmlValue($av); - } - } - - // if the $k is already in our children list, we need to transform - // it into an array, else we add it as a value - if ( !in_array( $k, array_keys($ar) ) ) { - $ar[$k] = $child; - } else { - // (This only applies to nested nodes that do not have an @id attribute) - - // if the $ar[$k] element is not already an array, then we need to make it one. - // this is a bit of a hack, but here we check to also make sure that if it is an - // array, that it has numeric keys. this distinguishes it from simply having other - // nested element data. - - if ( !is_array($ar[$k]) || !isset($ar[$k][0]) ) { $ar[$k] = array($ar[$k]); } - $ar[$k][] = $child; - } - - } - - return $ar; - } - - /** - * Process XML value, handling boolean, if appropriate. - * @param object The simplexml value object. - * @return mixed - */ - private static function getConvertedXmlValue($value) - { - $value = (string) $value; // convert from simplexml to string - // handle booleans specially - $lwr = strtolower($value); - if ($lwr === "false") { - $value = false; - } elseif ($lwr === "true") { - $value = true; - } - return $value; - } - - /** - * Lists data model classes and builds an associative array className => classPath - * To be used for autoloading - * @return array - */ - protected function getClassMap() - { - $phpconfClassmap = array(); - - $generatorConfig = $this->getGeneratorConfig(); - - foreach ($this->getDataModels() as $dataModel) { - - foreach ($dataModel->getDatabases() as $database) { - - $classMap = array(); - - foreach ($database->getTables() as $table) { - - if (!$table->isForReferenceOnly()) { - - // ----------------------------------------------------- - // Add TableMap class, - // Peer, Object & Query stub classes, - // and Peer, Object & Query base classes - // ----------------------------------------------------- - // (this code is based on PropelOMTask) - - foreach (array('tablemap', 'peerstub', 'objectstub', 'querystub', 'peer', 'object', 'query') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $this->log("Adding class mapping: " . $builder->getClassname() . ' => ' . $builder->getClassFilePath()); - $classMap[$builder->getFullyQualifiedClassname()] = $builder->getClassFilePath(); - } - - // ----------------------------------------------------- - // Add children classes for object and query, - // as well as base child query, - // for single tabel inheritance tables. - // ----------------------------------------------------- - - if ($col = $table->getChildrenColumn()) { - if ($col->isEnumeratedClasses()) { - foreach ($col->getChildren() as $child) { - foreach (array('objectmultiextend', 'queryinheritance', 'queryinheritancestub') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $builder->setChild($child); - $this->log("Adding class mapping: " . $builder->getClassname() . ' => ' . $builder->getClassFilePath()); - $classMap[$builder->getFullyQualifiedClassname()] = $builder->getClassFilePath(); - } - } - } - } - - // ----------------------------------------------------- - // Add base classes for alias tables (undocumented) - // ----------------------------------------------------- - - $baseClass = $table->getBaseClass(); - if ( $baseClass !== null ) { - $className = ClassTools::classname($baseClass); - if (!isset($classMap[$className])) { - $classPath = ClassTools::getFilePath($baseClass); - $this->log('Adding class mapping: ' . $className . ' => ' . $classPath); - $classMap[$className] = $classPath; - } - } - - $basePeer = $table->getBasePeer(); - if ( $basePeer !== null ) { - $className = ClassTools::classname($basePeer); - if (!isset($classMap[$className])) { - $classPath = ClassTools::getFilePath($basePeer); - $this->log('Adding class mapping: ' . $className . ' => ' . $classPath); - $classMap[$className] = $classPath; - } - } - - // ---------------------------------------------- - // Add classes for interface - // ---------------------------------------------- - - if ($table->getInterface()) { - $builder = $generatorConfig->getConfiguredBuilder($table, 'interface'); - $this->log("Adding class mapping: " . $builder->getClassname() . ' => ' . $builder->getClassFilePath()); - $classMap[$builder->getFullyQualifiedClassname()] = $builder->getClassFilePath(); - } - - // ---------------------------------------------- - // Add classes from old treeMode implementations - // ---------------------------------------------- - - if ($table->treeMode() == 'MaterializedPath') { - foreach (array('nodepeerstub', 'nodestub', 'nodepeer', 'node') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $this->log("Adding class mapping: " . $builder->getClassname() . ' => ' . $builder->getClassFilePath()); - $classMap[$builder->getFullyQualifiedClassname()] = $builder->getClassFilePath(); - } - } - if ($table->treeMode() == 'NestedSet') { - foreach (array('nestedset', 'nestedsetpeer') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $this->log("Adding class mapping: " . $builder->getClassname() . ' => ' . $builder->getClassFilePath()); - $classMap[$builder->getFullyQualifiedClassname()] = $builder->getClassFilePath(); - } - } - - } // if (!$table->isReferenceOnly()) - } - - $phpconfClassmap = array_merge($phpconfClassmap, $classMap); - } - } - - return $phpconfClassmap; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelDataDTDTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelDataDTDTask.php deleted file mode 100644 index 7252ae676..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelDataDTDTask.php +++ /dev/null @@ -1,68 +0,0 @@ - - * @package propel.generator.task - */ -class PropelDataDTDTask extends PropelDataModelTemplateTask -{ - - public function main() - { - // check to make sure task received all correct params - $this->validate(); - - if (!$this->mapperElement) { - throw new BuildException("You must use a element to describe how names should be transformed."); - } - - $basepath = $this->getOutputDirectory(); - - // Get new Capsule context - $generator = $this->createContext(); - $generator->put("basepath", $basepath); // make available to other templates - - // we need some values that were loaded into the template context - $basePrefix = $generator->get('basePrefix'); - $project = $generator->get('project'); - - foreach ($this->getDataModels() as $dataModel) { - - $this->log("Processing Datamodel : " . $dataModel->getName()); - - foreach ($dataModel->getDatabases() as $database) { - - $outFile = $this->getMappedFile($dataModel->getName()); - - $generator->put("tables", $database->getTables()); - $generator->parse("data/dtd/dataset.tpl", $outFile->getAbsolutePath()); - - $this->log("Generating DTD for database: " . $database->getName()); - $this->log("Creating DTD file: " . $outFile->getPath()); - - foreach ($database->getTables() as $tbl) { - $this->log("\t + " . $tbl->getName()); - $generator->put("table", $tbl); - $generator->parse("data/dtd/table.tpl", $outFile->getAbsolutePath(), true); - } - - } // foreach database - - } // foreach dataModel - - - } // main() -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelDataDumpTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelDataDumpTask.php deleted file mode 100644 index 17cf860ba..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelDataDumpTask.php +++ /dev/null @@ -1,354 +0,0 @@ - (Propel) - * @author Fedor Karpelevitch (Torque) - * @author Jason van Zyl (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.task - */ -class PropelDataDumpTask extends AbstractPropelDataModelTask -{ - - /** - * Database name. - * The database name may be optionally specified in the XML if you only want - * to dump the contents of one database. - */ - private $databaseName; - - /** - * Database URL used for Propel connection. - * This is a PEAR-compatible (loosely) DSN URL. - */ - private $databaseUrl; - - /** - * Database driver used for Propel connection. - * This should normally be left blank so that default (Propel built-in) driver for database type is used. - */ - private $databaseDriver; - - /** - * Database user used for Propel connection. - * @deprecated Put username in databaseUrl. - */ - private $databaseUser; - - /** - * Database password used for Propel connection. - * @deprecated Put password in databaseUrl. - */ - private $databasePassword; - - /** - * Properties file that maps a data XML file to a particular database. - * @var PhingFile - */ - private $datadbmap; - - /** - * The database connection used to retrieve the data to dump. - * Needs to be public so that the TableInfo class can access it. - */ - public $conn; - - /** - * The statement used to acquire the data to dump. - */ - private $stmt; - - /** - * Set the file that maps between data XML files and databases. - * - * @param PhingFile $sqldbmap the db map - * @return void - */ - public function setDataDbMap(PhingFile $datadbmap) - { - $this->datadbmap = $datadbmap; - } - - /** - * Get the file that maps between data XML files and databases. - * - * @return PhingFile $datadbmap. - */ - public function getDataDbMap() - { - return $this->datadbmap; - } - - /** - * Get the database name to dump - * - * @return The DatabaseName value - */ - public function getDatabaseName() - { - return $this->databaseName; - } - - /** - * Set the database name - * - * @param v The new DatabaseName value - */ - public function setDatabaseName($v) - { - $this->databaseName = $v; - } - - /** - * Get the database url - * - * @return The DatabaseUrl value - */ - public function getDatabaseUrl() - { - return $this->databaseUrl; - } - - /** - * Set the database url - * - * @param string $v The PEAR-compatible database DSN URL. - */ - public function setDatabaseUrl($v) - { - $this->databaseUrl = $v; - } - - /** - * Get the database user - * - * @return string database user - * @deprecated - */ - public function getDatabaseUser() - { - return $this->databaseUser; - } - - /** - * Set the database user - * - * @param string $v The new DatabaseUser value - * @deprecated Specify user in DSN URL. - */ - public function setDatabaseUser($v) - { - $this->databaseUser = $v; - } - - /** - * Get the database password - * - * @return string database password - */ - public function getDatabasePassword() - { - return $this->databasePassword; - } - - /** - * Set the database password - * - * @param string $v The new DatabasePassword value - * @deprecated Specify database password in DSN URL. - */ - public function setDatabasePassword($v) - { - $this->databasePassword = $v; - } - - /** - * Get the database driver name - * - * @return string database driver name - */ - public function getDatabaseDriver() - { - return $this->databaseDriver; - } - - /** - * Set the database driver name - * - * @param string $v The new DatabaseDriver value - */ - public function setDatabaseDriver($v) - { - $this->databaseDriver = $v; - } - - /** - * Create the data XML -> database map. - * - * This is necessary because there is currently no other method of knowing which - * data XML files correspond to which database. This map allows us to convert multiple - * data XML files into SQL. - * - * @throws IOException - if unable to store properties - */ - private function createDataDbMap() - { - if ($this->getDataDbMap() === null) { - return; - } - - // Produce the sql -> database map - $datadbmap = new Properties(); - - // Check to see if the sqldbmap has already been created. - if ($this->getDataDbMap()->exists()) { - $datadbmap->load($this->getDataDbMap()); - } - - foreach ($this->getDataModels() as $dataModel) { // there is really one 1 db per datamodel - foreach ($dataModel->getDatabases() as $database) { - - // if database name is specified, then we only want to dump that one db. - if (empty($this->databaseName) || ($this->databaseName && $database->getName() == $this->databaseName)) { - $outFile = $this->getMappedFile($dataModel->getName()); - $datadbmap->setProperty($outFile->getName(), $database->getName()); - } - } - } - - try { - $datadbmap->store($this->getDataDbMap(), "Data XML file -> Database map"); - } catch (IOException $e) { - throw new IOException("Unable to store properties: ". $e->getMessage()); - } - } - - /** - * Iterates through each datamodel/database, dumps the contents of all tables and creates a DOM XML doc. - * - * @return void - * @throws BuildException - */ - public function main() - { - $this->validate(); - - $buf = "Database settings:\n" - . " driver: " . ($this->databaseDriver ? $this->databaseDriver : "(default)" ). "\n" - . " URL: " . $this->databaseUrl . "\n" - . ($this->databaseUser ? " user: " . $this->databaseUser . "\n" : "") - . ($this->databasePassword ? " password: " . $this->databasePassword . "\n" : ""); - - $this->log($buf, Project::MSG_VERBOSE); - - // 1) First create the Data XML -> database name map. - $this->createDataDbMap(); - - // 2) Now go create the XML files from teh database(s) - foreach ($this->getDataModels() as $dataModel) { // there is really one 1 db per datamodel - foreach ($dataModel->getDatabases() as $database) { - - // if database name is specified, then we only want to dump that one db. - if (empty($this->databaseName) || ($this->databaseName && $database->getName() == $this->databaseName)) { - - $outFile = $this->getMappedFile($dataModel->getName()); - - $this->log("Dumping data to XML for database: " . $database->getName()); - $this->log("Writing to XML file: " . $outFile->getName()); - - try { - - $url = str_replace("@DB@", $database->getName(), $this->databaseUrl); - - if ($url !== $this->databaseUrl) { - $this->log("New (resolved) URL: " . $url, Project::MSG_VERBOSE); - } - - if (empty($url)) { - throw new BuildException("Unable to connect to database; no PDO connection URL specified.", $this->getLocation()); - } - - $this->conn = new PDO($url, $this->databaseUser, $this->databasePassword); - $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - $doc = $this->createXMLDoc($database); - $doc->save($outFile->getAbsolutePath()); - - } catch (SQLException $se) { - $this->log("SQLException while connecting to DB: ". $se->getMessage(), Project::MSG_ERR); - throw new BuildException($se); - } - } // if databaseName && database->getName == databaseName - } // foreach database - } // foreach datamodel - } - - /** - * Gets PDOStatement of query to fetch all data from a table. - * @param string $tableName - * @param Platform $platform - * @return PDOStatement - */ - private function getTableDataStmt($tableName, Platform $platform) - { - return $this->conn->query("SELECT * FROM " . $platform->quoteIdentifier( $tableName ) ); - } - - /** - * Creates a DOM document containing data for specified database. - * @param Database $database - * @return DOMDocument - */ - private function createXMLDoc(Database $database) - { - $doc = new DOMDocument('1.0', 'utf-8'); - $doc->formatOutput = true; // pretty printing - $doc->appendChild($doc->createComment("Created by data/dump/Control.tpl template.")); - - $dsNode = $doc->createElement("dataset"); - $dsNode->setAttribute("name", "all"); - $doc->appendChild($dsNode); - - $platform = $this->getGeneratorConfig()->getConfiguredPlatform($this->conn); - - $this->log("Building DOM tree containing data from tables:"); - - foreach ($database->getTables() as $tbl) { - $this->log("\t+ " . $tbl->getName()); - $stmt = $this->getTableDataStmt($tbl->getName(), $platform); - while ($row = $stmt->fetch()) { - $rowNode = $doc->createElement($tbl->getPhpName()); - foreach ($tbl->getColumns() as $col) { - $cval = $row[$col->getName()]; - if ($cval !== null) { - $rowNode->setAttribute($col->getPhpName(), iconv($this->dbEncoding, 'utf-8', $cval)); - } - } - $dsNode->appendChild($rowNode); - unset($rowNode); - } - unset($stmt); - } - - return $doc; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelDataModelTemplateTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelDataModelTemplateTask.php deleted file mode 100644 index fd3e7933c..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelDataModelTemplateTask.php +++ /dev/null @@ -1,217 +0,0 @@ - - * @package propel.generator.task - * @version $Revision: 1612 $ - */ -class PropelDataModelTemplateTask extends AbstractPropelDataModelTask -{ - - /** - * This is the file where the generated text - * will be placed. - * @var string - */ - protected $outputFile; - - /** - * Path where Capsule looks for templates. - * @var PhingFile - */ - protected $templatePath; - - /** - * This is the control template that governs the output. - * It may or may not invoke the services of worker - * templates. - * @var string - */ - protected $controlTemplate; - - /** - * [REQUIRED] Set the output file for the - * generation process. - * @param string $outputFile (TODO: change this to File) - * @return void - */ - public function setOutputFile($outputFile) { - $this->outputFile = $outputFile; - } - - /** - * Get the output file for the - * generation process. - * @return string - */ - public function getOutputFile() { - return $this->outputFile; - } - - /** - * [REQUIRED] Set the control template for the - * generating process. - * @param string $controlTemplate - * @return void - */ - public function setControlTemplate ($controlTemplate) { - $this->controlTemplate = $controlTemplate; - } - - /** - * Get the control template for the - * generating process. - * @return string - */ - public function getControlTemplate() { - return $this->controlTemplate; - } - - /** - * [REQUIRED] Set the path where Capsule will look - * for templates using the file template - * loader. - * @return void - * @throws Exception - */ - public function setTemplatePath($templatePath) { - $resolvedPath = ""; - $tok = strtok($templatePath, ","); - while ( $tok ) { - // resolve relative path from basedir and leave - // absolute path untouched. - $fullPath = $this->project->resolveFile($tok); - $cpath = $fullPath->getCanonicalPath(); - if ($cpath === false) { - $this->log("Template directory does not exist: " . $fullPath->getAbsolutePath()); - } else { - $resolvedPath .= $cpath; - } - $tok = strtok(","); - if ( $tok ) { - $resolvedPath .= ","; - } - } - $this->templatePath = $resolvedPath; - } - - /** - * Get the path where Velocity will look - * for templates using the file template - * loader. - * @return string - */ - public function getTemplatePath() { - return $this->templatePath; - } - - /** - * Creates a new Capsule context with some basic properties set. - * (Capsule is a simple PHP encapsulation system -- aka a php "template" class.) - * @return Capsule - */ - protected function createContext() { - - $context = new Capsule(); - - // Make sure the output directory exists, if it doesn't - // then create it. - $outputDir = new PhingFile($this->outputDirectory); - if (!$outputDir->exists()) { - $this->log("Output directory does not exist, creating: " . $outputDir->getAbsolutePath()); - $outputDir->mkdirs(); - } - - // Place our set of data models into the context along - // with the names of the databases as a convenience for now. - $context->put("targetDatabase", $this->getTargetDatabase()); - $context->put("targetPackage", $this->getTargetPackage()); - $context->put("now", strftime("%c")); - - $this->log("Target database type: " . $this->getTargetDatabase()); - $this->log("Target package: " . $this->getTargetPackage()); - $this->log("Using template path: " . $this->templatePath); - $this->log("Output directory: " . $this->getOutputDirectory()); - - $context->setTemplatePath($this->templatePath); - $context->setOutputDirectory($this->outputDirectory); - - $this->populateContextProperties($context); - - return $context; - } - - /** - * Adds the propel build properties to the passed Capsule context. - * - * @param Capsule $context - * @see GeneratorConfig::getBuildProperties() - */ - public function populateContextProperties(Capsule $context) - { - foreach ($this->getGeneratorConfig()->getBuildProperties() as $key => $propValue) { - $this->log('Adding property ${' . $key . '} to context', Project::MSG_DEBUG); - $context->put($key, $propValue); - } - } - - /** - * Performs validation for single-file mode. - * @throws BuildException - if there are any validation errors - */ - protected function singleFileValidate() - { - parent::validate(); - - // Make sure the control template is set. - if ($this->controlTemplate === null) { - throw new BuildException("The control template needs to be defined!"); - } - // Make sure there is an output file. - if ($this->outputFile === null) { - throw new BuildException("The output file needs to be defined!"); - } - - } - - /** - * Creates Capsule context and parses control template. - * @return void - */ - public function main() - { - $this->singleFileValidate(); - $context = $this->createContext(); - - $context->put("dataModels", $this->getDataModels()); - - $path = $this->outputDirectory . DIRECTORY_SEPARATOR . $this->outputFile; - $this->log("Generating to file " . $path); - - try { - $this->log("Parsing control template: " . $this->controlTemplate); - $context->parse($this->controlTemplate, $path); - } catch (Exception $ioe) { - throw new BuildException("Cannot write parsed template: ". $ioe->getMessage()); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelDataSQLTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelDataSQLTask.php deleted file mode 100644 index f651d07e3..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelDataSQLTask.php +++ /dev/null @@ -1,193 +0,0 @@ - (Propel) - * @author Jason van Zyl (Torque) - * @author John McNally (Torque) - * @author Fedor Karpelevitch (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.task - */ -class PropelDataSQLTask extends AbstractPropelDataModelTask -{ - - /** - * Properties file that maps an SQL file to a particular database. - * @var PhingFile - */ - private $sqldbmap; - - /** - * Properties file that maps a data XML file to a particular database. - * @var PhingFile - */ - private $datadbmap; - - /** - * The base directory in which to find data XML files. - * @var PhingFile - */ - private $srcDir; - - /** - * Set the file that maps between SQL files and databases. - * - * @param PhingFile $sqldbmap the sql -> db map. - * @return void - */ - public function setSqlDbMap(PhingFile $sqldbmap) - { - $this->sqldbmap = $sqldbmap; - } - - /** - * Get the file that maps between SQL files and databases. - * - * @return PhingFile sqldbmap. - */ - public function getSqlDbMap() - { - return $this->sqldbmap; - } - - /** - * Set the file that maps between data XML files and databases. - * - * @param PhingFile $sqldbmap the db map - * @return void - */ - public function setDataDbMap(PhingFile $datadbmap) - { - $this->datadbmap = $datadbmap; - } - - /** - * Get the file that maps between data XML files and databases. - * - * @return PhingFile $datadbmap. - */ - public function getDataDbMap() - { - return $this->datadbmap; - } - - /** - * Set the src directory for the data xml files listed in the datadbmap file. - * @param PhingFile $srcDir data xml source directory - */ - public function setSrcDir(PhingFile $srcDir) - { - $this->srcDir = $srcDir; - } - - /** - * Get the src directory for the data xml files listed in the datadbmap file. - * - * @return PhingFile data xml source directory - */ - public function getSrcDir() - { - return $this->srcDir; - } - - /** - * Search through all data models looking for matching database. - * @return Database or NULL if none found. - */ - private function getDatabase($name) - { - foreach ($this->getDataModels() as $dm) { - foreach ($dm->getDatabases() as $db) { - if ($db->getName() == $name) { - return $db; - } - } - } - } - - /** - * Main method parses the XML files and creates SQL files. - * - * @return void - * @throws Exception If there is an error parsing the data xml. - */ - public function main() - { - $this->validate(); - - $targetDatabase = $this->getTargetDatabase(); - - $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); - - // Load the Data XML -> DB Name properties - $map = new Properties(); - try { - $map->load($this->getDataDbMap()); - } catch (IOException $ioe) { - throw new BuildException("Cannot open and process the datadbmap!", $ioe); - } - - // Parse each file in the data -> db map - foreach ($map->keys() as $dataXMLFilename) { - - $dataXMLFile = new PhingFile($this->srcDir, $dataXMLFilename); - - // if file exists then proceed - if ($dataXMLFile->exists()) { - - $dbname = $map->get($dataXMLFilename); - - $db = $this->getDatabase($dbname); - - if (!$db) { - throw new BuildException("Cannot find instantiated Database for name '$dbname' from datadbmap file."); - } - - $db->setPlatform($platform); - - $outFile = $this->getMappedFile($dataXMLFilename); - $sqlWriter = new FileWriter($outFile); - - $this->log("Creating SQL from XML data dump file: " . $dataXMLFile->getAbsolutePath()); - - try { - $dataXmlParser = new XmlToDataSQL($db, $this->getGeneratorConfig(), $this->dbEncoding); - $dataXmlParser->transform($dataXMLFile, $sqlWriter); - } catch (Exception $e) { - throw new BuildException("Exception parsing data XML: " . $e->getMessage(), $x); - } - - // Place the generated SQL file(s) - $p = new Properties(); - if ($this->getSqlDbMap()->exists()) { - $p->load($this->getSqlDbMap()); - } - - $p->setProperty($outFile->getName(), $db->getName()); - $p->store($this->getSqlDbMap(), "Sqlfile -> Database map"); - - } else { - $this->log("File '" . $dataXMLFile->getAbsolutePath() - . "' in datadbmap does not exist, so skipping it.", Project::MSG_WARN); - } - - } // foreach data xml file - - } // main() - -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelGraphvizTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelGraphvizTask.php deleted file mode 100644 index e778d6e8c..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelGraphvizTask.php +++ /dev/null @@ -1,170 +0,0 @@ -exists()) { - $out->mkdirs(); - } - $this->outDir = $out; - } - - - /** - * Set the sqldbmap. - * @param PhingFile $sqldbmap The db map. - */ - public function setSqlDbMap(PhingFile $sqldbmap) - { - $this->sqldbmap = $sqldbmap; - } - - /** - * Get the sqldbmap. - * @return PhingFile $sqldbmap. - */ - public function getSqlDbMap() - { - return $this->sqldbmap; - } - - /** - * Set the database name. - * @param string $database - */ - public function setDatabase($database) - { - $this->database = $database; - } - - /** - * Get the database name. - * @return string - */ - public function getDatabase() - { - return $this->database; - } - - - public function main() - { - - $count = 0; - - $dotSyntax = ''; - - // file we are going to create - - $dbMaps = $this->getDataModelDbMap(); - - foreach ($this->getDataModels() as $dataModel) { - - $dotSyntax .= "digraph G {\n"; - foreach ($dataModel->getDatabases() as $database) { - - $this->log("db: " . $database->getName()); - - //print the tables - foreach ($database->getTables() as $tbl) { - - $this->log("\t+ " . $tbl->getName()); - - ++$count; - $dotSyntax .= 'node'.$tbl->getName().' [label="{
'.$tbl->getName().'|'; - - foreach ($tbl->getColumns() as $col) { - $dotSyntax .= $col->getName() . ' (' . $col->getType() . ')'; - if (count($col->getForeignKeys()) > 0) { - $dotSyntax .= ' [FK]'; - } elseif ($col->isPrimaryKey()) { - $dotSyntax .= ' [PK]'; - } - $dotSyntax .= '\l'; - } - $dotSyntax .= '}", shape=record];'; - $dotSyntax .= "\n"; - } - - //print the relations - - $count = 0; - $dotSyntax .= "\n"; - foreach ($database->getTables() as $tbl) { - ++$count; - - foreach ($tbl->getColumns() as $col) { - $fk = $col->getForeignKeys(); - if ( count($fk) == 0 or $fk === null ) continue; - if ( count($fk) > 1 ) throw( new Exception("not sure what to do here...") ); - $fk = $fk[0]; // try first one - $dotSyntax .= 'node'.$tbl->getName() .':cols -> node'.$fk->getForeignTableName() . ':table [label="' . $col->getName() . '=' . implode(',', $fk->getForeignColumns()) . ' "];'; - $dotSyntax .= "\n"; - } - } - - - - } // foreach database - $dotSyntax .= "}\n"; - - $this->writeDot($dotSyntax,$this->outDir,$database->getName()); - - $dotSyntax = ''; - - } //foreach datamodels - - } // main() - - - /** - * probably insecure - */ - function writeDot($dotSyntax, PhingFile $outputDir, $baseFilename) { - $file = new PhingFile($outputDir, $baseFilename . '.schema.dot'); - $this->log("Writing dot file to " . $file->getAbsolutePath()); - file_put_contents($file->getAbsolutePath(), $dotSyntax); - } - -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelOMTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelOMTask.php deleted file mode 100644 index 9dc9c7834..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelOMTask.php +++ /dev/null @@ -1,231 +0,0 @@ - - * @package propel.generator.task - */ -class PropelOMTask extends AbstractPropelDataModelTask -{ - - /** - * The platform (php4, php5, etc.) for which the om is being built. - * @var string - */ - private $targetPlatform; - - /** - * Sets the platform (php4, php5, etc.) for which the om is being built. - * @param string $v - */ - public function setTargetPlatform($v) { - $this->targetPlatform = $v; - } - - /** - * Gets the platform (php4, php5, etc.) for which the om is being built. - * @return string - */ - public function getTargetPlatform() { - return $this->targetPlatform; - } - - /** - * Utility method to create directory for package if it doesn't already exist. - * @param string $path The [relative] package path. - * @throws BuildException - if there is an error creating directories - */ - protected function ensureDirExists($path) - { - $f = new PhingFile($this->getOutputDirectory(), $path); - if (!$f->exists()) { - if (!$f->mkdirs()) { - throw new BuildException("Error creating directories: ". $f->getPath()); - } - } - } - - /** - * Uses a builder class to create the output class. - * This method assumes that the DataModelBuilder class has been initialized with the build properties. - * @param OMBuilder $builder - * @param boolean $overwrite Whether to overwrite existing files with te new ones (default is YES). - * @todo -cPropelOMTask Consider refactoring build() method into AbstractPropelDataModelTask (would need to be more generic). - */ - protected function build(OMBuilder $builder, $overwrite = true) - { - $path = $builder->getClassFilePath(); - $this->ensureDirExists(dirname($path)); - - $_f = new PhingFile($this->getOutputDirectory(), $path); - - // skip files already created once - if ($_f->exists() && !$overwrite) { - $this->log("\t\t-> (exists) " . $builder->getClassname(), Project::MSG_VERBOSE); - return 0; - } - - $script = $builder->build(); - foreach ($builder->getWarnings() as $warning) { - $this->log($warning, Project::MSG_WARN); - } - - // skip unchanged files - if ($_f->exists() && $script == $_f->contents()) { - $this->log("\t\t-> (unchanged) " . $builder->getClassname(), Project::MSG_VERBOSE); - return 0; - } - - // write / overwrite new / changed files - $this->log("\t\t-> " . $builder->getClassname() . " [builder: " . get_class($builder) . "]"); - file_put_contents($_f->getAbsolutePath(), $script); - return 1; - } - - /** - * Main method builds all the targets for a typical propel project. - */ - public function main() - { - // check to make sure task received all correct params - $this->validate(); - - $generatorConfig = $this->getGeneratorConfig(); - $totalNbFiles = 0; - - foreach ($this->getDataModels() as $dataModel) { - $this->log("Processing Datamodel : " . $dataModel->getName()); - - foreach ($dataModel->getDatabases() as $database) { - - $this->log(" - processing database : " . $database->getName()); - - foreach ($database->getTables() as $table) { - - if (!$table->isForReferenceOnly()) { - - $nbWrittenFiles = 0; - - $this->log("\t+ " . $table->getName()); - - // ----------------------------------------------------------------------------------------- - // Create Peer, Object, and TableMap classes - // ----------------------------------------------------------------------------------------- - - // these files are always created / overwrite any existing files - foreach (array('peer', 'object', 'tablemap', 'query') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $nbWrittenFiles += $this->build($builder); - } - - // ----------------------------------------------------------------------------------------- - // Create [empty] stub Peer and Object classes if they don't exist - // ----------------------------------------------------------------------------------------- - - // these classes are only generated if they don't already exist - foreach (array('peerstub', 'objectstub', 'querystub') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $nbWrittenFiles += $this->build($builder, $overwrite=false); - } - - // ----------------------------------------------------------------------------------------- - // Create [empty] stub child Object classes if they don't exist - // ----------------------------------------------------------------------------------------- - - // If table has enumerated children (uses inheritance) then create the empty child stub classes if they don't already exist. - if ($table->getChildrenColumn()) { - $col = $table->getChildrenColumn(); - if ($col->isEnumeratedClasses()) { - foreach ($col->getChildren() as $child) { - foreach (array('queryinheritance') as $target) { - if (!$child->getAncestor()) { - continue; - } - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $builder->setChild($child); - $nbWrittenFiles += $this->build($builder, $overwrite=true); - } - foreach (array('objectmultiextend', 'queryinheritancestub') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $builder->setChild($child); - $nbWrittenFiles += $this->build($builder, $overwrite=false); - } - } // foreach - } // if col->is enumerated - } // if tbl->getChildrenCol - - - // ----------------------------------------------------------------------------------------- - // Create [empty] Interface if it doesn't exist - // ----------------------------------------------------------------------------------------- - - // Create [empty] interface if it does not already exist - if ($table->getInterface()) { - $builder = $generatorConfig->getConfiguredBuilder($table, 'interface'); - $nbWrittenFiles += $this->build($builder, $overwrite=false); - } - - // ----------------------------------------------------------------------------------------- - // Create tree Node classes - // ----------------------------------------------------------------------------------------- - - if ($table->treeMode()) { - switch($table->treeMode()) { - case 'NestedSet': - foreach (array('nestedsetpeer', 'nestedset') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $nbWrittenFiles += $this->build($builder); - } - break; - - case 'MaterializedPath': - foreach (array('nodepeer', 'node') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $nbWrittenFiles += $this->build($builder); - } - - foreach (array('nodepeerstub', 'nodestub') as $target) { - $builder = $generatorConfig->getConfiguredBuilder($table, $target); - $nbWrittenFiles += $this->build($builder, $overwrite=false); - } - break; - - case 'AdjacencyList': - // No implementation for this yet. - default: - break; - } - - } // if Table->treeMode() - - $totalNbFiles += $nbWrittenFiles; - if ($nbWrittenFiles == 0) { - $this->log("\t\t(no change)"); - } - } // if !$table->isForReferenceOnly() - - } // foreach table - - } // foreach database - - } // foreach dataModel - if ($totalNbFiles) { - $this->log(sprintf("Object model generation complete - %d files written", $totalNbFiles)); - } else { - $this->log("Object model generation complete - All files already up to date"); - } - } // main() -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelSQLExec.php b/airtime_mvc/library/propel/generator/lib/task/PropelSQLExec.php deleted file mode 100644 index 4b9ff138e..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelSQLExec.php +++ /dev/null @@ -1,701 +0,0 @@ - Database map in the form of a properties - * file to insert each SQL file listed into its designated database. - * - * @author Hans Lellelid - * @author Dominik del Bondio - * @author Jeff Martin (Torque) - * @author Michael McCallum (Torque) - * @author Tim Stephenson (Torque) - * @author Jason van Zyl (Torque) - * @author Martin Poeschl (Torque) - * @version $Revision: 1612 $ - * @package propel.generator.task - */ -class PropelSQLExec extends Task -{ - - private $goodSql = 0; - private $totalSql = 0; - - const DELIM_ROW = "row"; - const DELIM_NORMAL = "normal"; - - /** - * The delimiter type indicating whether the delimiter will - * only be recognized on a line by itself - */ - private $delimiterType = "normal"; // can't use constant just defined - - //private static $delimiterTypes = array(DELIM_NORMAL, DELIM_ROW); - //private static $errorActions = array("continue", "stop", "abort"); - - /** PDO Database connection */ - private $conn = null; - - /** Autocommit flag. Default value is false */ - private $autocommit = false; - - /** DB url. */ - private $url = null; - - /** User name. */ - private $userId = null; - - /** Password */ - private $password = null; - - /** SQL input command */ - private $sqlCommand = ""; - - /** SQL transactions to perform */ - private $transactions = array(); - - /** SQL Statement delimiter */ - private $delimiter = ";"; - - /** Print SQL results. */ - private $print = false; - - /** Print header columns. */ - private $showheaders = true; - - /** Results Output file. */ - private $output = null; - - /** RDBMS Product needed for this SQL. */ - private $rdbms = null; - - /** RDBMS Version needed for this SQL. */ - private $version = null; - - /** Action to perform if an error is found */ - private $onError = "abort"; - - /** Encoding to use when reading SQL statements from a file */ - private $encoding = null; - - /** Src directory for the files listed in the sqldbmap. */ - private $srcDir; - - /** Properties file that maps an individual SQL file to a database. */ - private $sqldbmap; - - /** - * Set the sqldbmap properties file. - * - * @param sqldbmap filename for the sqldbmap - */ - public function setSqlDbMap($sqldbmap) - { - $this->sqldbmap = $this->project->resolveFile($sqldbmap); - } - - /** - * Get the sqldbmap properties file. - * - * @return filename for the sqldbmap - */ - public function getSqlDbMap() - { - return $this->sqldbmap; - } - - /** - * Set the src directory for the sql files listed in the sqldbmap file. - * - * @param PhingFile $srcDir sql source directory - */ - public function setSrcDir(PhingFile $srcDir) - { - $this->srcDir = $srcDir; - } - - /** - * Get the src directory for the sql files listed in the sqldbmap file. - * - * @return PhingFile SQL Source directory - */ - public function getSrcDir() - { - return $this->srcDir; - } - - /** - * Set the sql command to execute - * - * @param sql sql command to execute - */ - public function addText($sql) - { - $this->sqlCommand .= $sql; - } - - /** - * Set the DB connection url. - * - * @param string $url connection url - */ - public function setUrl($url) - { - $this->url = $url; - } - - /** - * Set the user name for the DB connection. - * - * @param string $userId database user - * @deprecated Specify userid in the DSN URL. - */ - public function setUserid($userId) - { - $this->userId = $userId; - } - - /** - * Set the password for the DB connection. - * - * @param string $password database password - * @deprecated Specify password in the DSN URL. - */ - public function setPassword($password) - { - $this->password = $password; - } - - /** - * Set the autocommit flag for the DB connection. - * - * @param boolean $autocommit the autocommit flag - */ - public function setAutoCommit($autocommit) - { - $this->autocommit = (boolean) $autocommit; - } - - /** - * Set the statement delimiter. - * - *

For example, set this to "go" and delimitertype to "ROW" for - * Sybase ASE or MS SQL Server.

- * - * @param string $delimiter - */ - public function setDelimiter($delimiter) - { - $this->delimiter = $delimiter; - } - - /** - * Set the Delimiter type for this sql task. The delimiter type takes two - * values - normal and row. Normal means that any occurence of the delimiter - * terminate the SQL command whereas with row, only a line containing just - * the delimiter is recognized as the end of the command. - * - * @param string $delimiterType - */ - public function setDelimiterType($delimiterType) - { - $this->delimiterType = $delimiterType; - } - - /** - * Set the print flag. - * - * @param boolean $print - */ - public function setPrint($print) - { - $this->print = (boolean) $print; - } - - /** - * Set the showheaders flag. - * - * @param boolean $showheaders - */ - public function setShowheaders($showheaders) - { - $this->showheaders = (boolean) $showheaders; - } - - /** - * Set the output file. - * - * @param PhingFile $output - */ - public function setOutput(PhingFile $output) - { - $this->output = $output; - } - - /** - * Set the action to perform onerror - * - * @param string $action - */ - public function setOnerror($action) - { - $this->onError = $action; - } - - /** - * Load the sql file and then execute it - * - * @throws BuildException - */ - public function main() - { - $this->sqlCommand = trim($this->sqlCommand); - - if ($this->sqldbmap === null || $this->getSqlDbMap()->exists() === false) { - throw new BuildException("You haven't provided an sqldbmap, or " - . "the one you specified doesn't exist: " . $this->sqldbmap->getPath()); - } - - if ($this->url === null) { - throw new BuildException("DSN url attribute must be set!"); - } - - $map = new Properties(); - - try { - $map->load($this->getSqlDbMap()); - } catch (IOException $ioe) { - throw new BuildException("Cannot open and process the sqldbmap!"); - } - - $databases = array(); - - foreach ($map->keys() as $sqlfile) { - - $database = $map->getProperty($sqlfile); - - // Q: already there? - if (!isset($databases[$database])) { - // A: No. - $databases[$database] = array(); - } - - // We want to make sure that the base schemas - // are inserted first. - if (strpos($sqlfile, "schema.sql") !== false) { - // add to the beginning of the array - array_unshift($databases[$database], $sqlfile); - } else { - array_push($databases[$database], $sqlfile); - } - } - - foreach ($databases as $db => $files) { - $transactions = array(); - - foreach ($files as $fileName) { - - $file = new PhingFile($this->srcDir, $fileName); - - if ($file->exists()) { - $this->log("Executing statements in file: " . $file->__toString()); - $transaction = new PropelSQLExecTransaction($this); - $transaction->setSrc($file); - $transactions[] = $transaction; - } else { - $this->log("File '" . $file->__toString() - . "' in sqldbmap does not exist, so skipping it."); - } - } - $this->insertDatabaseSqlFiles($this->url, $db, $transactions); - } - } - - /** - * Take the base url, the target database and insert a set of SQL - * files into the target database. - * - * @param string $url - * @param string $database - * @param array $transactions - */ - private function insertDatabaseSqlFiles($url, $database, $transactions) - { - $url = str_replace("@DB@", $database, $url); - $this->log("Our new url -> " . $url); - - try { - - $buf = "Database settings:" . PHP_EOL - . " URL: " . $url . PHP_EOL - . ($this->userId ? " user: " . $this->userId . PHP_EOL : "") - . ($this->password ? " password: " . $this->password . PHP_EOL : ""); - - $this->log($buf, Project::MSG_VERBOSE); - - // Set user + password to null if they are empty strings - if (!$this->userId) { $this->userId = null; } - - if (!$this->password) { $this->password = null; } - - $this->conn = new PDO($url, $this->userId, $this->password); - $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - // $this->conn->setAutoCommit($this->autocommit); - // $this->statement = $this->conn->createStatement(); - - $out = null; - - try { - if ($this->output !== null) { - $this->log("Opening PrintStream to output file " . $this->output->__toString(), Project::MSG_VERBOSE); - $out = new FileWriter($this->output); - } - - // Process all transactions - for ($i=0,$size=count($transactions); $i < $size; $i++) { - $transactions[$i]->runTransaction($out); - if (!$this->autocommit) { - $this->log("Commiting transaction", Project::MSG_VERBOSE); - $this->conn->commit(); - } - } - } catch (Exception $e) { - if ($out) $out->close(); - } - - } catch (IOException $e) { - - if (!$this->autocommit && $this->conn !== null && $this->onError == "abort") { - try { - $this->conn->rollBack(); - } catch (PDOException $ex) { - // do nothing. - System::println("Rollback failed."); - } - } - if ($this->statement) $this->statement = null; // close - throw new BuildException($e); - } catch (PDOException $e) { - if (!$this->autocommit && $this->conn !== null && $this->onError == "abort") { - try { - $this->conn->rollBack(); - } catch (PDOException $ex) { - // do nothing. - System::println("Rollback failed"); - } - } - if ($this->statement) $this->statement = null; // close - throw new BuildException($e); - } - - $this->statement = null; // close - - $this->log($this->goodSql . " of " . $this->totalSql - . " SQL statements executed successfully"); - } - - /** - * Read the statements from the .sql file and execute them. - * Lines starting with '//', '--' or 'REM ' are ignored. - * - * Developer note: must be public in order to be called from - * sudo-"inner" class PropelSQLExecTransaction. - * - * @param Reader $reader - * @param $out Optional output stream. - * @throws PDOException - * @throws IOException - */ - public function runStatements(Reader $reader, $out = null) - { - $sql = ""; - $line = ""; - $sqlBacklog = ""; - $hasQuery = false; - - $in = new BufferedReader($reader); - - $parser['pointer'] = 0; - $parser['isInString'] = false; - $parser['stringQuotes'] = ""; - $parser['backslashCount'] = 0; - $parser['parsedString'] = ""; - - $sqlParts = array(); - - while (($line = $in->readLine()) !== null) { - - $line = trim($line); - $line = ProjectConfigurator::replaceProperties($this->project, $line, - $this->project->getProperties()); - - if (StringHelper::startsWith("//", $line) - || StringHelper::startsWith("--", $line) - || StringHelper::startsWith("#", $line)) { - continue; - } - - if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") { - continue; - } - - if ($sqlBacklog !== "") { - $sql = $sqlBacklog; - $sqlBacklog = ""; - } - - $sql .= " " . $line . PHP_EOL; - - // SQL defines "--" as a comment to EOL - // and in Oracle it may contain a hint - // so we cannot just remove it, instead we must end it - if (strpos($line, "--") !== false) { - $sql .= PHP_EOL; - } - - // DELIM_ROW doesn't need this (as far as i can tell) - if ($this->delimiterType == self::DELIM_NORMAL) { - - // old regex, being replaced due to segfaults: - // See: http://propel.phpdb.org/trac/ticket/294 - //$reg = "#((?:\"(?:\\\\.|[^\"])*\"?)+|'(?:\\\\.|[^'])*'?|" . preg_quote($this->delimiter) . ")#"; - //$sqlParts = preg_split($reg, $sql, 0, PREG_SPLIT_DELIM_CAPTURE); - - $i = $parser['pointer']; - $c = strlen($sql); - while ($i < $c) { - - $char = $sql[$i]; - - switch($char) { - case "\\": - $parser['backslashCount']++; - $this->log("c$i: found ".$parser['backslashCount']." backslash(es)", Project::MSG_VERBOSE); - break; - case "'": - case "\"": - if ($parser['isInString'] && $parser['stringQuotes'] == $char) { - if (($parser['backslashCount'] & 1) == 0) { - #$this->log("$i: out of string", Project::MSG_VERBOSE); - $parser['isInString'] = false; - } else { - $this->log("c$i: rejected quoted delimiter", Project::MSG_VERBOSE); - } - - } elseif (!$parser['isInString']) { - $parser['stringQuotes'] = $char; - $parser['isInString'] = true; - #$this->log("$i: into string with $parser['stringQuotes']", Project::MSG_VERBOSE); - } - break; - } - - if ($char == $this->delimiter && !$parser['isInString']) { - $this->log("c$i: valid end of command found!", Project::MSG_VERBOSE); - $sqlParts[] = $parser['parsedString']; - $sqlParts[] = $this->delimiter; - break; - } - $parser['parsedString'] .= $char; - if ($char !== "\\") { - if ($parser['backslashCount']) $this->log("$i: backslash reset", Project::MSG_VERBOSE); - $parser['backslashCount'] = 0; - } - $i++; - $parser['pointer']++; - } - - $sqlBacklog = ""; - foreach ($sqlParts as $sqlPart) { - // we always want to append, even if it's a delim (which will be stripped off later) - $sqlBacklog .= $sqlPart; - - // we found a single (not enclosed by ' or ") delimiter, so we can use all stuff before the delim as the actual query - if ($sqlPart === $this->delimiter) { - $sql = $sqlBacklog; - $sqlBacklog = ""; - $hasQuery = true; - } - } - } - - if ($hasQuery || ($this->delimiterType == self::DELIM_ROW && $line == $this->delimiter)) { - // this assumes there is always a delimter on the end of the SQL statement. - $sql = StringHelper::substring($sql, 0, strlen($sql) - 1 - strlen($this->delimiter)); - $this->log("SQL: " . $sql, Project::MSG_VERBOSE); - $this->execSQL($sql, $out); - $sql = ""; - $hasQuery = false; - - $parser['pointer'] = 0; - $parser['isInString'] = false; - $parser['stringQuotes'] = ""; - $parser['backslashCount'] = 0; - $parser['parsedString'] = ""; - $sqlParts = array(); - } - } - - // Catch any statements not followed by ; - if ($sql !== "") { - $this->execSQL($sql, $out); - } - } - - /** - * Exec the sql statement. - * - * @param sql - * @param out - * @throws PDOException - */ - protected function execSQL($sql, $out = null) - { - // Check and ignore empty statements - if (trim($sql) == "") { - return; - } - - try { - $this->totalSql++; - - if (!$this->autocommit) $this->conn->beginTransaction(); - - $stmt = $this->conn->prepare($sql); - $stmt->execute(); - $this->log($stmt->rowCount() . " rows affected", Project::MSG_VERBOSE); - - if (!$this->autocommit) $this->conn->commit(); - - $this->goodSql++; - } catch (PDOException $e) { - $this->log("Failed to execute: " . $sql, Project::MSG_ERR); - if ($this->onError != "continue") { - throw $e; - } - $this->log($e->getMessage(), Project::MSG_ERR); - } - } - - /** - * print any results in the statement. - * - * @param out - * @throws PDOException - */ - protected function printResults($out = null) - { - $rs = null; - - do { - $rs = $this->statement->getResultSet(); - - if ($rs !== null) { - - $this->log("Processing new result set.", Project::MSG_VERBOSE); - - $line = ""; - - $colsprinted = false; - - while ($rs->next()) { - - if (!$colsprinted && $this->showheaders) { - $first = true; - foreach ($this->fields as $fieldName => $ignore) { - if ($first) $first = false; else $line .= ","; - $line .= $fieldName; - } - } // if show headers - - $first = true; - foreach ($rs->fields as $columnValue) { - - if ($columnValue != null) { - $columnValue = trim($columnValue); - } - - if ($first) { - $first = false; - } else { - $line .= ","; - } - $line .= $columnValue; - } - - if ($out !== null) { - $out->write($line); - $out->newLine(); - } - - System::println($line); - $line = ""; - } // while rs->next() - } - } while ($this->statement->getMoreResults()); - System::println(); - if ($out !== null) $out->newLine(); - } - -} - -/** - * "Inner" class that contains the definition of a new transaction element. - * Transactions allow several files or blocks of statements - * to be executed using the same Propel connection and commit - * operation in between. - * @package propel.generator.task - */ -class PropelSQLExecTransaction -{ - - private $tSrcFile = null; - private $tSqlCommand = ""; - private $parent; - - function __construct($parent) - { - // Parent is required so that we can log things ... - $this->parent = $parent; - } - - public function setSrc(PhingFile $src) - { - $this->tSrcFile = $src; - } - - public function addText($sql) - { - $this->tSqlCommand .= $sql; - } - - /** - * @throws IOException, PDOException - */ - public function runTransaction($out = null) - { - if (!empty($this->tSqlCommand)) { - $this->parent->log("Executing commands", Project::MSG_INFO); - $this->parent->runStatements($this->tSqlCommand, $out); - } - - if ($this->tSrcFile !== null) { - $this->parent->log("Executing file: " . $this->tSrcFile->getAbsolutePath(), Project::MSG_INFO); - $reader = new FileReader($this->tSrcFile); - $this->parent->runStatements($reader, $out); - $reader->close(); - } - } -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelSQLTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelSQLTask.php deleted file mode 100644 index 5c7304d2d..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelSQLTask.php +++ /dev/null @@ -1,250 +0,0 @@ - - * @package propel.generator.task - */ -class PropelSQLTask extends AbstractPropelDataModelTask -{ - - /** - * The properties file that maps an SQL file to a particular database. - * @var PhingFile - */ - private $sqldbmap; - - /** - * Name of the database. - */ - private $database; - - /** - * Set the sqldbmap. - * @param PhingFile $sqldbmap The db map. - */ - public function setSqlDbMap(PhingFile $sqldbmap) - { - $this->sqldbmap = $sqldbmap; - } - - /** - * Get the sqldbmap. - * @return PhingFile $sqldbmap. - */ - public function getSqlDbMap() - { - return $this->sqldbmap; - } - - /** - * Set the database name. - * @param string $database - */ - public function setDatabase($database) - { - $this->database = $database; - } - - /** - * Get the database name. - * @return string - */ - public function getDatabase() - { - return $this->database; - } - - /** - * Create the sql -> database map. - * - * @throws IOException - if unable to store properties - */ - protected function createSqlDbMap() - { - if ($this->getSqlDbMap() === null) { - return; - } - - // Produce the sql -> database map - $sqldbmap = new Properties(); - - // Check to see if the sqldbmap has already been created. - if ($this->getSqlDbMap()->exists()) { - $sqldbmap->load($this->getSqlDbMap()); - } - - if ($this->packageObjectModel) { - // in this case we'll get the sql file name from the package attribute - $dataModels = $this->packageDataModels(); - foreach ($dataModels as $package => $dataModel) { - foreach ($dataModel->getDatabases() as $database) { - $name = ($package ? $package . '.' : '') . 'schema.xml'; - $sqlFile = $this->getMappedFile($name); - $sqldbmap->setProperty($sqlFile->getName(), $database->getName()); - } - } - } else { - // the traditional way is to map the schema.xml filenames - $dmMap = $this->getDataModelDbMap(); - foreach (array_keys($dmMap) as $dataModelName) { - $sqlFile = $this->getMappedFile($dataModelName); - if ($this->getDatabase() === null) { - $databaseName = $dmMap[$dataModelName]; - } else { - $databaseName = $this->getDatabase(); - } - $sqldbmap->setProperty($sqlFile->getName(), $databaseName); - } - } - - try { - $sqldbmap->store($this->getSqlDbMap(), "Sqlfile -> Database map"); - } catch (IOException $e) { - throw new IOException("Unable to store properties: ". $e->getMessage()); - } - } - - public function main() { - - $this->validate(); - - if (!$this->mapperElement) { - throw new BuildException("You must use a element to describe how names should be transformed."); - } - - if ($this->packageObjectModel) { - $dataModels = $this->packageDataModels(); - } else { - $dataModels = $this->getDataModels(); - } - - // 1) first create a map of filenames to databases; this is used by other tasks like - // the SQLExec task. - $this->createSqlDbMap(); - - // 2) Now actually create the DDL based on the datamodel(s) from XML schema file. - $targetDatabase = $this->getTargetDatabase(); - - $generatorConfig = $this->getGeneratorConfig(); - - $builderClazz = $generatorConfig->getBuilderClassname('ddl'); - - foreach ($dataModels as $package => $dataModel) { - - foreach ($dataModel->getDatabases() as $database) { - - // Clear any start/end DLL - call_user_func(array($builderClazz, 'reset')); - - // file we are going to create - if (!$this->packageObjectModel) { - $name = $dataModel->getName(); - } else { - $name = ($package ? $package . '.' : '') . 'schema.xml'; - } - - $outFile = $this->getMappedFile($name); - - $this->log("Writing to SQL file: " . $outFile->getPath()); - - // First add any "header" SQL - $ddl = call_user_func(array($builderClazz, 'getDatabaseStartDDL')); - - foreach ($database->getTables() as $table) { - - if (!$table->isSkipSql()) { - $builder = $generatorConfig->getConfiguredBuilder($table, 'ddl'); - $this->log("\t+ " . $table->getName() . " [builder: " . get_class($builder) . "]"); - $ddl .= $builder->build(); - foreach ($builder->getWarnings() as $warning) { - $this->log($warning, Project::MSG_WARN); - } - } else { - $this->log("\t + (skipping) " . $table->getName()); - } - - } // foreach database->getTables() - - // Finally check to see if there is any "footer" SQL - $ddl .= call_user_func(array($builderClazz, 'getDatabaseEndDDL')); - - #var_dump($outFile->getAbsolutePath()); - // Now we're done. Write the file! - file_put_contents($outFile->getAbsolutePath(), $ddl); - - } // foreach database - } //foreach datamodels - - } // main() - - /** - * Packages the datamodels to one datamodel per package - * - * This applies only when the the packageObjectModel option is set. We need to - * re-package the datamodels to allow the database package attribute to control - * which tables go into which SQL file. - * - * @return array The packaged datamodels - */ - protected function packageDataModels() { - - static $packagedDataModels; - - if (is_null($packagedDataModels)) { - - $dataModels = $this->getDataModels(); - $dataModel = array_shift($dataModels); - $packagedDataModels = array(); - - $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); - - foreach ($dataModel->getDatabases() as $db) { - foreach ($db->getTables() as $table) { - $package = $table->getPackage(); - if (!isset($packagedDataModels[$package])) { - $dbClone = $this->cloneDatabase($db); - $dbClone->setPackage($package); - $ad = new AppData($platform); - $ad->setName($dataModel->getName()); - $ad->addDatabase($dbClone); - $packagedDataModels[$package] = $ad; - } - $packagedDataModels[$package]->getDatabase($db->getName())->addTable($table); - } - } - } - - return $packagedDataModels; - } - - protected function cloneDatabase($db) { - - $attributes = array ( - 'name' => $db->getName(), - 'baseClass' => $db->getBaseClass(), - 'basePeer' => $db->getBasePeer(), - 'defaultIdMethod' => $db->getDefaultIdMethod(), - 'defaultPhpNamingMethod' => $db->getDefaultPhpNamingMethod(), - 'defaultTranslateMethod' => $db->getDefaultTranslateMethod(), - 'heavyIndexing' => $db->getHeavyIndexing(), - ); - - $clone = new Database(); - $clone->loadFromXML($attributes); - return $clone; - } -} diff --git a/airtime_mvc/library/propel/generator/lib/task/PropelSchemaReverseTask.php b/airtime_mvc/library/propel/generator/lib/task/PropelSchemaReverseTask.php deleted file mode 100644 index e3bc270bf..000000000 --- a/airtime_mvc/library/propel/generator/lib/task/PropelSchemaReverseTask.php +++ /dev/null @@ -1,548 +0,0 @@ - - * @version $Revision: 1716 $ - * @package propel.generator.task - */ -class PropelSchemaReverseTask extends PDOTask -{ - - /** - * Zero bit for no validators - */ - const VALIDATORS_NONE = 0; - - /** - * Bit for maxLength validator - */ - const VALIDATORS_MAXLENGTH = 1; - - /** - * Bit for maxValue validator - */ - const VALIDATORS_MAXVALUE = 2; - - /** - * Bit for type validator - */ - const VALIDATORS_TYPE = 4; - - /** - * Bit for required validator - */ - const VALIDATORS_REQUIRED = 8; - - /** - * Bit for unique validator - */ - const VALIDATORS_UNIQUE = 16; - - /** - * Bit for all validators - */ - const VALIDATORS_ALL = 255; - - /** - * File to contain XML database schema. - * @var PhingFIle - */ - protected $xmlSchema; - - /** - * DB encoding to use - * @var string - */ - protected $dbEncoding = 'iso-8859-1'; - - /** - * DB schema to use. - * @var string - */ - protected $dbSchema; - - /** - * The datasource name (used for in schema.xml) - * - * @var string - */ - protected $databaseName; - - /** - * DOM document produced. - * @var DOMDocument - */ - protected $doc; - - /** - * The document root element. - * @var DOMElement - */ - protected $databaseNode; - - /** - * Hashtable of columns that have primary keys. - * @var array - */ - protected $primaryKeys; - - /** - * Whether to use same name for phpName or not. - * @var boolean - */ - protected $samePhpName; - - /** - * whether to add vendor info or not - * @var boolean - */ - protected $addVendorInfo; - - /** - * Bitfield to switch on/off which validators will be created. - * - * @var int - */ - protected $validatorBits = PropelSchemaReverseTask::VALIDATORS_NONE; - - /** - * Collect validatorInfos to create validators. - * - * @var int - */ - protected $validatorInfos; - - /** - * An initialized GeneratorConfig object containing the converted Phing props. - * - * @var GeneratorConfig - */ - private $generatorConfig; - - /** - * Maps validator type tokens to bits - * - * The tokens are used in the propel.addValidators property to define - * which validators are to be added - * - * @var array - */ - static protected $validatorBitMap = array ( - 'none' => PropelSchemaReverseTask::VALIDATORS_NONE, - 'maxlength' => PropelSchemaReverseTask::VALIDATORS_MAXLENGTH, - 'maxvalue' => PropelSchemaReverseTask::VALIDATORS_MAXVALUE, - 'type' => PropelSchemaReverseTask::VALIDATORS_TYPE, - 'required' => PropelSchemaReverseTask::VALIDATORS_REQUIRED, - 'unique' => PropelSchemaReverseTask::VALIDATORS_UNIQUE, - 'all' => PropelSchemaReverseTask::VALIDATORS_ALL, - ); - - /** - * Defines messages that are added to validators - * - * @var array - */ - static protected $validatorMessages = array ( - 'maxlength' => array ( - 'msg' => 'The field %s must be not longer than %s characters.', - 'var' => array('colName', 'value') - ), - 'maxvalue' => array ( - 'msg' => 'The field %s must be not greater than %s.', - 'var' => array('colName', 'value') - ), - 'type' => array ( - 'msg' => 'The column %s must be an %s value.', - 'var' => array('colName', 'value') - ), - 'required' => array ( - 'msg' => 'The field %s is required.', - 'var' => array('colName') - ), - 'unique' => array ( - 'msg' => 'This %s already exists in table %s.', - 'var' => array('colName', 'tableName') - ), - ); - - /** - * Gets the (optional) schema name to use. - * - * @return string - */ - public function getDbSchema() - { - return $this->dbSchema; - } - - /** - * Sets the name of a database schema to use (optional). - * - * @param string $dbSchema - */ - public function setDbSchema($dbSchema) - { - $this->dbSchema = $dbSchema; - } - - /** - * Gets the database encoding. - * - * @return string - */ - public function getDbEncoding($v) - { - return $this->dbEncoding; - } - - /** - * Sets the database encoding. - * - * @param string $v - */ - public function setDbEncoding($v) - { - $this->dbEncoding = $v; - } - - /** - * Gets the datasource name. - * - * @return string - */ - public function getDatabaseName() - { - return $this->databaseName; - } - - /** - * Sets the datasource name. - * - * This will be used as the value in the generated schema.xml - * - * @param string $v - */ - public function setDatabaseName($v) - { - $this->databaseName = $v; - } - - /** - * Sets the output name for the XML file. - * - * @param PhingFile $v - */ - public function setOutputFile(PhingFile $v) - { - $this->xmlSchema = $v; - } - - /** - * Set whether to use the column name as phpName without any translation. - * - * @param boolean $v - */ - public function setSamePhpName($v) - { - $this->samePhpName = $v; - } - - /** - * Set whether to add vendor info to the schema. - * - * @param boolean $v - */ - public function setAddVendorInfo($v) - { - $this->addVendorInfo = (boolean) $v; - } - - /** - * Sets set validator bitfield from a comma-separated list of "validator bit" names. - * - * @param string $v The comma-separated list of which validators to add. - * @return void - */ - public function setAddValidators($v) - { - $validKeys = array_keys(self::$validatorBitMap); - - // lowercase input - $v = strtolower($v); - - $bits = self::VALIDATORS_NONE; - - $exprs = explode(',', $v); - foreach ($exprs as $expr) { - $expr = trim($expr); - if(!empty($expr)) { - if (!isset(self::$validatorBitMap[$expr])) { - throw new BuildException("Unable to interpret validator in expression ('$v'): " . $expr); - } - $bits |= self::$validatorBitMap[$expr]; - } - } - - $this->validatorBits = $bits; - } - - /** - * Checks whether to add validators of specified type or not - * - * @param int $type The validator type constant. - * @return boolean - */ - protected function isValidatorRequired($type) - { - return (($this->validatorBits & $type) === $type); - } - - /** - * Whether to use the column name as phpName without any translation. - * - * @return boolean - */ - public function isSamePhpName() - { - return $this->samePhpName; - } - - /** - * @throws BuildException - */ - public function main() - { - if (!$this->getDatabaseName()) { - throw new BuildException("databaseName attribute is required for schema reverse engineering", $this->getLocation()); - } - - //(not yet supported) $this->log("schema : " . $this->dbSchema); - //DocumentTypeImpl docType = new DocumentTypeImpl(null, "database", null, - // "http://jakarta.apache.org/turbine/dtd/database.dtd"); - - $this->doc = new DOMDocument('1.0', 'utf-8'); - $this->doc->formatOutput = true; // pretty printing - - $this->doc->appendChild($this->doc->createComment("Autogenerated by ".get_class($this)." class.")); - - try { - - $database = $this->buildModel(); - - if ($this->validatorBits !== self::VALIDATORS_NONE) { - $this->addValidators($database); - } - - $database->appendXml($this->doc); - - $this->log("Writing XML to file: " . $this->xmlSchema->getPath()); - $out = new FileWriter($this->xmlSchema); - $xmlstr = $this->doc->saveXML(); - $out->write($xmlstr); - $out->close(); - - } catch (Exception $e) { - $this->log("There was an error building XML from metadata: " . $e->getMessage(), Project::MSG_ERR); - } - - $this->log("Schema reverse engineering finished"); - } - - /** - * Gets the GeneratorConfig object for this task or creates it on-demand. - * @return GeneratorConfig - */ - protected function getGeneratorConfig() - { - if ($this->generatorConfig === null) { - $this->generatorConfig = new GeneratorConfig(); - $this->generatorConfig->setBuildProperties($this->getProject()->getProperties()); - } - return $this->generatorConfig; - } - - /** - * Builds the model classes from the database schema. - * @return Database The built-out Database (with all tables, etc.) - */ - protected function buildModel() - { - $config = $this->getGeneratorConfig(); - $con = $this->getConnection(); - - $database = new Database($this->getDatabaseName()); - $database->setPlatform($config->getConfiguredPlatform($con)); - - // Some defaults ... - $database->setDefaultIdMethod(IDMethod::NATIVE); - - $parser = $config->getConfiguredSchemaParser($con); - - $nbTables = $parser->parse($database, $this); - - $this->log("Successfully Reverse Engineered " . $nbTables . " tables"); - - return $database; - } - - /** - * Adds any requested validators to the data model. - * - * We will add the following type specific validators: - * - * for notNull columns: required validator - * for unique indexes: unique validator - * for varchar types: maxLength validators (CHAR, VARCHAR, LONGVARCHAR) - * for numeric types: maxValue validators (BIGINT, SMALLINT, TINYINT, INTEGER, FLOAT, DOUBLE, NUMERIC, DECIMAL, REAL) - * for integer and timestamp types: notMatch validator with [^\d]+ (BIGINT, SMALLINT, TINYINT, INTEGER, TIMESTAMP) - * for float types: notMatch validator with [^\d\.]+ (FLOAT, DOUBLE, NUMERIC, DECIMAL, REAL) - * - * @param Database $database The Database model. - * @return void - * @todo find out how to evaluate the appropriate size and adjust maxValue rule values appropriate - * @todo find out if float type column values must always notMatch('[^\d\.]+'), i.e. digits and point for any db vendor, language etc. - */ - protected function addValidators(Database $database) - { - - $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); - - foreach ($database->getTables() as $table) { - - $set = new PropelSchemaReverse_ValidatorSet(); - - foreach ($table->getColumns() as $col) { - - if ($col->isNotNull() && $this->isValidatorRequired(self::VALIDATORS_REQUIRED)) { - $validator = $set->getValidator($col); - $validator->addRule($this->getValidatorRule($col, 'required')); - } - - if (in_array($col->getType(), array(PropelTypes::CHAR, PropelTypes::VARCHAR, PropelTypes::LONGVARCHAR)) - && $col->getSize() && $this->isValidatorRequired(self::VALIDATORS_MAXLENGTH)) { - $validator = $set->getValidator($col); - $validator->addRule($this->getValidatorRule($col, 'maxLength', $col->getSize())); - } - - if ($col->isNumericType() && $this->isValidatorRequired(self::VALIDATORS_MAXVALUE)) { - $this->log("WARNING: maxValue validator added for column ".$col->getName().". You will have to adjust the size value manually.", Project::MSG_WARN); - $validator = $set->getValidator($col); - $validator->addRule($this->getValidatorRule($col, 'maxValue', 'REPLACEME')); - } - - if ($col->isPhpPrimitiveType() && $this->isValidatorRequired(self::VALIDATORS_TYPE)) { - $validator = $set->getValidator($col); - $validator->addRule($this->getValidatorRule($col, 'type', $col->getPhpType())); - } - - } - - foreach ($table->getUnices() as $unique) { - $colnames = $unique->getColumns(); - if (count($colnames) == 1) { // currently 'unique' validator only works w/ single columns. - $col = $table->getColumn($colnames[0]); - $validator = $set->getValidator($col); - $validator->addRule($this->getValidatorRule($col, 'unique')); - } - } - - foreach ($set->getValidators() as $validator) { - $table->addValidator($validator); - } - - } // foreach table - - } - - /** - * Gets validator rule for specified type (string). - * - * @param Column $column The column that is being validated. - * @param string $type The type (string) for validator (e.g. 'required'). - * @param mixed $value The value for the validator (if applicable) - */ - protected function getValidatorRule(Column $column, $type, $value = null) - { - $rule = new Rule(); - $rule->setName($type); - if ($value !== null) { - $rule->setValue($value); - } - $rule->setMessage($this->getRuleMessage($column, $type, $value)); - return $rule; - } - - /** - * Gets the message for a specified rule. - * - * @param Column $column - * @param string $type - * @param mixed $value - */ - protected function getRuleMessage(Column $column, $type, $value) - { - // create message - $colName = $column->getName(); - $tableName = $column->getTable()->getName(); - $msg = self::$validatorMessages[strtolower($type)]; - $tmp = compact($msg['var']); - array_unshift($tmp, $msg['msg']); - $msg = call_user_func_array('sprintf', $tmp); - return $msg; - } - -} - -/** - * A helper class to store validator sets indexed by column. - * @package propel.generator.task - */ -class PropelSchemaReverse_ValidatorSet -{ - - /** - * Map of column names to validators. - * - * @var array Validator[] - */ - private $validators = array(); - - /** - * Gets a single validator for specified column name. - * @param Column $column - * @return Validator - */ - public function getValidator(Column $column) - { - $key = $column->getName(); - if (!isset($this->validators[$key])) { - $this->validators[$key] = new Validator(); - $this->validators[$key]->setColumn($column); - } - return $this->validators[$key]; - } - - /** - * Gets all validators. - * @return array Validator[] - */ - public function getValidators() - { - return $this->validators; - } -} diff --git a/airtime_mvc/library/propel/generator/pear/BuildPropelGenPEARPackageTask.php b/airtime_mvc/library/propel/generator/pear/BuildPropelGenPEARPackageTask.php deleted file mode 100644 index 87d21602c..000000000 --- a/airtime_mvc/library/propel/generator/pear/BuildPropelGenPEARPackageTask.php +++ /dev/null @@ -1,258 +0,0 @@ -. - */ - -require_once 'phing/tasks/system/MatchingTask.php'; -include_once 'phing/types/FileSet.php'; -include_once 'phing/tasks/ext/pearpackage/Fileset.php'; - -/** - * - * @author Hans Lellelid - * @package phing.tasks.ext - * @version $Revision: 1681 $ - */ -class BuildPropelGenPEARPackageTask extends MatchingTask -{ - - /** Base directory for reading files. */ - private $dir; - - private $version; - private $state = 'stable'; - private $notes; - - private $filesets = array(); - - /** Package file */ - private $packageFile; - - public function init() - { - include_once 'PEAR/PackageFileManager2.php'; - if (!class_exists('PEAR_PackageFileManager2')) { - throw new BuildException("You must have installed PEAR_PackageFileManager2 (PEAR_PackageFileManager >= 1.6.0) in order to create a PEAR package.xml file."); - } - } - - private function setOptions($pkg) - { - $options['baseinstalldir'] = 'propel'; - $options['packagedirectory'] = $this->dir->getAbsolutePath(); - - if (empty($this->filesets)) { - throw new BuildException("You must use a tag to specify the files to include in the package.xml"); - } - - $options['filelistgenerator'] = 'Fileset'; - - // Some PHING-specific options needed by our Fileset reader - $options['phing_project'] = $this->getProject(); - $options['phing_filesets'] = $this->filesets; - - if ($this->packageFile !== null) { - // create one w/ full path - $f = new PhingFile($this->packageFile->getAbsolutePath()); - $options['packagefile'] = $f->getName(); - // must end in trailing slash - $options['outputdirectory'] = $f->getParent() . DIRECTORY_SEPARATOR; - $this->log("Creating package file: " . $f->getPath(), Project::MSG_INFO); - } else { - $this->log("Creating [default] package.xml file in base directory.", Project::MSG_INFO); - } - - // add baseinstalldir exceptions - $options['installexceptions'] = array( - 'pear-propel-gen' => '/', - 'pear-propel-gen.bat' => '/', - ); - - $options['dir_roles'] = array( - 'lib' => 'data', - 'resources' => 'data' - ); - - $options['exceptions'] = array( - 'pear-propel-gen.bat' => 'script', - 'pear-propel-gen' => 'script', - ); - - $pkg->setOptions($options); - - } - - /** - * Main entry point. - * @return void - */ - public function main() - { - if ($this->dir === null) { - throw new BuildException("You must specify the \"dir\" attribute for PEAR package task."); - } - - if ($this->version === null) { - throw new BuildException("You must specify the \"version\" attribute for PEAR package task."); - } - - $package = new PEAR_PackageFileManager2(); - - $this->setOptions($package); - - // the hard-coded stuff - $package->setPackage('propel_generator'); - $package->setSummary('Generator component of the Propel PHP object persistence layer'); - $package->setDescription('Propel is an object persistence layer for PHP5 based on Apache Torque. This package provides the generator engine that builds PHP classes and SQL DDL based on an XML representation of your data model.'); - $package->setChannel('pear.propelorm.org'); - $package->setPackageType('php'); - - $package->setReleaseVersion($this->version); - $package->setAPIVersion($this->version); - - $package->setReleaseStability($this->state); - $package->setAPIStability($this->state); - - $package->setNotes($this->notes); - - $package->setLicense('MIT', 'http://www.opensource.org/licenses/mit-license.php'); - - // Add package maintainers - $package->addMaintainer('lead', 'hans', 'Hans Lellelid', 'hans@xmpl.org'); - $package->addMaintainer('lead', 'david', 'David Zuelke', 'dz@bitxtender.com'); - $package->addMaintainer('lead', 'francois', 'Francois Zaninotto', 'fzaninotto@[gmail].com'); - - // creating a sub-section for 'windows' - $package->addRelease(); - $package->setOSInstallCondition('windows'); - $package->addInstallAs('pear-propel-gen.bat', 'propel-gen.bat'); - $package->addIgnoreToRelease('pear-propel-gen'); - - // creating a sub-section for non-windows - $package->addRelease(); - $package->addInstallAs('pear-propel-gen', 'propel-gen'); - $package->addIgnoreToRelease('pear-propel-gen.bat'); - - // "core" dependencies - $package->setPhpDep('5.2.4'); - $package->setPearinstallerDep('1.4.0'); - - // "package" dependencies - $package->addPackageDepWithChannel('required', 'phing', 'pear.phing.info', '2.3.0'); - - $package->addExtensionDep('required', 'pdo'); - $package->addExtensionDep('required', 'xml'); - $package->addExtensionDep('required', 'xsl'); - - // now add the replacements .... - $package->addReplacement('pear-propel-gen.bat', 'pear-config', '@DATA-DIR@', 'data_dir'); - $package->addReplacement('pear-propel-gen', 'pear-config', '@DATA-DIR@', 'data_dir'); - - // now we run this weird generateContents() method that apparently - // is necessary before we can add replacements ... ? - $package->generateContents(); - - $e = $package->writePackageFile(); - - if (PEAR::isError($e)) { - throw new BuildException("Unable to write package file.", new Exception($e->getMessage())); - } - - } - - /** - * Used by the PEAR_PackageFileManager_PhingFileSet lister. - * @return array FileSet[] - */ - public function getFileSets() - { - return $this->filesets; - } - - // ------------------------------- - // Set properties from XML - // ------------------------------- - - /** - * Nested creator, creates a FileSet for this task - * - * @return FileSet The created fileset object - */ - function createFileSet() - { - $num = array_push($this->filesets, new FileSet()); - return $this->filesets[$num-1]; - } - - /** - * Set the version we are building. - * @param string $v - * @return void - */ - public function setVersion($v) - { - $this->version = $v; - } - - /** - * Set the state we are building. - * @param string $v - * @return void - */ - public function setState($v) - { - $this->state = $v; - } - - /** - * Sets release notes field. - * @param string $v - * @return void - */ - public function setNotes($v) - { - $this->notes = $v; - } - /** - * Sets "dir" property from XML. - * @param PhingFile $f - * @return void - */ - public function setDir(PhingFile $f) - { - $this->dir = $f; - } - - /** - * Sets the file to use for generated package.xml - */ - public function setDestFile(PhingFile $f) - { - $this->packageFile = $f; - } - -} diff --git a/airtime_mvc/library/propel/generator/pear/build-pear-package.xml b/airtime_mvc/library/propel/generator/pear/build-pear-package.xml deleted file mode 100644 index 62ce2103a..000000000 --- a/airtime_mvc/library/propel/generator/pear/build-pear-package.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Propel version for package - - - - - - - - - ----------------------------- - | Creating directory layout | - ----------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ----------------------------- - | Creating PEAR package.xml | - ----------------------------- - - - - - - - - - - - - - - - ----------------------------- - | Creating tar.gz package | - ----------------------------- - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/pear/build.properties b/airtime_mvc/library/propel/generator/pear/build.properties deleted file mode 100644 index 0f6c76b90..000000000 --- a/airtime_mvc/library/propel/generator/pear/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -# In this file you can define any properties taht you want to affect -# all projects built using the propel-gen script on this system -# -# See http://www.propelorm.org/wiki/Documentation/1.5/BuildConfiguration -# for a list of available properties. diff --git a/airtime_mvc/library/propel/generator/pear/pear-build.xml b/airtime_mvc/library/propel/generator/pear/pear-build.xml deleted file mode 100644 index dbc84eebd..000000000 --- a/airtime_mvc/library/propel/generator/pear/pear-build.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Processing additional properties file: ${additional.properties} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/pear/pear-propel-gen b/airtime_mvc/library/propel/generator/pear/pear-propel-gen deleted file mode 100755 index 253ef2920..000000000 --- a/airtime_mvc/library/propel/generator/pear/pear-propel-gen +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh - -# ------------------------------------------------------------------------ -# The phing build script for Unix based systems -# $Id: pear-propel-gen,v 1.2 2004/10/17 13:24:09 hlellelid Exp $ -# ------------------------------------------------------------------------ - -# ------------------------------------------------------------------------- -# Do not change anything below this line unless you know what you're doing. -# ------------------------------------------------------------------------- - -# (currently this is not reached) -if (test -z "$PHING_COMMAND") ; then - export PHING_COMMAND="phing" -fi - -if [ $# = 1 ] ; then - saveddir=`pwd` - $PHING_COMMAND -f @DATA-DIR@/propel_generator/pear-build.xml -Dproject.dir=$saveddir $* -else - $PHING_COMMAND -f @DATA-DIR@/propel_generator/pear-build.xml -Dproject.dir=$* -fi - - diff --git a/airtime_mvc/library/propel/generator/pear/pear-propel-gen.bat b/airtime_mvc/library/propel/generator/pear/pear-propel-gen.bat deleted file mode 100644 index 754ea5911..000000000 --- a/airtime_mvc/library/propel/generator/pear/pear-propel-gen.bat +++ /dev/null @@ -1,30 +0,0 @@ -@ECHO OFF - -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: The propel-gen build script for Windows based systems -:: $Id: pear-propel-gen.bat,v 1.2 2004/10/17 13:24:09 hlellelid Exp $ -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -::---------------------------------------------------------------------------------- -:: Please set following to the "phing" script. By default this is expected to be -:: on your path. (You don't need to modify this file if that is the case.) - -SET phingScript=phing - -::--------------------------------------------------------------------------------- -::--------------------------------------------------------------------------------- -:: Do not modify below this line!! (Unless you know what your doing :) -::--------------------------------------------------------------------------------- -::--------------------------------------------------------------------------------- - -set nbArgs=0 -for %%x in (%*) do Set /A nbArgs+=1 -if %nbArgs% leq 1 ( - "%phingScript%" -f "@DATA-DIR@\propel_generator\pear-build.xml" -Dproject.dir="%CD%" %* -) else ( - "%phingScript%" -f "@DATA-DIR@\propel_generator\pear-build.xml" -Dproject.dir=%* -) -GOTO :EOF - -:PAUSE_END -PAUSE \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/resources/dtd/database.dtd b/airtime_mvc/library/propel/generator/resources/dtd/database.dtd deleted file mode 100644 index 1de399e8b..000000000 --- a/airtime_mvc/library/propel/generator/resources/dtd/database.dtd +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/generator/resources/xsd/custom_datatypes.xsd b/airtime_mvc/library/propel/generator/resources/xsd/custom_datatypes.xsd deleted file mode 100644 index 12e8327cb..000000000 --- a/airtime_mvc/library/propel/generator/resources/xsd/custom_datatypes.xsd +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/generator/resources/xsd/database.xsd b/airtime_mvc/library/propel/generator/resources/xsd/database.xsd deleted file mode 100644 index a54046efa..000000000 --- a/airtime_mvc/library/propel/generator/resources/xsd/database.xsd +++ /dev/null @@ -1,862 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - The name of the column as it appears in the database. - - - - - - - Name used in PHP code to reference this column (in getters, setters, etc.). Defaults to the name transformed by the phpNamingMethod, which defaults to a CamelCase converter. So by default, a column named 'author_id' receives 'AuthorId' as phpName. - - - - - - - Name used for the class constant corresponding to this column in PHP code. Defaults to the uppercase name, so a column named 'author_id' receives 'AUTHOR_ID' as peerName. - - - - - - - - Visibility for the column accessor method. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Visibility for the column mutator method. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Set to true to add a primary key on this column. - - - - - - - Set to true to forbid NULL values. - - - - - - - Any of the Propel supported data types. These types are database-agnostic, and converted to the native database type according to the connection. - - - - - - - Native database column type. - - - - - - - PHP type for te column in PHP code. This column's setter uses type casting with the set php_type; besides, generated phpDoc in the model classes use this attribute for code completion. - - - - - - - Numeric length of the column. - - - - - - - Digits after decimal place - - - - - - - Synonym for defaultValue - - - - - - - The default value that the object will have for this column in the PHP instance after creating a "new Object". This value is always interpreted as a string. See defaultExpr for setting an SQL function as a default value. - - - - - - - The default value for this column as expressed in SQL. This value is used solely for the "sql" target which builds your database from the schema.xml file. The defaultExpr is the SQL expression used as the "default" for the column. - - - - - - - - - - Name of the method used to transform the column name into a phpName. Defaults to 'clean', which Removes any character that is not a letter or a number and capitilizes the first letter of the name, the first letter of each alphanumeric block, and converts the rest of the letters to lowercase. Possible values: any of the PhpNameGenerator CONV_METHOD_XXX constants (clean, underscore, phpName, nochange). - - - - - - - A text description of the column. It gets added to the SQL CREATE table as a comment, and appears in the phpDoc bloc of the related getter and setter methods in the ActiveRecord class. - - - - - - - Set to true to skip this column by default during hydration. That means that this column will be hydrated on demand, using a supplementary query. Mostly useful for LOB columns. - - - - - - - (DEPRECATED) For use with treeMode table attribute. - - - - - - - (DEPRECATED) For use with treeMode table attribute. - - - - - - - (DEPRECATED) For use with treeMode table attribute. - - - - - - - (DEPRECATED) For use with treeMode table attribute. - - - - - - - (DEPRECATED) For use with treeMode table attribute. - - - - - - - A column defined as primary string serves as default value for a `__toString()` method in the generated Propel object. - - - - - - - - - - - A reference between a local and a foreign column. Composite foreign keys can have several references. - - - - - - - - - The other table name - - - - - - - Name for this foreign key - - - - - - - Name for the foreign object in methods generated in this class. - - - - - - - Name for this object in methods generated in the foreign class - - - - - - - This affects the default join type used in the generated `joinXXX()` methods in the model query class. Propel uses an INNER JOIN for foreign keys attached to a required column, and a LEFT JOIN for foreign keys attached to a non-required column, but you can override this in the foreign key element. - - - - - - - - - - - - The (absolute or relative to this schema dir name) path to the external schema file. - - - - - - - - - - - - - A column of the table - - - - - - - - A foreign key on one or several columns in this table, referencing a foreign table - - - - - - - - An index on one or several columns of the current table - - - - - - - - A unique index on one or several columns of the current table - - - - - - - - If you are using a database that uses sequences for auto-increment columns (e.g. PostgreSQL or Oracle), you can customize the name of the sequence using this tag - - - - - - - - A validator to be executed on a given column at runtime - - - - - - - - A behavior to be added to the current table. Can modify the table structure, as well as modify the runtime code of the generated Model objects linked to this table. Bundled behaviors include alternative_coding_standards, auto_add_pk, timestampable, sluggable, soft_delete, sortable, nested_set, query_cache, and concrete_inheritance. - - - - - - - - table attributes specific to a database vendor. Only supports MySQL specific table attributes for now (Charset, Collate, Checksum, Pack_keys, Delay_key_write). - - - - - - - - - The name of the table as it appears in the database. - - - - - - - The name of the ActiveRecord class generated for this table. Defaults to the name transformed by the phpNamingMethod, which defaults to a CamelCase converter. So by default, a table named 'foo_author' receives 'FooAuthor' as phpName. - - - - - - - The PHP 5.3 namespace to use for the generated model classes. - - - - - - - - Default visibility for column accessor methods. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Default visibility for column mutator methods. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Id method to use for auto-increment columns. - - - - - - - Can be used if you want to define the primary key of a new object being inserted. By default if idMethod is "native", Propel would throw an exception. However, in some cases this feature is useful, for example if you do some replication of data in an master-master environment. - - - - - - - Instructs Propel not to generate DDL SQL for the specified table. This can be used together with readOnly for supperting VIEWS in Propel - - - - - - - Suppresses the mutator/setter methods, save() and delete() methods. - - - - - - - Whether the generated stub class will be abstract (e.g. if you're using inheritance) - - - - - - - Allows you to specify a class that the generated Propel objects should extend (in place of propel.om.BaseObject) - - - - - - - Instructs Propel to use a different SQL-generating BasePeer class (or sub-class of BasePeer). - - - - - - - - Specifies the "package" for the generated classes. Classes are created in subdirectories according to the package attribute value. - - - - - - - - Name of the method used to transform the table name into a phpName. Defaults to 'clean', which Removes any character that is not a letter or a number and capitilizes the first letter of the name, the first letter of each alphanumeric block, and converts the rest of the letters to lowercase. Possible values: any of the PhpNameGenerator CONV_METHOD_XXX constants (clean, underscore, phpName, nochange). - - - - - - - Adds indexes for each component of the primary key (when using composite primary keys) - - - - - - - A text description of the table. It gets added to the SQL CREATE table as a comment, and appears in the phpDoc bloc of the related ActiveRecord class. - - - - - - - Used to indicate that this table is part of a node tree. Currently the only supported values are "NestedSet" and "MaterializedPath" (DEPRECATED: use nested_set behavior instead). - - - - - - - Indicate that the object should be reloaded from the database when an INSERT is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on INSERT. - - - - - - - Indicate that the object should be reloaded from the database when an UPDATE is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on UPDATE. - - - - - - - Set to true if the current table is a cross-reference table in a many-to-many relationship to allow generation of getter and setter in each of the tables of the relationship. - - - - - - - - - - - Embed an external schema file into the current schema. Accepts absolute and relative schema file paths. - - - - - - - A table using the database connection. - - - - - - - Behavior to be applied to all the database tables - - - - - - - - The name of the table in the database. Propel advocates the use of singular table names. - - - - - - - Default id method to use for auto-increment columns - - - - - - - - Default visibility for column accessor methods. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Default visibility for column mutator methods. 'public' by default, also accepts 'protected' and 'private'. - - - - - - - Specifies the "package" for the generated classes. Classes are created in subdirectories according to the package attribute value. - - - - - - - The PHP 5.3 namespace to use for the generated model classes of the database. Can be overridden on a per-table basis. - - - - - - - Allows to specify a default base class that all generated Propel objects should extend (in place of propel.om.BaseObject) - - - - - - - Instructs Propel to use a different SQL-generating BasePeer class (or sub-class of BasePeer) for all generated objects - - - - - - - The default naming method to use in this database. - - - - - - - Adds indexes for each component of the primary key (when using composite primary keys) - - - - - - - Adds a prefix to all the SQL table names - - - - - diff --git a/airtime_mvc/library/propel/generator/resources/xsl/database.xsl b/airtime_mvc/library/propel/generator/resources/xsl/database.xsl deleted file mode 100644 index 81d8217ad..000000000 --- a/airtime_mvc/library/propel/generator/resources/xsl/database.xsl +++ /dev/null @@ -1,292 +0,0 @@ - - -]> - - - - - - - - - - - - native - - - underscore - - - false - - - - - - - - - - - - - - - - - - none - - - - - - - - - - - - - - - - - none - - - - - - - - - - - - - - - - - - - - - - - - -
- - false - - - false - - - - - - - - - - -
- - - - - - - none - - - none - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - default - - - - - - - - - - - - - - - - - - class - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - false - - - VARCHAR - - - false - - - false - - - 255 - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/runtime/lib/Propel.php b/airtime_mvc/library/propel/runtime/lib/Propel.php deleted file mode 100644 index 6171408e1..000000000 --- a/airtime_mvc/library/propel/runtime/lib/Propel.php +++ /dev/null @@ -1,916 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @author Magnús Þór Torfason (Torque) - * @author Jason van Zyl (Torque) - * @author Rafal Krzewski (Torque) - * @author Martin Poeschl (Torque) - * @author Henning P. Schmiedehausen (Torque) - * @author Kurt Schrader (Torque) - * @version $Revision: 1811 $ - * @package propel.runtime - */ -class Propel -{ - /** - * The Propel version. - */ - const VERSION = '1.5.2'; - - /** - * A constant for default. - */ - const DEFAULT_NAME = "default"; - - /** - * A constant defining 'System is unusuable' logging level - */ - const LOG_EMERG = 0; - - /** - * A constant defining 'Immediate action required' logging level - */ - const LOG_ALERT = 1; - - /** - * A constant defining 'Critical conditions' logging level - */ - const LOG_CRIT = 2; - - /** - * A constant defining 'Error conditions' logging level - */ - const LOG_ERR = 3; - - /** - * A constant defining 'Warning conditions' logging level - */ - const LOG_WARNING = 4; - - /** - * A constant defining 'Normal but significant' logging level - */ - const LOG_NOTICE = 5; - - /** - * A constant defining 'Informational' logging level - */ - const LOG_INFO = 6; - - /** - * A constant defining 'Debug-level messages' logging level - */ - const LOG_DEBUG = 7; - - /** - * The class name for a PDO object. - */ - const CLASS_PDO = 'PDO'; - - /** - * The class name for a PropelPDO object. - */ - const CLASS_PROPEL_PDO = 'PropelPDO'; - - /** - * The class name for a DebugPDO object. - */ - const CLASS_DEBUG_PDO = 'DebugPDO'; - - /** - * Constant used to request a READ connection (applies to replication). - */ - const CONNECTION_READ = 'read'; - - /** - * Constant used to request a WRITE connection (applies to replication). - */ - const CONNECTION_WRITE = 'write'; - - /** - * @var string The db name that is specified as the default in the property file - */ - private static $defaultDBName; - - /** - * @var array The global cache of database maps - */ - private static $dbMaps = array(); - - /** - * @var array The cache of DB adapter keys - */ - private static $adapterMap = array(); - - /** - * @var array Cache of established connections (to eliminate overhead). - */ - private static $connectionMap = array(); - - /** - * @var PropelConfiguration Propel-specific configuration. - */ - private static $configuration; - - /** - * @var bool flag to set to true once this class has been initialized - */ - private static $isInit = false; - - /** - * @var Log optional logger - */ - private static $logger = null; - - /** - * @var string The name of the database mapper class - */ - private static $databaseMapClass = 'DatabaseMap'; - - /** - * @var bool Whether the object instance pooling is enabled - */ - private static $instancePoolingEnabled = true; - - /** - * @var bool For replication, whether to force the use of master connection. - */ - private static $forceMasterConnection = false; - - /** - * @var string Base directory to use for autoloading. Initialized in self::initBaseDir() - */ - protected static $baseDir; - - /** - * @var array A map of class names and their file paths for autoloading - */ - protected static $autoloadMap = array( - - 'DBAdapter' => 'adapter/DBAdapter.php', - 'DBMSSQL' => 'adapter/DBMSSQL.php', - 'MssqlPropelPDO' => 'adapter/MSSQL/MssqlPropelPDO.php', - 'MssqlDebugPDO' => 'adapter/MSSQL/MssqlDebugPDO.php', - 'MssqlDateTime' => 'adapter/MSSQL/MssqlDateTime.class.php', - 'DBMySQL' => 'adapter/DBMySQL.php', - 'DBMySQLi' => 'adapter/DBMySQLi.php', - 'DBNone' => 'adapter/DBNone.php', - 'DBOracle' => 'adapter/DBOracle.php', - 'DBPostgres' => 'adapter/DBPostgres.php', - 'DBSQLite' => 'adapter/DBSQLite.php', - 'DBSybase' => 'adapter/DBSybase.php', - - 'PropelArrayCollection' => 'collection/PropelArrayCollection.php', - 'PropelCollection' => 'collection/PropelCollection.php', - 'PropelObjectCollection' => 'collection/PropelObjectCollection.php', - 'PropelOnDemandCollection' => 'collection/PropelOnDemandCollection.php', - 'PropelOnDemandIterator' => 'collection/PropelOnDemandIterator.php', - - 'PropelConfiguration' => 'config/PropelConfiguration.php', - 'PropelConfigurationIterator' => 'config/PropelConfigurationIterator.php', - - 'PropelPDO' => 'connection/PropelPDO.php', - 'DebugPDO' => 'connection/DebugPDO.php', - 'DebugPDOStatement' => 'connection/DebugPDOStatement.php', - - 'PropelException' => 'exception/PropelException.php', - - 'ModelWith' => 'formatter/ModelWith.php', - 'PropelArrayFormatter' => 'formatter/PropelArrayFormatter.php', - 'PropelFormatter' => 'formatter/PropelFormatter.php', - 'PropelObjectFormatter' => 'formatter/PropelObjectFormatter.php', - 'PropelOnDemandFormatter' => 'formatter/PropelOnDemandFormatter.php', - 'PropelStatementFormatter' => 'formatter/PropelStatementFormatter.php', - - 'BasicLogger' => 'logger/BasicLogger.php', - 'MojaviLogAdapter' => 'logger/MojaviLogAdapter.php', - - 'ColumnMap' => 'map/ColumnMap.php', - 'DatabaseMap' => 'map/DatabaseMap.php', - 'TableMap' => 'map/TableMap.php', - 'RelationMap' => 'map/RelationMap.php', - 'ValidatorMap' => 'map/ValidatorMap.php', - - 'BaseObject' => 'om/BaseObject.php', - 'NodeObject' => 'om/NodeObject.php', - 'Persistent' => 'om/Persistent.php', - 'PreOrderNodeIterator' => 'om/PreOrderNodeIterator.php', - 'NestedSetPreOrderNodeIterator' => 'om/NestedSetPreOrderNodeIterator.php', - 'NestedSetRecursiveIterator' => 'om/NestedSetRecursiveIterator.php', - - 'Criteria' => 'query/Criteria.php', - 'Criterion' => 'query/Criterion.php', - 'CriterionIterator' => 'query/CriterionIterator.php', - 'Join' => 'query/Join.php', - 'ModelCriteria' => 'query/ModelCriteria.php', - 'ModelCriterion' => 'query/ModelCriterion.php', - 'ModelJoin' => 'query/ModelJoin.php', - 'PropelQuery' => 'query/PropelQuery.php', - - 'BasePeer' => 'util/BasePeer.php', - 'NodePeer' => 'util/NodePeer.php', - 'PeerInfo' => 'util/PeerInfo.php', - 'PropelAutoloader' => 'util/PropelAutoloader.php', - 'PropelColumnTypes' => 'util/PropelColumnTypes.php', - 'PropelConditionalProxy' => 'util/PropelConditionalProxy.php', - 'PropelModelPager' => 'util/PropelModelPager.php', - 'PropelPager' => 'util/PropelPager.php', - 'PropelDateTime' => 'util/PropelDateTime.php', - - 'BasicValidator' => 'validator/BasicValidator.php', - 'MatchValidator' => 'validator/MatchValidator.php', - 'MaxLengthValidator' => 'validator/MaxLengthValidator.php', - 'MaxValueValidator' => 'validator/MaxValueValidator.php', - 'MinLengthValidator' => 'validator/MinLengthValidator.php', - 'MinValueValidator' => 'validator/MinValueValidator.php', - 'NotMatchValidator' => 'validator/NotMatchValidator.php', - 'RequiredValidator' => 'validator/RequiredValidator.php', - 'UniqueValidator' => 'validator/UniqueValidator.php', - 'ValidValuesValidator' => 'validator/ValidValuesValidator.php', - 'ValidationFailed' => 'validator/ValidationFailed.php', - ); - - /** - * Initializes Propel - * - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function initialize() - { - if (self::$configuration === null) { - throw new PropelException("Propel cannot be initialized without a valid configuration. Please check the log files for further details."); - } - - self::configureLogging(); - - // reset the connection map (this should enable runtime changes of connection params) - self::$connectionMap = array(); - - if (isset(self::$configuration['classmap']) && is_array(self::$configuration['classmap'])) { - PropelAutoloader::getInstance()->addClassPaths(self::$configuration['classmap']); - PropelAutoloader::getInstance()->register(); - } - - self::$isInit = true; - } - - /** - * Configure Propel a PHP (array) config file. - * - * @param string Path (absolute or relative to include_path) to config file. - * - * @throws PropelException If configuration file cannot be opened. - * (E_WARNING probably will also be raised by PHP) - */ - public static function configure($configFile) - { - $configuration = include($configFile); - if ($configuration === false) { - throw new PropelException("Unable to open configuration file: " . var_export($configFile, true)); - } - self::setConfiguration($configuration); - } - - /** - * Configure the logging system, if config is specified in the runtime configuration. - */ - protected static function configureLogging() - { - if (self::$logger === null) { - if (isset(self::$configuration['log']) && is_array(self::$configuration['log']) && count(self::$configuration['log'])) { - include_once 'Log.php'; // PEAR Log class - $c = self::$configuration['log']; - $type = isset($c['type']) ? $c['type'] : 'file'; - $name = isset($c['name']) ? $c['name'] : './propel.log'; - $ident = isset($c['ident']) ? $c['ident'] : 'propel'; - $conf = isset($c['conf']) ? $c['conf'] : array(); - $level = isset($c['level']) ? $c['level'] : PEAR_LOG_DEBUG; - self::$logger = Log::singleton($type, $name, $ident, $conf, $level); - } // if isset() - } - } - - /** - * Initialization of Propel a PHP (array) configuration file. - * - * @param string $c The Propel configuration file path. - * - * @throws PropelException Any exceptions caught during processing will be - * rethrown wrapped into a PropelException. - */ - public static function init($c) - { - self::configure($c); - self::initialize(); - } - - /** - * Determine whether Propel has already been initialized. - * - * @return bool True if Propel is already initialized. - */ - public static function isInit() - { - return self::$isInit; - } - - /** - * Sets the configuration for Propel and all dependencies. - * - * @param mixed The Configuration (array or PropelConfiguration) - */ - public static function setConfiguration($c) - { - if (is_array($c)) { - if (isset($c['propel']) && is_array($c['propel'])) { - $c = $c['propel']; - } - $c = new PropelConfiguration($c); - } - self::$configuration = $c; - } - - /** - * Get the configuration for this component. - * - * @param int - PropelConfiguration::TYPE_ARRAY: return the configuration as an array - * (for backward compatibility this is the default) - * - PropelConfiguration::TYPE_ARRAY_FLAT: return the configuration as a flat array - * ($config['name.space.item']) - * - PropelConfiguration::TYPE_OBJECT: return the configuration as a PropelConfiguration instance - * @return mixed The Configuration (array or PropelConfiguration) - */ - public static function getConfiguration($type = PropelConfiguration::TYPE_ARRAY) - { - return self::$configuration->getParameters($type); - } - - /** - * Override the configured logger. - * - * This is primarily for things like unit tests / debugging where - * you want to change the logger without altering the configuration file. - * - * You can use any logger class that implements the propel.logger.BasicLogger - * interface. This interface is based on PEAR::Log, so you can also simply pass - * a PEAR::Log object to this method. - * - * @param object The new logger to use. ([PEAR] Log or BasicLogger) - */ - public static function setLogger($logger) - { - self::$logger = $logger; - } - - /** - * Returns true if a logger, for example PEAR::Log, has been configured, - * otherwise false. - * - * @return bool True if Propel uses logging - */ - public static function hasLogger() - { - return (self::$logger !== null); - } - - /** - * Get the configured logger. - * - * @return object Configured log class ([PEAR] Log or BasicLogger). - */ - public static function logger() - { - return self::$logger; - } - - /** - * Logs a message - * If a logger has been configured, the logger will be used, otherwrise the - * logging message will be discarded without any further action - * - * @param string The message that will be logged. - * @param string The logging level. - * - * @return bool True if the message was logged successfully or no logger was used. - */ - public static function log($message, $level = self::LOG_DEBUG) - { - if (self::hasLogger()) { - $logger = self::logger(); - switch ($level) { - case self::LOG_EMERG: - return $logger->log($message, $level); - case self::LOG_ALERT: - return $logger->alert($message); - case self::LOG_CRIT: - return $logger->crit($message); - case self::LOG_ERR: - return $logger->err($message); - case self::LOG_WARNING: - return $logger->warning($message); - case self::LOG_NOTICE: - return $logger->notice($message); - case self::LOG_INFO: - return $logger->info($message); - default: - return $logger->debug($message); - } - } - return true; - } - - /** - * Returns the database map information. Name relates to the name - * of the connection pool to associate with the map. - * - * The database maps are "registered" by the generated map builder classes. - * - * @param string The name of the database corresponding to the DatabaseMap to retrieve. - * - * @return DatabaseMap The named DatabaseMap. - * - * @throws PropelException - if database map is null or propel was not initialized properly. - */ - public static function getDatabaseMap($name = null) - { - if ($name === null) { - $name = self::getDefaultDB(); - if ($name === null) { - throw new PropelException("DatabaseMap name is null!"); - } - } - - if (!isset(self::$dbMaps[$name])) { - $clazz = self::$databaseMapClass; - self::$dbMaps[$name] = new $clazz($name); - } - - return self::$dbMaps[$name]; - } - - /** - * Sets the database map object to use for specified datasource. - * - * @param string $name The datasource name. - * @param DatabaseMap $map The database map object to use for specified datasource. - */ - public static function setDatabaseMap($name, DatabaseMap $map) - { - if ($name === null) { - $name = self::getDefaultDB(); - } - self::$dbMaps[$name] = $map; - } - - /** - * For replication, set whether to always force the use of a master connection. - * - * @param boolean $bit True or False - */ - public static function setForceMasterConnection($bit) - { - self::$forceMasterConnection = (bool) $bit; - } - - /** - * For replication, whether to always force the use of a master connection. - * - * @return boolean - */ - public static function getForceMasterConnection() - { - return self::$forceMasterConnection; - } - - /** - * Sets a Connection for specified datasource name. - * - * @param string $name The datasource name for the connection being set. - * @param PropelPDO $con The PDO connection. - * @param string $mode Whether this is a READ or WRITE connection (Propel::CONNECTION_READ, Propel::CONNECTION_WRITE) - */ - public static function setConnection($name, PropelPDO $con, $mode = Propel::CONNECTION_WRITE) - { - if ($name === null) { - $name = self::getDefaultDB(); - } - if ($mode == Propel::CONNECTION_READ) { - self::$connectionMap[$name]['slave'] = $con; - } else { - self::$connectionMap[$name]['master'] = $con; - } - } - - /** - * Gets an already-opened PDO connection or opens a new one for passed-in db name. - * - * @param string $name The datasource name that is used to look up the DSN from the runtime configuation file. - * @param string $mode The connection mode (this applies to replication systems). - * - * @return PDO A database connection - * - * @throws PropelException - if connection cannot be configured or initialized. - */ - public static function getConnection($name = null, $mode = Propel::CONNECTION_WRITE) - { - if ($name === null) { - $name = self::getDefaultDB(); - } - - // IF a WRITE-mode connection was requested - // or Propel is configured to always use the master connection - // THEN return the master connection. - if ($mode != Propel::CONNECTION_READ || self::$forceMasterConnection) { - return self::getMasterConnection($name); - } else { - return self::getSlaveConnection($name); - } - - } - - /** - * Gets an already-opened write PDO connection or opens a new one for passed-in db name. - * - * @param string $name The datasource name that is used to look up the DSN - * from the runtime configuation file. Empty name not allowed. - * - * @return PDO A database connection - * - * @throws PropelException - if connection cannot be configured or initialized. - */ - public static function getMasterConnection($name) - { - if (!isset(self::$connectionMap[$name]['master'])) { - // load connection parameter for master connection - $conparams = isset(self::$configuration['datasources'][$name]['connection']) ? self::$configuration['datasources'][$name]['connection'] : null; - if (empty($conparams)) { - throw new PropelException('No connection information in your runtime configuration file for datasource ['.$name.']'); - } - // initialize master connection - $con = Propel::initConnection($conparams, $name); - self::$connectionMap[$name]['master'] = $con; - } - - return self::$connectionMap[$name]['master']; - } - - /** - * Gets an already-opened read PDO connection or opens a new one for passed-in db name. - * - * @param string $name The datasource name that is used to look up the DSN - * from the runtime configuation file. Empty name not allowed. - * - * @return PDO A database connection - * - * @throws PropelException - if connection cannot be configured or initialized. - */ - public static function getSlaveConnection($name) - { - if (!isset(self::$connectionMap[$name]['slave'])) { - - $slaveconfigs = isset(self::$configuration['datasources'][$name]['slaves']) ? self::$configuration['datasources'][$name]['slaves'] : null; - - if (empty($slaveconfigs)) { - // no slaves configured for this datasource - // fallback to the master connection - self::$connectionMap[$name]['slave'] = self::getMasterConnection($name); - } else { - // Initialize a new slave - if (isset($slaveconfigs['connection']['dsn'])) { - // only one slave connection configured - $conparams = $slaveconfigs['connection']; - } else { - // more than one sleve connection configured - // pickup a random one - $randkey = array_rand($slaveconfigs['connection']); - $conparams = $slaveconfigs['connection'][$randkey]; - if (empty($conparams)) { - throw new PropelException('No connection information in your runtime configuration file for SLAVE ['.$randkey.'] to datasource ['.$name.']'); - } - } - - // initialize slave connection - $con = Propel::initConnection($conparams, $name); - self::$connectionMap[$name]['slave'] = $con; - } - - } // if datasource slave not set - - return self::$connectionMap[$name]['slave']; - } - - /** - * Opens a new PDO connection for passed-in db name. - * - * @param array $conparams Connection paramters. - * @param string $name Datasource name. - * @param string $defaultClass The PDO subclass to instantiate if there is no explicit classname - * specified in the connection params (default is Propel::CLASS_PROPEL_PDO) - * - * @return PDO A database connection of the given class (PDO, PropelPDO, SlavePDO or user-defined) - * - * @throws PropelException - if lower-level exception caught when trying to connect. - */ - public static function initConnection($conparams, $name, $defaultClass = Propel::CLASS_PROPEL_PDO) - { - - $dsn = $conparams['dsn']; - if ($dsn === null) { - throw new PropelException('No dsn specified in your connection parameters for datasource ['.$name.']'); - } - - if (isset($conparams['classname']) && !empty($conparams['classname'])) { - $classname = $conparams['classname']; - if (!class_exists($classname)) { - throw new PropelException('Unable to load specified PDO subclass: ' . $classname); - } - } else { - $classname = $defaultClass; - } - - $user = isset($conparams['user']) ? $conparams['user'] : null; - $password = isset($conparams['password']) ? $conparams['password'] : null; - - // load any driver options from the config file - // driver options are those PDO settings that have to be passed during the connection construction - $driver_options = array(); - if ( isset($conparams['options']) && is_array($conparams['options']) ) { - try { - self::processDriverOptions( $conparams['options'], $driver_options ); - } catch (PropelException $e) { - throw new PropelException('Error processing driver options for datasource ['.$name.']', $e); - } - } - - try { - $con = new $classname($dsn, $user, $password, $driver_options); - $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - if (Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->getParameter('debugpdo.logging.enabled', false)) { - $con->useLogging(true); - } - } catch (PDOException $e) { - throw new PropelException("Unable to open PDO connection", $e); - } - - // load any connection options from the config file - // connection attributes are those PDO flags that have to be set on the initialized connection - if (isset($conparams['attributes']) && is_array($conparams['attributes'])) { - $attributes = array(); - try { - self::processDriverOptions( $conparams['attributes'], $attributes ); - } catch (PropelException $e) { - throw new PropelException('Error processing connection attributes for datasource ['.$name.']', $e); - } - foreach ($attributes as $key => $value) { - $con->setAttribute($key, $value); - } - } - - // initialize the connection using the settings provided in the config file. this could be a "SET NAMES " query for MySQL, for instance - $adapter = self::getDB($name); - $adapter->initConnection($con, isset($conparams['settings']) && is_array($conparams['settings']) ? $conparams['settings'] : array()); - - return $con; - } - - /** - * Internal function to handle driver options or conneciton attributes in PDO. - * - * Process the INI file flags to be passed to each connection. - * - * @param array Where to find the list of constant flags and their new setting. - * @param array Put the data into here - * - * @throws PropelException If invalid options were specified. - */ - private static function processDriverOptions($source, &$write_to) - { - foreach ($source as $option => $optiondata) { - if (is_string($option) && strpos($option, '::') !== false) { - $key = $option; - } elseif (is_string($option)) { - $key = 'PropelPDO::' . $option; - } - if (!defined($key)) { - throw new PropelException("Invalid PDO option/attribute name specified: ".$key); - } - $key = constant($key); - - $value = $optiondata['value']; - if (is_string($value) && strpos($value, '::') !== false) { - if (!defined($value)) { - throw new PropelException("Invalid PDO option/attribute value specified: ".$value); - } - $value = constant($value); - } - - $write_to[$key] = $value; - } - } - - /** - * Returns database adapter for a specific datasource. - * - * @param string The datasource name. - * - * @return DBAdapter The corresponding database adapter. - * - * @throws PropelException If unable to find DBdapter for specified db. - */ - public static function getDB($name = null) - { - if ($name === null) { - $name = self::getDefaultDB(); - } - - if (!isset(self::$adapterMap[$name])) { - if (!isset(self::$configuration['datasources'][$name]['adapter'])) { - throw new PropelException("Unable to find adapter for datasource [" . $name . "]."); - } - $db = DBAdapter::factory(self::$configuration['datasources'][$name]['adapter']); - // register the adapter for this name - self::$adapterMap[$name] = $db; - } - - return self::$adapterMap[$name]; - } - - /** - * Sets a database adapter for specified datasource. - * - * @param string $name The datasource name. - * @param DBAdapter $adapter The DBAdapter implementation to use. - */ - public static function setDB($name, DBAdapter $adapter) - { - if ($name === null) { - $name = self::getDefaultDB(); - } - self::$adapterMap[$name] = $adapter; - } - - /** - * Returns the name of the default database. - * - * @return string Name of the default DB - */ - public static function getDefaultDB() - { - if (self::$defaultDBName === null) { - // Determine default database name. - self::$defaultDBName = isset(self::$configuration['datasources']['default']) ? self::$configuration['datasources']['default'] : self::DEFAULT_NAME; - } - return self::$defaultDBName; - } - - /** - * Closes any associated resource handles. - * - * This method frees any database connection handles that have been - * opened by the getConnection() method. - */ - public static function close() - { - foreach (self::$connectionMap as $idx => $cons) { - // Propel::log("Closing connections for " . $idx, Propel::LOG_DEBUG); - unset(self::$connectionMap[$idx]); - } - } - - /** - * Autoload function for loading propel dependencies. - * - * @param string The class name needing loading. - * - * @return boolean TRUE if the class was loaded, false otherwise. - */ - public static function autoload($className) - { - if (isset(self::$autoloadMap[$className])) { - require self::$baseDir . self::$autoloadMap[$className]; - return true; - } - return false; - } - - /** - * Initialize the base directory for the autoloader. - * Avoids a call to dirname(__FILE__) each time self::autoload() is called. - * FIXME put in the constructor if the Propel class ever becomes a singleton - */ - public static function initBaseDir() - { - self::$baseDir = dirname(__FILE__) . '/'; - } - - /** - * Include once a file specified in DOT notation and return unqualified classname. - * - * Typically, Propel uses autoload is used to load classes and expects that all classes - * referenced within Propel are included in Propel's autoload map. This method is only - * called when a specific non-Propel classname was specified -- for example, the - * classname of a validator in the schema.xml. This method will attempt to include that - * class via autoload and then relative to a location on the include_path. - * - * @param string $class dot-path to clas (e.g. path.to.my.ClassName). - * @return string unqualified classname - */ - public static function importClass($path) { - - // extract classname - if (($pos = strrpos($path, '.')) === false) { - $class = $path; - } else { - $class = substr($path, $pos + 1); - } - - // check if class exists, using autoloader to attempt to load it. - if (class_exists($class, $useAutoload=true)) { - return $class; - } - - // turn to filesystem path - $path = strtr($path, '.', DIRECTORY_SEPARATOR) . '.php'; - - // include class - $ret = include_once($path); - if ($ret === false) { - throw new PropelException("Unable to import class: " . $class . " from " . $path); - } - - // return qualified name - return $class; - } - - /** - * Set your own class-name for Database-Mapping. Then - * you can change the whole TableMap-Model, but keep its - * functionality for Criteria. - * - * @param string The name of the class. - */ - public static function setDatabaseMapClass($name) - { - self::$databaseMapClass = $name; - } - - /** - * Disable instance pooling. - * - * @return boolean true if the method changed the instance pooling state, - * false if it was already disabled - */ - public static function disableInstancePooling() - { - if (!self::$instancePoolingEnabled) { - return false; - } - self::$instancePoolingEnabled = false; - return true; - } - - /** - * Enable instance pooling (enabled by default). - * - * @return boolean true if the method changed the instance pooling state, - * false if it was already enabled - */ - public static function enableInstancePooling() - { - if (self::$instancePoolingEnabled) { - return false; - } - self::$instancePoolingEnabled = true; - return true; - } - - /** - * the instance pooling behaviour. True by default. - * - * @return boolean Whether the pooling is enabled or not. - */ - public static function isInstancePoolingEnabled() - { - return self::$instancePoolingEnabled; - } -} - -// Since the Propel class is not a true singleton, this code cannot go into the __construct() -Propel::initBaseDir(); -spl_autoload_register(array('Propel', 'autoload')); diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBAdapter.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBAdapter.php deleted file mode 100644 index 4da98dc38..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBAdapter.php +++ /dev/null @@ -1,297 +0,0 @@ - defines the interface for a Propel database adapter. - * - *

Support for new databases is added by subclassing - * DBAdapter and implementing its abstract interface, and by - * registering the new database adapter and corresponding Propel - * driver in the private adapters map (array) in this class.

- * - *

The Propel database adapters exist to present a uniform - * interface to database access across all available databases. Once - * the necessary adapters have been written and configured, - * transparent swapping of databases is theoretically supported with - * zero code change and minimal configuration file - * modifications.

- * - * @author Hans Lellelid (Propel) - * @author Jon S. Stevens (Torque) - * @author Brett McLaughlin (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.adapter - */ -abstract class DBAdapter -{ - - const ID_METHOD_NONE = 0; - const ID_METHOD_AUTOINCREMENT = 1; - const ID_METHOD_SEQUENCE = 2; - - /** - * Propel driver to Propel adapter map. - * @var array - */ - private static $adapters = array( - 'mysql' => 'DBMySQL', - 'mysqli' => 'DBMySQLi', - 'mssql' => 'DBMSSQL', - 'dblib' => 'DBMSSQL', - 'sybase' => 'DBSybase', - 'oracle' => 'DBOracle', - 'oci' => 'DBOracle', - 'pgsql' => 'DBPostgres', - 'sqlite' => 'DBSQLite', - '' => 'DBNone', - ); - - /** - * Creates a new instance of the database adapter associated - * with the specified Propel driver. - * - * @param string $driver The name of the Propel driver to - * create a new adapter instance for or a shorter form adapter key. - * @return DBAdapter An instance of a Propel database adapter. - * @throws PropelException if the adapter could not be instantiated. - */ - public static function factory($driver) { - $adapterClass = isset(self::$adapters[$driver]) ? self::$adapters[$driver] : null; - if ($adapterClass !== null) { - $a = new $adapterClass(); - return $a; - } else { - throw new PropelException("Unsupported Propel driver: " . $driver . ": Check your configuration file"); - } - } - - /** - * This method is called after a connection was created to run necessary - * post-initialization queries or code. - * - * If a charset was specified, this will be set before any other queries - * are executed. - * - * This base method runs queries specified using the "query" setting. - * - * @param PDO A PDO connection instance. - * @param array An array of settings. - * @see setCharset() - */ - public function initConnection(PDO $con, array $settings) - { - if (isset($settings['charset']['value'])) { - $this->setCharset($con, $settings['charset']['value']); - } - if (isset($settings['queries']) && is_array($settings['queries'])) { - foreach ($settings['queries'] as $queries) { - foreach ((array)$queries as $query) { - $con->exec($query); - } - } - } - } - - /** - * Sets the character encoding using SQL standard SET NAMES statement. - * - * This method is invoked from the default initConnection() method and must - * be overridden for an RDMBS which does _not_ support this SQL standard. - * - * @param PDO A PDO connection instance. - * @param string The charset encoding. - * @see initConnection() - */ - public function setCharset(PDO $con, $charset) - { - $con->exec("SET NAMES '" . $charset . "'"); - } - - /** - * This method is used to ignore case. - * - * @param string The string to transform to upper case. - * @return string The upper case string. - */ - public abstract function toUpperCase($in); - - /** - * Returns the character used to indicate the beginning and end of - * a piece of text used in a SQL statement (generally a single - * quote). - * - * @return string The text delimeter. - */ - public function getStringDelimiter() - { - return '\''; - } - - /** - * This method is used to ignore case. - * - * @param string $in The string whose case to ignore. - * @return string The string in a case that can be ignored. - */ - public abstract function ignoreCase($in); - - /** - * This method is used to ignore case in an ORDER BY clause. - * Usually it is the same as ignoreCase, but some databases - * (Interbase for example) does not use the same SQL in ORDER BY - * and other clauses. - * - * @param string $in The string whose case to ignore. - * @return string The string in a case that can be ignored. - */ - public function ignoreCaseInOrderBy($in) - { - return $this->ignoreCase($in); - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public abstract function concatString($s1, $s2); - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public abstract function subString($s, $pos, $len); - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public abstract function strLength($s); - - - /** - * Quotes database objec identifiers (table names, col names, sequences, etc.). - * @param string $text The identifier to quote. - * @return string The quoted identifier. - */ - public function quoteIdentifier($text) - { - return '"' . $text . '"'; - } - - /** - * Quotes a database table which could have space seperating it from an alias, both should be identified seperately - * @param string $table The table name to quo - * @return string The quoted table name - **/ - public function quoteIdentifierTable($table) { - return implode(" ", array_map(array($this, "quoteIdentifier"), explode(" ", $table) ) ); - } - - /** - * Returns the native ID method for this RDBMS. - * @return int one of DBAdapter:ID_METHOD_SEQUENCE, DBAdapter::ID_METHOD_AUTOINCREMENT. - */ - protected function getIdMethod() - { - return DBAdapter::ID_METHOD_AUTOINCREMENT; - } - - /** - * Whether this adapter uses an ID generation system that requires getting ID _before_ performing INSERT. - * @return boolean - */ - public function isGetIdBeforeInsert() - { - return ($this->getIdMethod() === DBAdapter::ID_METHOD_SEQUENCE); - } - - /** - * Whether this adapter uses an ID generation system that requires getting ID _before_ performing INSERT. - * @return boolean - */ - public function isGetIdAfterInsert() - { - return ($this->getIdMethod() === DBAdapter::ID_METHOD_AUTOINCREMENT); - } - - /** - * Gets the generated ID (either last ID for autoincrement or next sequence ID). - * @return mixed - */ - public function getId(PDO $con, $name = null) - { - return $con->lastInsertId($name); - } - - /** - * Returns timestamp formatter string for use in date() function. - * @return string - */ - public function getTimestampFormatter() - { - return "Y-m-d H:i:s"; - } - - /** - * Returns date formatter string for use in date() function. - * @return string - */ - public function getDateFormatter() - { - return "Y-m-d"; - } - - /** - * Returns time formatter string for use in date() function. - * @return string - */ - public function getTimeFormatter() - { - return "H:i:s"; - } - - /** - * Should Column-Names get identifiers for inserts or updates. - * By default false is returned -> backwards compability. - * - * it`s a workaround...!!! - * - * @todo should be abstract - * @return boolean - * @deprecated - */ - public function useQuoteIdentifier() - { - return false; - } - - /** - * Modifies the passed-in SQL to add LIMIT and/or OFFSET. - */ - public abstract function applyLimit(&$sql, $offset, $limit); - - /** - * Gets the SQL string that this adapter uses for getting a random number. - * - * @param mixed $seed (optional) seed value for databases that support this - */ - public abstract function random($seed = null); - -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBMSSQL.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBMSSQL.php deleted file mode 100644 index f98fa7dfc..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBMSSQL.php +++ /dev/null @@ -1,215 +0,0 @@ - (Propel) - * @version $Revision: 1700 $ - * @package propel.runtime.adapter - */ -class DBMSSQL extends DBAdapter -{ - - /** - * This method is used to ignore case. - * - * @param in The string to transform to upper case. - * @return The upper case string. - */ - public function toUpperCase($in) - { - return $this->ignoreCase($in); - } - - /** - * This method is used to ignore case. - * - * @param in The string whose case to ignore. - * @return The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return '(' . $s1 . ' + ' . $s2 . ')'; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return 'SUBSTRING(' . $s . ', ' . $pos . ', ' . $len . ')'; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return 'LEN(' . $s . ')'; - } - - /** - * @see DBAdapter::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - /** - * @see DBAdapter::random() - */ - public function random($seed = null) - { - return 'RAND(' . ((int)$seed) . ')'; - } - - /** - * Simulated Limit/Offset - * This rewrites the $sql query to apply the offset and limit. - * some of the ORDER BY logic borrowed from Doctrine MsSqlPlatform - * @see DBAdapter::applyLimit() - * @author Benjamin Runnels - */ - public function applyLimit(&$sql, $offset, $limit) - { - // make sure offset and limit are numeric - if(! is_numeric($offset) || ! is_numeric($limit)) - { - throw new PropelException('DBMSSQL::applyLimit() expects a number for argument 2 and 3'); - } - - //split the select and from clauses out of the original query - $selectSegment = array(); - - $selectText = 'SELECT '; - - if (preg_match('/\Aselect(\s+)distinct/i', $sql)) { - $selectText .= 'DISTINCT '; - } - - preg_match('/\Aselect(.*)from(.*)/si', $sql, $selectSegment); - if(count($selectSegment) == 3) { - $selectStatement = trim($selectSegment[1]); - $fromStatement = trim($selectSegment[2]); - } else { - throw new Exception('DBMSSQL::applyLimit() could not locate the select statement at the start of the query.'); - } - - // if we're starting at offset 0 then theres no need to simulate limit, - // just grab the top $limit number of rows - if($offset == 0) { - $sql = $selectText . 'TOP ' . $limit . ' ' . $selectStatement . ' FROM ' . $fromStatement; - return; - } - - //get the ORDER BY clause if present - $orderStatement = stristr($fromStatement, 'ORDER BY'); - $orders = ''; - - if($orderStatement !== false) { - //remove order statement from the from statement - $fromStatement = trim(str_replace($orderStatement, '', $fromStatement)); - - $order = str_ireplace('ORDER BY', '', $orderStatement); - $orders = explode(',', $order); - - for($i = 0; $i < count($orders); $i ++) { - $orderArr[trim(preg_replace('/\s+(ASC|DESC)$/i', '', $orders[$i]))] = array( - 'sort' => (stripos($orders[$i], ' DESC') !== false) ? 'DESC' : 'ASC', - 'key' => $i - ); - } - } - - //setup inner and outer select selects - $innerSelect = ''; - $outerSelect = ''; - foreach(explode(', ', $selectStatement) as $selCol) { - $selColArr = explode(' ', $selCol); - $selColCount = count($selColArr) - 1; - - //make sure the current column isn't * or an aggregate - if($selColArr[0] != '*' && ! strstr($selColArr[0], '(')) { - if(isset($orderArr[$selColArr[0]])) { - $orders[$orderArr[$selColArr[0]]['key']] = $selColArr[0] . ' ' . $orderArr[$selColArr[0]]['sort']; - } - - //use the alias if one was present otherwise use the column name - $alias = (! stristr($selCol, ' AS ')) ? $this->quoteIdentifier($selColArr[0]) : $this->quoteIdentifier($selColArr[$selColCount]); - - //save the first non-aggregate column for use in ROW_NUMBER() if required - if(! isset($firstColumnOrderStatement)) { - $firstColumnOrderStatement = 'ORDER BY ' . $selColArr[0]; - } - - //add an alias to the inner select so all columns will be unique - $innerSelect .= $selColArr[0] . ' AS ' . $alias . ', '; - $outerSelect .= $alias . ', '; - } else { - //agregate columns must always have an alias clause - if(! stristr($selCol, ' AS ')) { - throw new Exception('DBMSSQL::applyLimit() requires aggregate columns to have an Alias clause'); - } - - //aggregate column alias can't be used as the count column you must use the entire aggregate statement - if(isset($orderArr[$selColArr[$selColCount]])) { - $orders[$orderArr[$selColArr[$selColCount]]['key']] = str_replace($selColArr[$selColCount - 1] . ' ' . $selColArr[$selColCount], '', $selCol) . $orderArr[$selColArr[$selColCount]]['sort']; - } - - //quote the alias - $alias = $this->quoteIdentifier($selColArr[$selColCount]); - $innerSelect .= str_replace($selColArr[$selColCount], $alias, $selCol) . ', '; - $outerSelect .= $alias . ', '; - } - } - - if(is_array($orders)) { - $orderStatement = 'ORDER BY ' . implode(', ', $orders); - } else { - //use the first non aggregate column in our select statement if no ORDER BY clause present - if(isset($firstColumnOrderStatement)) { - $orderStatement = $firstColumnOrderStatement; - } else { - throw new Exception('DBMSSQL::applyLimit() unable to find column to use with ROW_NUMBER()'); - } - } - - //substring the select strings to get rid of the last comma and add our FROM and SELECT clauses - $innerSelect = $selectText . 'ROW_NUMBER() OVER(' . $orderStatement . ') AS RowNumber, ' . substr($innerSelect, 0, - 2) . ' FROM'; - //outer select can't use * because of the RowNumber column - $outerSelect = 'SELECT ' . substr($outerSelect, 0, - 2) . ' FROM'; - - //ROW_NUMBER() starts at 1 not 0 - $sql = $outerSelect . ' (' . $innerSelect . ' ' . $fromStatement . ') AS derivedb WHERE RowNumber BETWEEN ' . ($offset + 1) . ' AND ' . ($limit + $offset); - return; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBMySQL.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBMySQL.php deleted file mode 100644 index 99818e8cd..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBMySQL.php +++ /dev/null @@ -1,145 +0,0 @@ - (Propel) - * @author Jon S. Stevens (Torque) - * @author Brett McLaughlin (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.adapter - */ -class DBMySQL extends DBAdapter -{ - - /** - * This method is used to ignore case. - * - * @param in The string to transform to upper case. - * @return The upper case string. - */ - public function toUpperCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * This method is used to ignore case. - * - * @param in The string whose case to ignore. - * @return The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return "CONCAT($s1, $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return "SUBSTRING($s, $pos, $len)"; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return "CHAR_LENGTH($s)"; - } - - - /** - * Locks the specified table. - * - * @param Connection $con The Propel connection to use. - * @param string $table The name of the table to lock. - * @throws PDOException No Statement could be created or - * executed. - */ - public function lockTable(PDO $con, $table) - { - $con->exec("LOCK TABLE " . $table . " WRITE"); - } - - /** - * Unlocks the specified table. - * - * @param PDO $con The PDO connection to use. - * @param string $table The name of the table to unlock. - * @throws PDOException No Statement could be created or - * executed. - */ - public function unlockTable(PDO $con, $table) - { - $statement = $con->exec("UNLOCK TABLES"); - } - - /** - * @see DBAdapter::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '`' . $text . '`'; - } - - /** - * @see DBAdapter::useQuoteIdentifier() - */ - public function useQuoteIdentifier() - { - return true; - } - - /** - * @see DBAdapter::applyLimit() - */ - public function applyLimit(&$sql, $offset, $limit) - { - if ( $limit > 0 ) { - $sql .= " LIMIT " . ($offset > 0 ? $offset . ", " : "") . $limit; - } else if ( $offset > 0 ) { - $sql .= " LIMIT " . $offset . ", 18446744073709551615"; - } - } - - /** - * @see DBAdapter::random() - */ - public function random($seed = null) - { - return 'rand('.((int) $seed).')'; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBNone.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBNone.php deleted file mode 100644 index 1349f17da..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBNone.php +++ /dev/null @@ -1,104 +0,0 @@ - (Propel) - * @author Jon S. Stevens (Torque) - * @author Brett McLaughlin (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.adapter - */ -class DBNone extends DBAdapter -{ - - /** - * @see DBAdapter::initConnection() - */ - public function initConnection(PDO $con, array $settings) - { - } - - /** - * This method is used to ignore case. - * - * @param in The string to transform to upper case. - * @return The upper case string. - */ - public function toUpperCase($in) - { - return $in; - } - - /** - * This method is used to ignore case. - * - * @param in The string whose case to ignore. - * @return The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return $in; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return ($s1 . $s2); - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return substr($s, $pos, $len); - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return strlen($s); - } - - /** - * Modifies the passed-in SQL to add LIMIT and/or OFFSET. - */ - public function applyLimit(&$sql, $offset, $limit) - { - } - - /** - * Gets the SQL string that this adapter uses for getting a random number. - * - * @param mixed $seed (optional) seed value for databases that support this - */ - public function random($seed = null) - { - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBOracle.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBOracle.php deleted file mode 100644 index f67000a8e..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBOracle.php +++ /dev/null @@ -1,150 +0,0 @@ - (Propel) - * @author Hans Lellelid (Propel) - * @author Jon S. Stevens (Torque) - * @author Brett McLaughlin (Torque) - * @author Bill Schneider (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1669 $ - * @package propel.runtime.adapter - */ -class DBOracle extends DBAdapter -{ - /** - * This method is called after a connection was created to run necessary - * post-initialization queries or code. - * Removes the charset query and adds the date queries - * - * @param PDO A PDO connection instance. - * @see parent::initConnection() - */ - public function initConnection(PDO $con, array $settings) - { - $con->exec("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'"); - $con->exec("ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'"); - if (isset($settings['queries']) && is_array($settings['queries'])) { - foreach ($settings['queries'] as $queries) { - foreach ((array)$queries as $query) { - $con->exec($query); - } - } - } - } - - /** - * This method is used to ignore case. - * - * @param string $in The string to transform to upper case. - * @return string The upper case string. - */ - public function toUpperCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * This method is used to ignore case. - * - * @param string $in The string whose case to ignore. - * @return string The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return "CONCAT($s1, $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return "SUBSTR($s, $pos, $len)"; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return "LENGTH($s)"; - } - - /** - * @see DBAdapter::applyLimit() - */ - public function applyLimit(&$sql, $offset, $limit, $criteria = null) - { - if (BasePeer::needsSelectAliases($criteria)) { - $selectSql = BasePeer::createSelectSqlPart($criteria, $params, true); - $sql = $selectSql . substr($sql, strpos('FROM', $sql)); - } - $sql = 'SELECT B.* FROM (' - . 'SELECT A.*, rownum AS PROPEL_ROWNUM FROM (' . $sql . ') A ' - . ') B WHERE '; - - if ( $offset > 0 ) { - $sql .= ' B.PROPEL_ROWNUM > ' . $offset; - if ( $limit > 0 ) { - $sql .= ' AND B.PROPEL_ROWNUM <= ' . ( $offset + $limit ); - } - } else { - $sql .= ' B.PROPEL_ROWNUM <= ' . $limit; - } - } - - protected function getIdMethod() - { - return DBAdapter::ID_METHOD_SEQUENCE; - } - - public function getId(PDO $con, $name = null) - { - if ($name === null) { - throw new PropelException("Unable to fetch next sequence ID without sequence name."); - } - - $stmt = $con->query("SELECT " . $name . ".nextval FROM dual"); - $row = $stmt->fetch(PDO::FETCH_NUM); - - return $row[0]; - } - - public function random($seed=NULL) - { - return 'dbms_random.value'; - } - - -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBPostgres.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBPostgres.php deleted file mode 100644 index ad3243402..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBPostgres.php +++ /dev/null @@ -1,141 +0,0 @@ -http://www.pgsql.org - * - * @author Hans Lellelid (Propel) - * @author Hakan Tandogan (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.adapter - */ -class DBPostgres extends DBAdapter -{ - - /** - * This method is used to ignore case. - * - * @param string $in The string to transform to upper case. - * @return string The upper case string. - */ - public function toUpperCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * This method is used to ignore case. - * - * @param in The string whose case to ignore. - * @return The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return "UPPER(" . $in . ")"; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return "($s1 || $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return "substring($s from $pos" . ($len > -1 ? "for $len" : "") . ")"; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return "char_length($s)"; - } - - /** - * @see DBAdapter::getIdMethod() - */ - protected function getIdMethod() - { - return DBAdapter::ID_METHOD_SEQUENCE; - } - - /** - * Gets ID for specified sequence name. - */ - public function getId(PDO $con, $name = null) - { - if ($name === null) { - throw new PropelException("Unable to fetch next sequence ID without sequence name."); - } - $stmt = $con->query("SELECT nextval(".$con->quote($name).")"); - $row = $stmt->fetch(PDO::FETCH_NUM); - return $row[0]; - } - - /** - * Returns timestamp formatter string for use in date() function. - * @return string - */ - public function getTimestampFormatter() - { - return "Y-m-d H:i:s O"; - } - - /** - * Returns timestamp formatter string for use in date() function. - * @return string - */ - public function getTimeFormatter() - { - return "H:i:s O"; - } - - /** - * @see DBAdapter::applyLimit() - */ - public function applyLimit(&$sql, $offset, $limit) - { - if ( $limit > 0 ) { - $sql .= " LIMIT ".$limit; - } - if ( $offset > 0 ) { - $sql .= " OFFSET ".$offset; - } - } - - /** - * @see DBAdapter::random() - */ - public function random($seed=NULL) - { - return 'random()'; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/DBSQLite.php b/airtime_mvc/library/propel/runtime/lib/adapter/DBSQLite.php deleted file mode 100644 index 4b1da232d..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/DBSQLite.php +++ /dev/null @@ -1,116 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.adapter - */ -class DBSQLite extends DBAdapter -{ - - /** - * For SQLite this method has no effect, since SQLite doesn't support specifying a character - * set (or, another way to look at it, it doesn't require a single character set per DB). - * - * @param PDO A PDO connection instance. - * @param string The charset encoding. - * @throws PropelException If the specified charset doesn't match sqlite_libencoding() - */ - public function setCharset(PDO $con, $charset) - { - } - - /** - * This method is used to ignore case. - * - * @param in The string to transform to upper case. - * @return The upper case string. - */ - public function toUpperCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * This method is used to ignore case. - * - * @param in The string whose case to ignore. - * @return The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string String to concatenate. - * @param string String to append. - * @return string - */ - public function concatString($s1, $s2) - { - return "($s1 || $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string String to extract from. - * @param int Offset to start from. - * @param int Number of characters to extract. - * @return string - */ - public function subString($s, $pos, $len) - { - return "substr($s, $pos, $len)"; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string String to calculate length of. - * @return string - */ - public function strLength($s) - { - return "length($s)"; - } - - /** - * @see DBAdapter::quoteIdentifier() - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - /** - * @see DBAdapter::applyLimit() - */ - public function applyLimit(&$sql, $offset, $limit) - { - if ( $limit > 0 ) { - $sql .= " LIMIT " . $limit . ($offset > 0 ? " OFFSET " . $offset : ""); - } elseif ( $offset > 0 ) { - $sql .= " LIMIT -1 OFFSET " . $offset; - } - } - - public function random($seed=NULL) - { - return 'random()'; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlDateTime.class.php b/airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlDateTime.class.php deleted file mode 100644 index 512c9b497..000000000 --- a/airtime_mvc/library/propel/runtime/lib/adapter/MSSQL/MssqlDateTime.class.php +++ /dev/null @@ -1,35 +0,0 @@ -getNestedTransactionCount(); - if ( $opcount === 0 ) { - $return = self::exec('BEGIN TRANSACTION'); - if ($this->useDebug) { - $this->log('Begin transaction', null, __METHOD__); - } - $this->isUncommitable = false; - } - $this->nestedTransactionCount++; - return $return; - } - - /** - * Commit a transaction. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - */ - public function commit() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - if ($opcount === 1) { - if ($this->isUncommitable) { - throw new PropelException('Cannot commit because a nested transaction was rolled back'); - } else { - $return = self::exec('COMMIT TRANSACTION'); - if ($this->useDebug) { - $this->log('Commit transaction', null, __METHOD__); - } - - } - } - $this->nestedTransactionCount--; - } - return $return; - } - - /** - * Roll-back a transaction. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - */ - public function rollBack() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - if ($opcount === 1) { - $return = self::exec('ROLLBACK TRANSACTION'); - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } else { - $this->isUncommitable = true; - } - $this->nestedTransactionCount--; - } - return $return; - } - - /** - * Rollback the whole transaction, even if this is a nested rollback - * and reset the nested transaction count to 0. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - */ - public function forceRollBack() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - // If we're in a transaction, always roll it back - // regardless of nesting level. - $return = self::exec('ROLLBACK TRANSACTION'); - - // reset nested transaction count to 0 so that we don't - // try to commit (or rollback) the transaction outside this scope. - $this->nestedTransactionCount = 0; - - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } - return $return; - } - - public function lastInsertId($seqname = null) - { - $result = self::query('SELECT SCOPE_IDENTITY()'); - return (int) $result->fetchColumn(); - } - - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - public function useQuoteIdentifier() - { - return true; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/collection/PropelArrayCollection.php b/airtime_mvc/library/propel/runtime/lib/collection/PropelArrayCollection.php deleted file mode 100644 index c85bcecc4..000000000 --- a/airtime_mvc/library/propel/runtime/lib/collection/PropelArrayCollection.php +++ /dev/null @@ -1,188 +0,0 @@ -getConnection(Propel::CONNECTION_WRITE); - } - $con->beginTransaction(); - try { - $obj = $this->getWorkerObject(); - foreach ($this as $element) { - $obj->clear(); - $obj->fromArray($element); - $obj->setNew($obj->isPrimaryKeyNull()); - $obj->save($con); - } - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - } - } - - /** - * Delete all the elements in the collection - */ - public function delete($con = null) - { - if (null === $con) { - $con = $this->getConnection(Propel::CONNECTION_WRITE); - } - $con->beginTransaction(); - try { - foreach ($this as $element) { - $obj = $this->getWorkerObject(); - $obj->setDeleted(false); - $obj->fromArray($element); - $obj->delete($con); - } - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - throw $e; - } - } - - /** - * Get an array of the primary keys of all the objects in the collection - * - * @return array The list of the primary keys of the collection - */ - public function getPrimaryKeys($usePrefix = true) - { - $callable = array($this->getPeerClass(), 'getPrimaryKeyFromRow'); - $ret = array(); - foreach ($this as $key => $element) { - $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; - $ret[$key]= call_user_func($callable, array_values($element)); - } - - return $ret; - } - - /** - * Populates the collection from an array - * Uses the object model to force the column types - * Does not empty the collection before adding the data from the array - * - * @param array $arr - */ - public function fromArray($arr) - { - $obj = $this->getWorkerObject(); - foreach ($arr as $element) { - $obj->clear(); - $obj->fromArray($element); - $this->append($obj->toArray()); - } - } - - /** - * Get an array representation of the collection - * This is not an alias for getData(), since it returns a copy of the data - * - * @param string $keyColumn If null, the returned array uses an incremental index. - * Otherwise, the array is indexed using the specified column - * @param boolean $usePrefix If true, the returned array prefixes keys - * with the model class name ('Article_0', 'Article_1', etc). - * - * - * $bookCollection->toArray(); - * array( - * 0 => array('Id' => 123, 'Title' => 'War And Peace'), - * 1 => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * $bookCollection->toArray('Id'); - * array( - * 123 => array('Id' => 123, 'Title' => 'War And Peace'), - * 456 => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * $bookCollection->toArray(null, true); - * array( - * 'Book_0' => array('Id' => 123, 'Title' => 'War And Peace'), - * 'Book_1' => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * - * @return array - */ - public function toArray($keyColumn = null, $usePrefix = false) - { - $ret = array(); - foreach ($this as $key => $element) { - $key = null === $keyColumn ? $key : $element[$keyColumn]; - $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; - $ret[$key] = $element; - } - - return $ret; - } - - /** - * Synonym for toArray(), to provide a similar interface to PopelObjectCollection - */ - public function getArrayCopy($keyColumn = null, $usePrefix = false) - { - if (null === $keyColumn && false === $usePrefix) { - return parent::getArrayCopy(); - } else { - return $this->toArray($keyColumn, $usePrefix); - } - } - - /** - * Get an associative array representation of the collection - * The first parameter specifies the column to be used for the key, - * And the seconf for the value. - * - * $res = $coll->toKeyValue('Id', 'Name'); - * - * - * @return array - */ - public function toKeyValue($keyColumn, $valueColumn) - { - $ret = array(); - foreach ($this as $obj) { - $ret[$obj[$keyColumn]] = $obj[$valueColumn]; - } - - return $ret; - } - - protected function getWorkerObject() - { - if (null === $this->workerObject) { - if ($this->model == '') { - throw new PropelException('You must set the collection model before interacting with it'); - } - $class = $this->getModel(); - $this->workerObject = new $class(); - } - - return $this->workerObject; - } - -} - -?> \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/collection/PropelCollection.php b/airtime_mvc/library/propel/runtime/lib/collection/PropelCollection.php deleted file mode 100644 index a62b12da7..000000000 --- a/airtime_mvc/library/propel/runtime/lib/collection/PropelCollection.php +++ /dev/null @@ -1,409 +0,0 @@ -getArrayCopy(); - } - - /** - * Set the data in the collection - * - * @param array $data - */ - public function setData($data) - { - $this->exchangeArray($data); - } - - /** - * Gets the position of the internal pointer - * This position can be later used in seek() - * - * @return int - */ - public function getPosition() - { - return (int) $this->getInternalIterator()->key(); - } - - /** - * Move the internal pointer to the beginning of the list - * And get the first element in the collection - * - * @return mixed - */ - public function getFirst() - { - $this->getInternalIterator()->rewind(); - return $this->getCurrent(); - } - - /** - * Check whether the internal pointer is at the beginning of the list - * - * @return boolean - */ - public function isFirst() - { - return $this->getPosition() == 0; - } - - /** - * Move the internal pointer backward - * And get the previous element in the collection - * - * @return mixed - */ - public function getPrevious() - { - $pos = $this->getPosition(); - if ($pos == 0) { - return null; - } else { - $this->getInternalIterator()->seek($pos - 1); - return $this->getCurrent(); - } - } - - /** - * Get the current element in the collection - * - * @return mixed - */ - public function getCurrent() - { - return $this->getInternalIterator()->current(); - } - - /** - * Move the internal pointer forward - * And get the next element in the collection - * - * @return mixed - */ - public function getNext() - { - $this->getInternalIterator()->next(); - return $this->getCurrent(); - } - - /** - * Move the internal pointer to the end of the list - * And get the last element in the collection - * - * @return mixed - */ - public function getLast() - { - $count = $this->count(); - if ($count == 0) { - return null; - } else { - $this->getInternalIterator()->seek($count - 1); - return $this->getCurrent(); - } - } - - /** - * Check whether the internal pointer is at the end of the list - * - * @return boolean - */ - public function isLast() - { - $count = $this->count(); - if ($count == 0) { - // empty list... so yes, this is the last - return true; - } else { - return $this->getPosition() == $count - 1; - } - } - - /** - * Check if the collection is empty - * - * @return boolean - */ - public function isEmpty() - { - return $this->count() == 0; - } - - /** - * Check if the current index is an odd integer - * - * @return boolean - */ - public function isOdd() - { - return (boolean) ($this->getInternalIterator()->key() % 2); - } - - /** - * Check if the current index is an even integer - * - * @return boolean - */ - public function isEven() - { - return !$this->isOdd(); - } - - /** - * Get an element from its key - * Alias for ArrayObject::offsetGet() - * - * @param mixed $key - * - * @return mixed The element - */ - public function get($key) - { - if (!$this->offsetExists($key)) { - throw new PropelException('Unknown key ' . $key); - } - return $this->offsetGet($key); - } - - /** - * Pops an element off the end of the collection - * - * @return mixed The popped element - */ - public function pop() - { - if ($this->count() == 0) { - return null; - } - $ret = $this->getLast(); - $lastKey = $this->getInternalIterator()->key(); - $this->offsetUnset((string) $lastKey); - return $ret; - } - - /** - * Pops an element off the beginning of the collection - * - * @return mixed The popped element - */ - public function shift() - { - // the reindexing is complicated to deal with through the iterator - // so let's use the simple solution - $arr = $this->getArrayCopy(); - $ret = array_shift($arr); - $this->exchangeArray($arr); - - return $ret; - } - - /** - * Prepend one or more elements to the beginning of the collection - * - * @param mixed $value the element to prepend - * - * @return int The number of new elements in the array - */ - public function prepend($value) - { - // the reindexing is complicated to deal with through the iterator - // so let's use the simple solution - $arr = $this->getArrayCopy(); - $ret = array_unshift($arr, $value); - $this->exchangeArray($arr); - - return $ret; - } - - /** - * Add an element to the collection with the given key - * Alias for ArrayObject::offsetSet() - * - * @param mixed $key - * @param mixed $value - */ - public function set($key, $value) - { - return $this->offsetSet($key, $value); - } - - /** - * Removes a specified collection element - * Alias for ArrayObject::offsetUnset() - * - * @param mixed $key - * - * @return mixed The removed element - */ - public function remove($key) - { - if (!$this->offsetExists($key)) { - throw new PropelException('Unknown key ' . $key); - } - return $this->offsetUnset($key); - } - - /** - * Clears the collection - * - * @return array The previous collection - */ - public function clear() - { - return $this->exchangeArray(array()); - } - - /** - * Whether or not this collection contains a specified element - * - * @param mixed $element the element - * - * @return boolean - */ - public function contains($element) - { - return in_array($element, $this->getArrayCopy(), true); - } - - /** - * Search an element in the collection - * - * @param mixed $element - * - * @return mixed Returns the key for the element if it is found in the collection, FALSE otherwise - */ - public function search($element) - { - return array_search($element, $this->getArrayCopy(), true); - } - - // Serializable interface - - public function serialize() - { - $repr = array( - 'data' => $this->getArrayCopy(), - 'model' => $this->model, - ); - return serialize($repr); - } - - public function unserialize($data) - { - $repr = unserialize($data); - $this->exchangeArray($repr['data']); - $this->model = $repr['model']; - } - - // IteratorAggregate method - - /** - * Overrides ArrayObject::getIterator() to save the iterator object - * for internal use e.g. getNext(), isOdd(), etc. - */ - public function getIterator() - { - $this->iterator = new ArrayIterator($this); - return $this->iterator; - } - - public function getInternalIterator() - { - if (null === $this->iterator) { - return $this->getIterator(); - } - return $this->iterator; - } - - // Propel collection methods - - /** - * Set the model of the elements in the collection - * - * @param string $model Name of the Propel object classes stored in the collection - */ - public function setModel($model) - { - $this->model = $model; - } - - /** - * Get the model of the elements in the collection - * - * @return string Name of the Propel object class stored in the collection - */ - public function getModel() - { - return $this->model; - } - - /** - * Get the peer class of the elements in the collection - * - * @return string Name of the Propel peer class stored in the collection - */ - public function getPeerClass() - { - if ($this->model == '') { - throw new PropelException('You must set the collection model before interacting with it'); - } - return constant($this->getModel() . '::PEER'); - } - - public function setFormatter(PropelFormatter $formatter) - { - $this->formatter = $formatter; - } - - public function getFormatter() - { - return $this->formatter; - } - - /** - * Get a connection object for the database containing the elements of the collection - * - * @param string $type The connection type (Propel::CONNECTION_READ by default; can be Propel::connection_WRITE) - * - * @return PropelPDO a connection object - */ - public function getConnection($type = Propel::CONNECTION_READ) - { - $databaseName = constant($this->getPeerClass() . '::DATABASE_NAME'); - - return Propel::getConnection($databaseName, $type); - } - -} - -?> \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/collection/PropelObjectCollection.php b/airtime_mvc/library/propel/runtime/lib/collection/PropelObjectCollection.php deleted file mode 100644 index 37061affa..000000000 --- a/airtime_mvc/library/propel/runtime/lib/collection/PropelObjectCollection.php +++ /dev/null @@ -1,249 +0,0 @@ -getConnection(Propel::CONNECTION_WRITE); - } - $con->beginTransaction(); - try { - foreach ($this as $element) { - $element->save($con); - } - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - throw $e; - } - } - - /** - * Delete all the elements in the collection - */ - public function delete($con = null) - { - if (null === $con) { - $con = $this->getConnection(Propel::CONNECTION_WRITE); - } - $con->beginTransaction(); - try { - foreach ($this as $element) { - $element->delete($con); - } - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - throw $e; - } - } - - /** - * Get an array of the primary keys of all the objects in the collection - * - * @return array The list of the primary keys of the collection - */ - public function getPrimaryKeys($usePrefix = true) - { - $ret = array(); - foreach ($this as $key => $obj) { - $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; - $ret[$key]= $obj->getPrimaryKey(); - } - - return $ret; - } - - /** - * Populates the collection from an array - * Each object is populated from an array and the result is stored - * Does not empty the collection before adding the data from the array - * - * @param array $arr - */ - public function fromArray($arr) - { - $class = $this->getModel(); - foreach ($arr as $element) { - $obj = new $class(); - $obj->fromArray($element); - $this->append($obj); - } - } - - /** - * Get an array representation of the collection - * Each object is turned into an array and the result is returned - * - * @param string $keyColumn If null, the returned array uses an incremental index. - * Otherwise, the array is indexed using the specified column - * @param boolean $usePrefix If true, the returned array prefixes keys - * with the model class name ('Article_0', 'Article_1', etc). - * - * - * $bookCollection->toArray(); - * array( - * 0 => array('Id' => 123, 'Title' => 'War And Peace'), - * 1 => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * $bookCollection->toArray('Id'); - * array( - * 123 => array('Id' => 123, 'Title' => 'War And Peace'), - * 456 => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * $bookCollection->toArray(null, true); - * array( - * 'Book_0' => array('Id' => 123, 'Title' => 'War And Peace'), - * 'Book_1' => array('Id' => 456, 'Title' => 'Don Juan'), - * ) - * - * @return array - */ - public function toArray($keyColumn = null, $usePrefix = false) - { - $ret = array(); - $keyGetterMethod = 'get' . $keyColumn; - foreach ($this as $key => $obj) { - $key = null === $keyColumn ? $key : $obj->$keyGetterMethod(); - $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; - $ret[$key] = $obj->toArray(); - } - - return $ret; - } - - /** - * Get an array representation of the collection - * - * @param string $keyColumn If null, the returned array uses an incremental index. - * Otherwise, the array is indexed using the specified column - * @param boolean $usePrefix If true, the returned array prefixes keys - * with the model class name ('Article_0', 'Article_1', etc). - * - * - * $bookCollection->getArrayCopy(); - * array( - * 0 => $book0, - * 1 => $book1, - * ) - * $bookCollection->getArrayCopy('Id'); - * array( - * 123 => $book0, - * 456 => $book1, - * ) - * $bookCollection->getArrayCopy(null, true); - * array( - * 'Book_0' => $book0, - * 'Book_1' => $book1, - * ) - * - * @return array - */ - public function getArrayCopy($keyColumn = null, $usePrefix = false) - { - if (null === $keyColumn && false === $usePrefix) { - return parent::getArrayCopy(); - } - $ret = array(); - $keyGetterMethod = 'get' . $keyColumn; - foreach ($this as $key => $obj) { - $key = null === $keyColumn ? $key : $obj->$keyGetterMethod(); - $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; - $ret[$key] = $obj; - } - - return $ret; - } - - /** - * Get an associative array representation of the collection - * The first parameter specifies the column to be used for the key, - * And the seconf for the value. - * - * $res = $coll->toKeyValue('Id', 'Name'); - * - * - * @return array - */ - public function toKeyValue($keyColumn = 'PrimaryKey', $valueColumn = null) - { - $ret = array(); - $keyGetterMethod = 'get' . $keyColumn; - $valueGetterMethod = (null === $valueColumn) ? '__toString' : ('get' . $valueColumn); - foreach ($this as $obj) { - $ret[$obj->$keyGetterMethod()] = $obj->$valueGetterMethod(); - } - - return $ret; - } - - /** - * Makes an additional query to populate the objects related to the collection objects - * by a certain relation - * - * @param string $relation Relation name (e.g. 'Book') - * @param Criteria $criteria Optional Criteria object to filter the related object collection - * @param PropelPDO $con Optional connection object - * - * @return PropelObjectCollection the list of related objects - */ - public function populateRelation($relation, $criteria = null, $con = null) - { - if (!Propel::isInstancePoolingEnabled()) { - throw new PropelException('populateRelation() needs instance pooling to be enabled prior to populating the collection'); - } - $relationMap = $this->getFormatter()->getTableMap()->getRelation($relation); - $symRelationMap = $relationMap->getSymmetricalRelation(); - - // query the db for the related objects - $useMethod = 'use' . $symRelationMap->getName() . 'Query'; - $query = PropelQuery::from($relationMap->getRightTable()->getPhpName()); - if (null !== $criteria) { - $query->mergeWith($criteria); - } - $relatedObjects = $query - ->$useMethod() - ->filterByPrimaryKeys($this->getPrimaryKeys()) - ->endUse() - ->find($con); - - // associate the related objects to the main objects - if ($relationMap->getType() == RelationMap::ONE_TO_MANY) { - $getMethod = 'get' . $symRelationMap->getName(); - $addMethod = 'add' . $relationMap->getName(); - foreach ($relatedObjects as $object) { - $mainObj = $object->$getMethod(); // instance pool is used here to avoid a query - $mainObj->$addMethod($object); - } - } elseif ($relationMap->getType() == RelationMap::MANY_TO_ONE) { - // nothing to do; the instance pool will catch all calls to getRelatedObject() - // and return the object in memory - } else { - throw new PropelException('populateRelation() does not support this relation type'); - } - - return $relatedObjects; - } - -} - -?> \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandCollection.php b/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandCollection.php deleted file mode 100644 index 409aef32f..000000000 --- a/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandCollection.php +++ /dev/null @@ -1,151 +0,0 @@ -iterator = new PropelOnDemandIterator($formatter, $stmt); - } - - // IteratorAggregate Interface - - public function getIterator() - { - return $this->iterator; - } - - // ArrayAccess Interface - - public function offsetExists($offset) - { - if ($offset == $this->currentKey) { - return true; - } - throw new PropelException('The On Demand Collection does not allow acces by offset'); - } - - public function offsetGet($offset) - { - if ($offset == $this->currentKey) { - return $this->currentRow; - } - throw new PropelException('The On Demand Collection does not allow acces by offset'); - } - - public function offsetSet($offset, $value) - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function offsetUnset($offset) - { - throw new PropelException('The On Demand Collection is read only'); - } - - // Serializable Interface - - public function serialize() - { - throw new PropelException('The On Demand Collection cannot be serialized'); - } - - public function unserialize($data) - { - throw new PropelException('The On Demand Collection cannot be serialized'); - } - - // Countable Interface - - /** - * Returns the number of rows in the resultset - * Warning: this number is inaccurate for most databases. Do not rely on it for a portable application. - * - * @return int number of results - */ - public function count() - { - return $this->iterator->count(); - } - - // ArrayObject methods - - public function append($value) - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function prepend($value) - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function asort() - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function exchangeArray($input) - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function getArrayCopy() - { - throw new PropelException('The On Demand Collection does not allow acces by offset'); - } - - public function getFlags() - { - throw new PropelException('The On Demand Collection does not allow acces by offset'); - } - - public function ksort() - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function natcasesort() - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function natsort() - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function setFlags($flags) - { - throw new PropelException('The On Demand Collection does not allow acces by offset'); - } - - public function uasort($cmp_function) - { - throw new PropelException('The On Demand Collection is read only'); - } - - public function uksort($cmp_function) - { - throw new PropelException('The On Demand Collection is read only'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandIterator.php b/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandIterator.php deleted file mode 100644 index e814781b5..000000000 --- a/airtime_mvc/library/propel/runtime/lib/collection/PropelOnDemandIterator.php +++ /dev/null @@ -1,118 +0,0 @@ -formatter = $formatter; - $this->stmt = $stmt; - $this->enableInstancePoolingOnFinish = Propel::disableInstancePooling(); - } - - public function closeCursor() - { - $this->stmt->closeCursor(); - } - - /** - * Returns the number of rows in the resultset - * Warning: this number is inaccurate for most databases. Do not rely on it for a portable application. - * - * @return int number of results - */ - public function count() - { - return $this->stmt->rowCount(); - } - - // Iterator Interface - - /** - * Gets the current Model object in the collection - * This is where the hydration takes place. - * - * @see PropelObjectFormatter::getAllObjectsFromRow() - * - * @return BaseObject - */ - public function current() - { - return $this->formatter->getAllObjectsFromRow($this->currentRow); - } - - /** - * Gets the current key in the iterator - * - * @return string - */ - public function key() - { - return $this->currentKey; - } - - /** - * Advances the curesor in the statement - * Closes the cursor if the end of the statement is reached - */ - public function next() - { - $this->currentRow = $this->stmt->fetch(PDO::FETCH_NUM); - $this->currentKey++; - $this->isValid = (boolean) $this->currentRow; - if (!$this->isValid) { - $this->closeCursor(); - if ($this->enableInstancePoolingOnFinish) { - Propel::enableInstancePooling(); - } - } - } - - /** - * Initializes the iterator by advancing to the first position - * This method can only be called once (this is a NoRewindIterator) - */ - public function rewind() - { - // check that the hydration can begin - if (null === $this->formatter) { - throw new PropelException('The On Demand collection requires a formatter. Add it by calling setFormatter()'); - } - if (null === $this->stmt) { - throw new PropelException('The On Demand collection requires a statement. Add it by calling setStatement()'); - } - if (null !== $this->isValid) { - throw new PropelException('The On Demand collection can only be iterated once'); - } - - // initialize the current row and key - $this->next(); - } - - public function valid() - { - return $this->isValid; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/config/PropelConfiguration.php b/airtime_mvc/library/propel/runtime/lib/config/PropelConfiguration.php deleted file mode 100644 index 299677f29..000000000 --- a/airtime_mvc/library/propel/runtime/lib/config/PropelConfiguration.php +++ /dev/null @@ -1,159 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.config - */ -class PropelConfiguration implements ArrayAccess -{ - const TYPE_ARRAY = 1; - - const TYPE_ARRAY_FLAT = 2; - - const TYPE_OBJECT = 3; - - /** - * @var array An array of parameters - */ - protected $parameters = array(); - - /** - * Construct a new configuration container - * - * @param array $parameters - */ - public function __construct(array $parameters = array()) - { - $this->parameters = $parameters; - } - - /** - * @see http://www.php.net/ArrayAccess - */ - public function offsetExists($offset) - { - return array_key_exists($offset, $this->parameters); - } - - /** - * @see http://www.php.net/ArrayAccess - */ - public function offsetSet($offset, $value) - { - $this->parameter[$offset] = $value; - } - - /** - * @see http://www.php.net/ArrayAccess - */ - public function offsetGet($offset) - { - return $this->parameters[$offset]; - } - - /** - * @see http://www.php.net/ArrayAccess - */ - public function offsetUnset($offset) - { - unset($this->parameters[$offset]); - } - - /** - * Get parameter value from the container - * - * @param string $name Parameter name - * @param mixed $default Default value to be used if the - * requested value is not found - * @return mixed Parameter value or the default - */ - public function getParameter($name, $default = null) - { - $ret = $this->parameters; - $parts = explode('.', $name); //name.space.name - while ($part = array_shift($parts)) { - if (isset($ret[$part])) { - $ret = $ret[$part]; - } else { - return $default; - } - } - return $ret; - } - - /** - * Store a value to the container - * - * @param string $name Configuration item name (name.space.name) - * @param mixed $value Value to be stored - */ - public function setParameter($name, $value) - { - $param = &$this->parameters; - $parts = explode('.', $name); //name.space.name - while ($part = array_shift($parts)) { - $param = &$param[$part]; - } - $param = $value; - } - - /** - * - * - * @param int $type - * @return mixed - */ - public function getParameters($type = PropelConfiguration::TYPE_ARRAY) - { - switch ($type) { - case PropelConfiguration::TYPE_ARRAY: - return $this->parameters; - case PropelConfiguration::TYPE_ARRAY_FLAT: - return $this->toFlatArray(); - case PropelConfiguration::TYPE_OBJECT: - return $this; - default: - throw new PropelException('Unknown configuration type: '. var_export($type, true)); - } - - } - - - /** - * Get the configuration as a flat array. ($array['name.space.item'] = 'value') - * - * @return array - */ - protected function toFlatArray() - { - $result = array(); - $it = new PropelConfigurationIterator(new RecursiveArrayIterator($this->parameters), RecursiveIteratorIterator::SELF_FIRST); - foreach($it as $key => $value) { - $ns = $it->getDepth() ? $it->getNamespace() . '.'. $key : $key; - if ($it->getNodeType() == PropelConfigurationIterator::NODE_ITEM) { - $result[$ns] = $value; - } - } - - return $result; - } - -} - -?> diff --git a/airtime_mvc/library/propel/runtime/lib/config/PropelConfigurationIterator.php b/airtime_mvc/library/propel/runtime/lib/config/PropelConfigurationIterator.php deleted file mode 100644 index 45552d9db..000000000 --- a/airtime_mvc/library/propel/runtime/lib/config/PropelConfigurationIterator.php +++ /dev/null @@ -1,103 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.config - */ -class PropelConfigurationIterator extends RecursiveIteratorIterator -{ - /** - * Node is a parent node - */ - const NODE_PARENT = 0; - - /** - * Node is an actual configuration item - */ - const NODE_ITEM = 1; - - /** - * Namespace stack when recursively iterating the configuration tree - * - * @var array - */ - protected $namespaceStack = array(); - - /** - * Current node type. Possible values: null (undefined), self::NODE_PARENT or self::NODE_ITEM - * - * @var int - */ - protected $nodeType = null; - - /** - * Get current namespace - * - * @return string - */ - public function getNamespace() - { - return implode('.', $this->namespaceStack); - } - - /** - * Get current node type. - * - * @see http://www.php.net/RecursiveIteratorIterator - * @return int - * - null (undefined) - * - self::NODE_PARENT - * - self::NODE_ITEM - */ - public function getNodeType() - { - return $this->nodeType; - } - - /** - * Get the current element - * - * @see http://www.php.net/RecursiveIteratorIterator - * @return mixed - */ - public function current() - { - $current = parent::current(); - if (is_array($current)) { - $this->namespaceStack[] = $this->key(); - $this->nodeType = self::NODE_PARENT; - } - else { - $this->nodeType = self::NODE_ITEM; - } - - return $current; - } - - /** - * Called after current child iterator is invalid and right before it gets destructed. - * - * @see http://www.php.net/RecursiveIteratorIterator - */ - public function endChildren() - { - if ($this->namespaceStack) { - array_pop($this->namespaceStack); - } - } - -} - -?> diff --git a/airtime_mvc/library/propel/runtime/lib/connection/DebugPDO.php b/airtime_mvc/library/propel/runtime/lib/connection/DebugPDO.php deleted file mode 100644 index e9dd0759a..000000000 --- a/airtime_mvc/library/propel/runtime/lib/connection/DebugPDO.php +++ /dev/null @@ -1,111 +0,0 @@ -setParameter('debugpdo.logging.details.slow.enabled', true); - * $config->setParameter('debugpdo.logging.details.slow.threshold', 1.5); - * $config->setParameter('debugpdo.logging.details.time.enabled', true); - * - * @author Francois Zaninotto - * @author Cameron Brunner - * @author Hans Lellelid - * @author Christian Abegg - * @author Jarno Rantanen - * @since 2006-09-22 - * @package propel.runtime.connection - */ -class DebugPDO extends PropelPDO -{ - public $useDebug = true; -} diff --git a/airtime_mvc/library/propel/runtime/lib/connection/DebugPDOStatement.php b/airtime_mvc/library/propel/runtime/lib/connection/DebugPDOStatement.php deleted file mode 100644 index f1b2243e1..000000000 --- a/airtime_mvc/library/propel/runtime/lib/connection/DebugPDOStatement.php +++ /dev/null @@ -1,122 +0,0 @@ - - * @author Jarno Rantanen - * @since 2007-07-12 - * @package propel.runtime.connection - */ -class DebugPDOStatement extends PDOStatement -{ - - /** - * The PDO connection from which this instance was created. - * - * @var PropelPDO - */ - protected $pdo; - - /** - * Hashmap for resolving the PDO::PARAM_* class constants to their human-readable names. - * - * This is only used in logging the binding of variables. - * - * @see self::bindValue() - * @var array - */ - protected static $typeMap = array( - PDO::PARAM_BOOL => "PDO::PARAM_BOOL", - PDO::PARAM_INT => "PDO::PARAM_INT", - PDO::PARAM_STR => "PDO::PARAM_STR", - PDO::PARAM_LOB => "PDO::PARAM_LOB", - PDO::PARAM_NULL => "PDO::PARAM_NULL", - ); - - /** - * @var array The values that have been bound - */ - protected $boundValues = array(); - - /** - * Construct a new statement class with reference to main DebugPDO object from - * which this instance was created. - * - * @param DebugPDO $pdo Reference to the parent PDO instance. - */ - protected function __construct(PropelPDO $pdo) - { - $this->pdo = $pdo; - } - - public function getExecutedQueryString() - { - $sql = $this->queryString; - $matches = array(); - if (preg_match_all('/(:p[0-9]+\b)/', $sql, $matches)) { - $size = count($matches[1]); - for ($i = $size-1; $i >= 0; $i--) { - $pos = $matches[1][$i]; - $sql = str_replace($pos, $this->boundValues[$pos], $sql); - } - } - - return $sql; - } - - /** - * Executes a prepared statement. Returns a boolean value indicating success. - * - * Overridden for query counting and logging. - * - * @return bool - */ - public function execute($input_parameters = null) - { - $debug = $this->pdo->getDebugSnapshot(); - $return = parent::execute($input_parameters); - - $sql = $this->getExecutedQueryString(); - $this->pdo->log($sql, null, __METHOD__, $debug); - $this->pdo->setLastExecutedQuery($sql); - $this->pdo->incrementQueryCount(); - - return $return; - } - - /** - * Binds a value to a corresponding named or question mark placeholder in the SQL statement - * that was use to prepare the statement. Returns a boolean value indicating success. - * - * @param int $pos Parameter identifier (for determining what to replace in the query). - * @param mixed $value The value to bind to the parameter. - * @param int $type Explicit data type for the parameter using the PDO::PARAM_* constants. Defaults to PDO::PARAM_STR. - * @return boolean - */ - public function bindValue($pos, $value, $type = PDO::PARAM_STR) - { - $debug = $this->pdo->getDebugSnapshot(); - $typestr = isset(self::$typeMap[$type]) ? self::$typeMap[$type] : '(default)'; - $return = parent::bindValue($pos, $value, $type); - $valuestr = $type == PDO::PARAM_LOB ? '[LOB value]' : var_export($value, true); - $msg = "Binding $valuestr at position $pos w/ PDO type $typestr"; - - $this->boundValues[$pos] = $valuestr; - - $this->pdo->log($msg, null, __METHOD__, $debug); - - return $return; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/connection/PropelPDO.php b/airtime_mvc/library/propel/runtime/lib/connection/PropelPDO.php deleted file mode 100644 index 6bfa5a07b..000000000 --- a/airtime_mvc/library/propel/runtime/lib/connection/PropelPDO.php +++ /dev/null @@ -1,716 +0,0 @@ - - * @author Hans Lellelid - * @author Christian Abegg - * @since 2006-09-22 - * @package propel.runtime.connection - */ -class PropelPDO extends PDO -{ - - /** - * Attribute to use to set whether to cache prepared statements. - */ - const PROPEL_ATTR_CACHE_PREPARES = -1; - - const DEFAULT_SLOW_THRESHOLD = 0.1; - const DEFAULT_ONLYSLOW_ENABLED = false; - - /** - * The current transaction depth. - * @var int - */ - protected $nestedTransactionCount = 0; - - /** - * Cache of prepared statements (PDOStatement) keyed by md5 of SQL. - * - * @var array [md5(sql) => PDOStatement] - */ - protected $preparedStatements = array(); - - /** - * Whether to cache prepared statements. - * - * @var boolean - */ - protected $cachePreparedStatements = false; - - /** - * Whether the final commit is possible - * Is false if a nested transaction is rolled back - */ - protected $isUncommitable = false; - - /** - * Count of queries performed. - * - * @var int - */ - protected $queryCount = 0; - - /** - * SQL code of the latest performed query. - * - * @var string - */ - protected $lastExecutedQuery; - - /** - * Whether or not the debug is enabled - * - * @var boolean - */ - public $useDebug = false; - - /** - * Configured BasicLogger (or compatible) logger. - * - * @var BasicLogger - */ - protected $logger; - - /** - * The log level to use for logging. - * - * @var int - */ - private $logLevel = Propel::LOG_DEBUG; - - /** - * The default value for runtime config item "debugpdo.logging.methods". - * - * @var array - */ - protected static $defaultLogMethods = array( - 'PropelPDO::exec', - 'PropelPDO::query', - 'DebugPDOStatement::execute', - ); - - /** - * Creates a PropelPDO instance representing a connection to a database. - *. - * If so configured, specifies a custom PDOStatement class and makes an entry - * to the log with the state of this object just after its initialization. - * Add PropelPDO::__construct to $defaultLogMethods to see this message - * - * @param string $dsn Connection DSN. - * @param string $username (optional) The user name for the DSN string. - * @param string $password (optional) The password for the DSN string. - * @param array $driver_options (optional) A key=>value array of driver-specific connection options. - * @throws PDOException if there is an error during connection initialization. - */ - public function __construct($dsn, $username = null, $password = null, $driver_options = array()) - { - if ($this->useDebug) { - $debug = $this->getDebugSnapshot(); - } - - parent::__construct($dsn, $username, $password, $driver_options); - - if ($this->useDebug) { - $this->configureStatementClass('DebugPDOStatement', $suppress = true); - $this->log('Opening connection', null, __METHOD__, $debug); - } - } - - /** - * Gets the current transaction depth. - * @return int - */ - public function getNestedTransactionCount() - { - return $this->nestedTransactionCount; - } - - /** - * Set the current transaction depth. - * @param int $v The new depth. - */ - protected function setNestedTransactionCount($v) - { - $this->nestedTransactionCount = $v; - } - - /** - * Is this PDO connection currently in-transaction? - * This is equivalent to asking whether the current nested transaction count - * is greater than 0. - * @return boolean - */ - public function isInTransaction() - { - return ($this->getNestedTransactionCount() > 0); - } - - /** - * Check whether the connection contains a transaction that can be committed. - * To be used in an evironment where Propelexceptions are caught. - * - * @return boolean True if the connection is in a committable transaction - */ - public function isCommitable() - { - return $this->isInTransaction() && !$this->isUncommitable; - } - - /** - * Overrides PDO::beginTransaction() to prevent errors due to already-in-progress transaction. - */ - public function beginTransaction() - { - $return = true; - if (!$this->nestedTransactionCount) { - $return = parent::beginTransaction(); - if ($this->useDebug) { - $this->log('Begin transaction', null, __METHOD__); - } - $this->isUncommitable = false; - } - $this->nestedTransactionCount++; - return $return; - } - - /** - * Overrides PDO::commit() to only commit the transaction if we are in the outermost - * transaction nesting level. - */ - public function commit() - { - $return = true; - $opcount = $this->nestedTransactionCount; - if ($opcount > 0) { - if ($opcount === 1) { - if ($this->isUncommitable) { - throw new PropelException('Cannot commit because a nested transaction was rolled back'); - } else { - $return = parent::commit(); - if ($this->useDebug) { - $this->log('Commit transaction', null, __METHOD__); - } - } - } - $this->nestedTransactionCount--; - } - return $return; - } - - /** - * Overrides PDO::rollBack() to only rollback the transaction if we are in the outermost - * transaction nesting level - * @return boolean Whether operation was successful. - */ - public function rollBack() - { - $return = true; - $opcount = $this->nestedTransactionCount; - if ($opcount > 0) { - if ($opcount === 1) { - $return = parent::rollBack(); - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } else { - $this->isUncommitable = true; - } - $this->nestedTransactionCount--; - } - return $return; - } - - /** - * Rollback the whole transaction, even if this is a nested rollback - * and reset the nested transaction count to 0. - * @return boolean Whether operation was successful. - */ - public function forceRollBack() - { - $return = true; - if ($this->nestedTransactionCount) { - // If we're in a transaction, always roll it back - // regardless of nesting level. - $return = parent::rollBack(); - - // reset nested transaction count to 0 so that we don't - // try to commit (or rollback) the transaction outside this scope. - $this->nestedTransactionCount = 0; - - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } - return $return; - } - - /** - * Sets a connection attribute. - * - * This is overridden here to provide support for setting Propel-specific attributes - * too. - * - * @param int $attribute The attribute to set (e.g. PropelPDO::PROPEL_ATTR_CACHE_PREPARES). - * @param mixed $value The attribute value. - */ - public function setAttribute($attribute, $value) - { - switch($attribute) { - case self::PROPEL_ATTR_CACHE_PREPARES: - $this->cachePreparedStatements = $value; - break; - default: - parent::setAttribute($attribute, $value); - } - } - - /** - * Gets a connection attribute. - * - * This is overridden here to provide support for setting Propel-specific attributes - * too. - * - * @param int $attribute The attribute to get (e.g. PropelPDO::PROPEL_ATTR_CACHE_PREPARES). - */ - public function getAttribute($attribute) - { - switch($attribute) { - case self::PROPEL_ATTR_CACHE_PREPARES: - return $this->cachePreparedStatements; - break; - default: - return parent::getAttribute($attribute); - } - } - - /** - * Prepares a statement for execution and returns a statement object. - * - * Overrides PDO::prepare() in order to: - * - Add logging and query counting if logging is true. - * - Add query caching support if the PropelPDO::PROPEL_ATTR_CACHE_PREPARES was set to true. - * - * @param string $sql This must be a valid SQL statement for the target database server. - * @param array One or more key => value pairs to set attribute values - * for the PDOStatement object that this method returns. - * @return PDOStatement - */ - public function prepare($sql, $driver_options = array()) - { - if ($this->useDebug) { - $debug = $this->getDebugSnapshot(); - } - - if ($this->cachePreparedStatements) { - if (!isset($this->preparedStatements[$sql])) { - $return = parent::prepare($sql, $driver_options); - $this->preparedStatements[$sql] = $return; - } else { - $return = $this->preparedStatements[$sql]; - } - } else { - $return = parent::prepare($sql, $driver_options); - } - - if ($this->useDebug) { - $this->log($sql, null, __METHOD__, $debug); - } - - return $return; - } - - /** - * Execute an SQL statement and return the number of affected rows. - * - * Overrides PDO::exec() to log queries when required - * - * @return int - */ - public function exec($sql) - { - if ($this->useDebug) { - $debug = $this->getDebugSnapshot(); - } - - $return = parent::exec($sql); - - if ($this->useDebug) { - $this->log($sql, null, __METHOD__, $debug); - $this->setLastExecutedQuery($sql); - $this->incrementQueryCount(); - } - - return $return; - } - - /** - * Executes an SQL statement, returning a result set as a PDOStatement object. - * Despite its signature here, this method takes a variety of parameters. - * - * Overrides PDO::query() to log queries when required - * - * @see http://php.net/manual/en/pdo.query.php for a description of the possible parameters. - * @return PDOStatement - */ - public function query() - { - if ($this->useDebug) { - $debug = $this->getDebugSnapshot(); - } - - $args = func_get_args(); - if (version_compare(PHP_VERSION, '5.3', '<')) { - $return = call_user_func_array(array($this, 'parent::query'), $args); - } else { - $return = call_user_func_array('parent::query', $args); - } - - if ($this->useDebug) { - $sql = $args[0]; - $this->log($sql, null, __METHOD__, $debug); - $this->setLastExecutedQuery($sql); - $this->incrementQueryCount(); - } - - return $return; - } - - /** - * Clears any stored prepared statements for this connection. - */ - public function clearStatementCache() - { - $this->preparedStatements = array(); - } - - /** - * Configures the PDOStatement class for this connection. - * - * @param boolean $suppressError Whether to suppress an exception if the statement class cannot be set. - * @throws PropelException if the statement class cannot be set (and $suppressError is false). - */ - protected function configureStatementClass($class = 'PDOStatement', $suppressError = true) - { - // extending PDOStatement is only supported with non-persistent connections - if (!$this->getAttribute(PDO::ATTR_PERSISTENT)) { - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($class, array($this))); - } elseif (!$suppressError) { - throw new PropelException('Extending PDOStatement is not supported with persistent connections.'); - } - } - - /** - * Returns the number of queries this DebugPDO instance has performed on the database connection. - * - * When using DebugPDOStatement as the statement class, any queries by DebugPDOStatement instances - * are counted as well. - * - * @return int - * @throws PropelException if persistent connection is used (since unable to override PDOStatement in that case). - */ - public function getQueryCount() - { - // extending PDOStatement is not supported with persistent connections - if ($this->getAttribute(PDO::ATTR_PERSISTENT)) { - throw new PropelException('Extending PDOStatement is not supported with persistent connections. Count would be inaccurate, because we cannot count the PDOStatment::execute() calls. Either don\'t use persistent connections or don\'t call PropelPDO::getQueryCount()'); - } - return $this->queryCount; - } - - /** - * Increments the number of queries performed by this DebugPDO instance. - * - * Returns the original number of queries (ie the value of $this->queryCount before calling this method). - * - * @return int - */ - public function incrementQueryCount() - { - $this->queryCount++; - } - - /** - * Get the SQL code for the latest query executed by Propel - * - * @return string Executable SQL code - */ - public function getLastExecutedQuery() - { - return $this->lastExecutedQuery; - } - - /** - * Set the SQL code for the latest query executed by Propel - * - * @param string $query Executable SQL code - */ - public function setLastExecutedQuery($query) - { - $this->lastExecutedQuery = $query; - } - - /** - * Enable or disable the query debug features - * - * @var boolean $value True to enable debug (default), false to disable it - */ - public function useDebug($value = true) - { - if ($value) { - $this->configureStatementClass('DebugPDOStatement', $suppress = true); - } else { - // reset query logging - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement')); - $this->setLastExecutedQuery(''); - $this->queryCount = 0; - } - $this->clearStatementCache(); - $this->useDebug = $value; - } - - /** - * Sets the logging level to use for logging method calls and SQL statements. - * - * @param int $level Value of one of the Propel::LOG_* class constants. - */ - public function setLogLevel($level) - { - $this->logLevel = $level; - } - - /** - * Sets a logger to use. - * - * The logger will be used by this class to log various method calls and their properties. - * - * @param BasicLogger $logger A Logger with an API compatible with BasicLogger (or PEAR Log). - */ - public function setLogger($logger) - { - $this->logger = $logger; - } - - /** - * Gets the logger in use. - * - * @return BasicLogger $logger A Logger with an API compatible with BasicLogger (or PEAR Log). - */ - public function getLogger() - { - return $this->logger; - } - - /** - * Logs the method call or SQL using the Propel::log() method or a registered logger class. - * - * @uses self::getLogPrefix() - * @see self::setLogger() - * - * @param string $msg Message to log. - * @param int $level (optional) Log level to use; will use self::setLogLevel() specified level by default. - * @param string $methodName (optional) Name of the method whose execution is being logged. - * @param array $debugSnapshot (optional) Previous return value from self::getDebugSnapshot(). - */ - public function log($msg, $level = null, $methodName = null, array $debugSnapshot = null) - { - // If logging has been specifically disabled, this method won't do anything - if (!$this->getLoggingConfig('enabled', true)) { - return; - } - - // If the method being logged isn't one of the ones to be logged, bail - if (!in_array($methodName, $this->getLoggingConfig('methods', self::$defaultLogMethods))) { - return; - } - - // If a logging level wasn't provided, use the default one - if ($level === null) { - $level = $this->logLevel; - } - - // Determine if this query is slow enough to warrant logging - if ($this->getLoggingConfig("onlyslow", self::DEFAULT_ONLYSLOW_ENABLED)) { - $now = $this->getDebugSnapshot(); - if ($now['microtime'] - $debugSnapshot['microtime'] < $this->getLoggingConfig("details.slow.threshold", self::DEFAULT_SLOW_THRESHOLD)) return; - } - - // If the necessary additional parameters were given, get the debug log prefix for the log line - if ($methodName && $debugSnapshot) { - $msg = $this->getLogPrefix($methodName, $debugSnapshot) . $msg; - } - - // We won't log empty messages - if (!$msg) { - return; - } - - // Delegate the actual logging forward - if ($this->logger) { - $this->logger->log($msg, $level); - } else { - Propel::log($msg, $level); - } - } - - /** - * Returns a snapshot of the current values of some functions useful in debugging. - * - * @return array - */ - public function getDebugSnapshot() - { - if ($this->useDebug) { - return array( - 'microtime' => microtime(true), - 'memory_get_usage' => memory_get_usage($this->getLoggingConfig('realmemoryusage', false)), - 'memory_get_peak_usage' => memory_get_peak_usage($this->getLoggingConfig('realmemoryusage', false)), - ); - } else { - throw new PropelException('Should not get debug snapshot when not debugging'); - } - } - - /** - * Returns a named configuration item from the Propel runtime configuration, from under the - * 'debugpdo.logging' prefix. If such a configuration setting hasn't been set, the given default - * value will be returned. - * - * @param string $key Key for which to return the value. - * @param mixed $defaultValue Default value to apply if config item hasn't been set. - * @return mixed - */ - protected function getLoggingConfig($key, $defaultValue) - { - return Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->getParameter("debugpdo.logging.$key", $defaultValue); - } - - /** - * Returns a prefix that may be prepended to a log line, containing debug information according - * to the current configuration. - * - * Uses a given $debugSnapshot to calculate how much time has passed since the call to self::getDebugSnapshot(), - * how much the memory consumption by PHP has changed etc. - * - * @see self::getDebugSnapshot() - * - * @param string $methodName Name of the method whose execution is being logged. - * @param array $debugSnapshot A previous return value from self::getDebugSnapshot(). - * @return string - */ - protected function getLogPrefix($methodName, $debugSnapshot) - { - $prefix = ''; - $now = $this->getDebugSnapshot(); - $logDetails = array_keys($this->getLoggingConfig('details', array())); - $innerGlue = $this->getLoggingConfig('innerglue', ': '); - $outerGlue = $this->getLoggingConfig('outerglue', ' | '); - - // Iterate through each detail that has been configured to be enabled - foreach ($logDetails as $detailName) { - - if (!$this->getLoggingConfig("details.$detailName.enabled", false)) - continue; - - switch ($detailName) { - - case 'slow'; - $value = $now['microtime'] - $debugSnapshot['microtime'] >= $this->getLoggingConfig("details.$detailName.threshold", self::DEFAULT_SLOW_THRESHOLD) ? 'YES' : ' NO'; - break; - - case 'time': - $value = number_format($now['microtime'] - $debugSnapshot['microtime'], $this->getLoggingConfig("details.$detailName.precision", 3)) . ' sec'; - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 10), ' ', STR_PAD_LEFT); - break; - - case 'mem': - $value = self::getReadableBytes($now['memory_get_usage'], $this->getLoggingConfig("details.$detailName.precision", 1)); - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 9), ' ', STR_PAD_LEFT); - break; - - case 'memdelta': - $value = $now['memory_get_usage'] - $debugSnapshot['memory_get_usage']; - $value = ($value > 0 ? '+' : '') . self::getReadableBytes($value, $this->getLoggingConfig("details.$detailName.precision", 1)); - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 10), ' ', STR_PAD_LEFT); - break; - - case 'mempeak': - $value = self::getReadableBytes($now['memory_get_peak_usage'], $this->getLoggingConfig("details.$detailName.precision", 1)); - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 9), ' ', STR_PAD_LEFT); - break; - - case 'querycount': - $value = $this->getQueryCount(); - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 2), ' ', STR_PAD_LEFT); - break; - - case 'method': - $value = $methodName; - $value = str_pad($value, $this->getLoggingConfig("details.$detailName.pad", 28), ' ', STR_PAD_RIGHT); - break; - - default: - $value = 'n/a'; - break; - - } - - $prefix .= $detailName . $innerGlue . $value . $outerGlue; - - } - - return $prefix; - } - - /** - * Returns a human-readable representation of the given byte count. - * - * @param int $bytes Byte count to convert. - * @param int $precision How many decimals to include. - * @return string - */ - protected function getReadableBytes($bytes, $precision) - { - $suffix = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - $total = count($suffix); - - for ($i = 0; $bytes > 1024 && $i < $total; $i++) - $bytes /= 1024; - - return number_format($bytes, $precision) . ' ' . $suffix[$i]; - } - - /** - * If so configured, makes an entry to the log of the state of this object just prior to its destruction. - * Add PropelPDO::__destruct to $defaultLogMethods to see this message - * - * @see self::log() - */ - public function __destruct() - { - if ($this->useDebug) { - $this->log('Closing connection', null, __METHOD__, $this->getDebugSnapshot()); - } - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/exception/PropelException.php b/airtime_mvc/library/propel/runtime/lib/exception/PropelException.php deleted file mode 100644 index b6a7bc700..000000000 --- a/airtime_mvc/library/propel/runtime/lib/exception/PropelException.php +++ /dev/null @@ -1,50 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.exception - */ -class PropelException extends Exception { - - /** The nested "cause" exception. */ - protected $cause; - - function __construct($p1, $p2 = null) { - - $cause = null; - - if ($p2 !== null) { - $msg = $p1; - $cause = $p2; - } else { - if ($p1 instanceof Exception) { - $msg = ""; - $cause = $p1; - } else { - $msg = $p1; - } - } - - parent::__construct($msg); - - if ($cause !== null) { - $this->cause = $cause; - $this->message .= " [wrapped: " . $cause->getMessage() ."]"; - } - } - - function getCause() { - return $this->cause; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/ModelWith.php b/airtime_mvc/library/propel/runtime/lib/formatter/ModelWith.php deleted file mode 100644 index 2e295505d..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/ModelWith.php +++ /dev/null @@ -1,144 +0,0 @@ -init($join); - } - } - - /** - * Define the joined hydration schema based on a join object. - * Fills the ModelWith properties using a ModelJoin as source - * - * @param ModelJoin $join - */ - public function init(ModelJoin $join) - { - $tableMap = $join->getTableMap(); - $this->modelName = $tableMap->getClassname(); - $this->modelPeerName = $tableMap->getPeerClassname(); - $this->isSingleTableInheritance = $tableMap->isSingleTableInheritance(); - $relation = $join->getRelationMap(); - if ($relation->getType() == RelationMap::ONE_TO_MANY) { - $this->isAdd = true; - $this->relationName = $relation->getName() . 's'; - $this->relationMethod = 'add' . $relation->getName(); - } else { - $this->relationName = $relation->getName(); - $this->relationMethod = 'set' . $relation->getName(); - } - if (!$join->isPrimary()) { - $this->relatedClass = $join->hasLeftTableAlias() ? $join->getLeftTableAlias() : $relation->getLeftTable()->getPhpName(); - } - } - - // DataObject getters & setters - - public function setModelName($modelName) - { - $this->modelName = $modelName; - } - - public function getModelName() - { - return $this->modelName; - } - - public function setModelPeerName($modelPeerName) - { - $this->modelPeerName = $modelPeerName; - } - - public function getModelPeerName() - { - return $this->modelPeerName; - } - - public function setIsSingleTableInheritance($isSingleTableInheritance) - { - $this->isSingleTableInheritance = $isSingleTableInheritance; - } - - public function isSingleTableInheritance() - { - return $this->isSingleTableInheritance; - } - - public function setIsAdd($isAdd) - { - $this->isAdd = $isAdd;; - } - - public function isAdd() - { - return $this->isAdd; - } - - public function setRelationName($relationName) - { - $this->relationName = $relationName; - } - - public function getRelationName() - { - return $this->relationName; - } - - public function setRelationMethod($relationMethod) - { - $this->relationMethod = $relationMethod; - } - - public function getRelationMethod() - { - return $this->relationMethod; - } - - public function setRelatedClass($relatedClass) - { - $this->relatedClass = $relatedClass; - } - - public function getRelatedClass() - { - return $this->relatedClass; - } - - // Utility methods - - public function isPrimary() - { - return null === $this->relatedClass; - } - - public function __toString() - { - return sprintf("modelName: %s, relationName: %s, relationMethod: %s, relatedClass: %s", $this->modelName, $this->relationName, $this->relationMethod, $this->relatedClass); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/PropelArrayFormatter.php b/airtime_mvc/library/propel/runtime/lib/formatter/PropelArrayFormatter.php deleted file mode 100644 index 97bc33427..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/PropelArrayFormatter.php +++ /dev/null @@ -1,170 +0,0 @@ -checkInit(); - if($class = $this->collectionName) { - $collection = new $class(); - $collection->setModel($this->class); - $collection->setFormatter($this); - } else { - $collection = array(); - } - if ($this->isWithOneToMany() && $this->hasLimit) { - throw new PropelException('Cannot use limit() in conjunction with with() on a one-to-many relationship. Please remove the with() call, or the limit() call.'); - } - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - if ($object = &$this->getStructuredArrayFromRow($row)) { - $collection[] = $object; - } - } - $this->currentObjects = array(); - $this->alreadyHydratedObjects = array(); - $stmt->closeCursor(); - - return $collection; - } - - public function formatOne(PDOStatement $stmt) - { - $this->checkInit(); - $result = null; - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - if ($object = &$this->getStructuredArrayFromRow($row)) { - $result = &$object; - } - } - $this->currentObjects = array(); - $this->alreadyHydratedObjects = array(); - $stmt->closeCursor(); - return $result; - } - - /** - * Formats an ActiveRecord object - * - * @param BaseObject $record the object to format - * - * @return array The original record turned into an array - */ - public function formatRecord($record = null) - { - return $record ? $record->toArray() : array(); - } - - public function isObjectFormatter() - { - return false; - } - - - /** - * Hydrates a series of objects from a result row - * The first object to hydrate is the model of the Criteria - * The following objects (the ones added by way of ModelCriteria::with()) are linked to the first one - * - * @param array $row associative array indexed by column number, - * as returned by PDOStatement::fetch(PDO::FETCH_NUM) - * - * @return Array - */ - public function &getStructuredArrayFromRow($row) - { - $col = 0; - - // hydrate main object or take it from registry - $mainObjectIsNew = false; - $mainKey = call_user_func(array($this->peer, 'getPrimaryKeyHashFromRow'), $row); - // we hydrate the main object even in case of a one-to-many relationship - // in order to get the $col variable increased anyway - $obj = $this->getSingleObjectFromRow($row, $this->class, $col); - if (!isset($this->alreadyHydratedObjects[$this->class][$mainKey])) { - $this->alreadyHydratedObjects[$this->class][$mainKey] = $obj->toArray(); - $mainObjectIsNew = true; - } - - $hydrationChain = array(); - - // related objects added using with() - foreach ($this->getWith() as $relAlias => $modelWith) { - - // determine class to use - if ($modelWith->isSingleTableInheritance()) { - $class = call_user_func(array($modelWith->getModelPeerName(), 'getOMClass'), $row, $col, false); - $refl = new ReflectionClass($class); - if ($refl->isAbstract()) { - $col += constant($class . 'Peer::NUM_COLUMNS'); - continue; - } - } else { - $class = $modelWith->getModelName(); - } - - // hydrate related object or take it from registry - $key = call_user_func(array($modelWith->getModelPeerName(), 'getPrimaryKeyHashFromRow'), $row, $col); - // we hydrate the main object even in case of a one-to-many relationship - // in order to get the $col variable increased anyway - $secondaryObject = $this->getSingleObjectFromRow($row, $class, $col); - if (!isset($this->alreadyHydratedObjects[$relAlias][$key])) { - - if ($secondaryObject->isPrimaryKeyNull()) { - $this->alreadyHydratedObjects[$relAlias][$key] = array(); - } else { - $this->alreadyHydratedObjects[$relAlias][$key] = $secondaryObject->toArray(); - } - } - - if ($modelWith->isPrimary()) { - $arrayToAugment = &$this->alreadyHydratedObjects[$this->class][$mainKey]; - } else { - $arrayToAugment = &$hydrationChain[$modelWith->getRelatedClass()]; - } - - if ($modelWith->isAdd()) { - if (!isset($arrayToAugment[$modelWith->getRelationName()]) || !in_array($this->alreadyHydratedObjects[$relAlias][$key], $arrayToAugment[$modelWith->getRelationName()])) { - $arrayToAugment[$modelWith->getRelationName()][] = &$this->alreadyHydratedObjects[$relAlias][$key]; - } - } else { - $arrayToAugment[$modelWith->getRelationName()] = &$this->alreadyHydratedObjects[$relAlias][$key]; - } - - $hydrationChain[$relAlias] = &$this->alreadyHydratedObjects[$relAlias][$key]; - } - - // columns added using withColumn() - foreach ($this->getAsColumns() as $alias => $clause) { - $this->alreadyHydratedObjects[$this->class][$mainKey][$alias] = $row[$col]; - $col++; - } - - if ($mainObjectIsNew) { - return $this->alreadyHydratedObjects[$this->class][$mainKey]; - } else { - // we still need to return a reference to something to avoid a warning - return $emptyVariable; - } - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/PropelFormatter.php b/airtime_mvc/library/propel/runtime/lib/formatter/PropelFormatter.php deleted file mode 100644 index 5933515d9..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/PropelFormatter.php +++ /dev/null @@ -1,202 +0,0 @@ -init($criteria); - } - } - - /** - * Define the hydration schema based on a query object. - * Fills the Formatter's properties using a Criteria as source - * - * @param ModelCriteria $criteria - * - * @return PropelFormatter The current formatter object - */ - public function init(ModelCriteria $criteria) - { - $this->dbName = $criteria->getDbName(); - $this->class = $criteria->getModelName(); - $this->peer = $criteria->getModelPeerName(); - $this->setWith($criteria->getWith()); - $this->asColumns = $criteria->getAsColumns(); - $this->hasLimit = $criteria->getLimit() != 0; - - return $this; - } - - // DataObject getters & setters - - public function setDbName($dbName) - { - $this->dbName = $dbName; - } - - public function getDbName() - { - return $this->dbName; - } - - public function setClass($class) - { - $this->class = $class; - } - - public function getClass() - { - return $this->class; - } - - public function setPeer($peer) - { - $this->peer = $peer; - } - - public function getPeer() - { - return $this->peer; - } - - public function setWith($withs = array()) - { - $this->with = array(); - foreach ($withs as $relation => $join) { - $this->with[$relation] = new ModelWith($join); - } - } - - public function getWith() - { - return $this->with; - } - - public function setAsColumns($asColumns = array()) - { - $this->asColumns = $asColumns; - } - - public function getAsColumns() - { - return $this->asColumns; - } - - public function setHasLimit($hasLimit = false) - { - $this->hasLimit = $hasLimit; - } - - public function hasLimit() - { - return $this->hasLimit; - } - - /** - * Formats an ActiveRecord object - * - * @param BaseObject $record the object to format - * - * @return BaseObject The original record - */ - public function formatRecord($record = null) - { - return $record; - } - - abstract public function format(PDOStatement $stmt); - - abstract public function formatOne(PDOStatement $stmt); - - abstract public function isObjectFormatter(); - - public function checkInit() - { - if (null === $this->peer) { - throw new PropelException('You must initialize a formatter object before calling format() or formatOne()'); - } - } - - public function getTableMap() - { - return Propel::getDatabaseMap($this->dbName)->getTableByPhpName($this->class); - } - - protected function isWithOneToMany() - { - foreach ($this->with as $modelWith) { - if ($modelWith->isAdd()) { - return true; - } - } - return false; - } - - /** - * Gets the worker object for the class. - * To save memory, we don't create a new object for each row, - * But we keep hydrating a single object per class. - * The column offset in the row is used to index the array of classes - * As there may be more than one object of the same class in the chain - * - * @param int $col Offset of the object in the list of objects to hydrate - * @param string $class Propel model object class - * - * @return BaseObject - */ - protected function getWorkerObject($col, $class) - { - if(isset($this->currentObjects[$col])) { - $this->currentObjects[$col]->clear(); - } else { - $this->currentObjects[$col] = new $class(); - } - return $this->currentObjects[$col]; - } - - /** - * Gets a Propel object hydrated from a selection of columns in statement row - * - * @param array $row associative array indexed by column number, - * as returned by PDOStatement::fetch(PDO::FETCH_NUM) - * @param string $class The classname of the object to create - * @param int $col The start column for the hydration (modified) - * - * @return BaseObject - */ - public function getSingleObjectFromRow($row, $class, &$col = 0) - { - $obj = $this->getWorkerObject($col, $class); - $col = $obj->hydrate($row, $col); - - return $obj; - } - - -} diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/PropelObjectFormatter.php b/airtime_mvc/library/propel/runtime/lib/formatter/PropelObjectFormatter.php deleted file mode 100644 index af6444e12..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/PropelObjectFormatter.php +++ /dev/null @@ -1,112 +0,0 @@ -checkInit(); - if($class = $this->collectionName) { - $collection = new $class(); - $collection->setModel($this->class); - $collection->setFormatter($this); - } else { - $collection = array(); - } - if ($this->isWithOneToMany()) { - if ($this->hasLimit) { - throw new PropelException('Cannot use limit() in conjunction with with() on a one-to-many relationship. Please remove the with() call, or the limit() call.'); - } - $pks = array(); - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $object = $this->getAllObjectsFromRow($row); - $pk = $object->getPrimaryKey(); - if (!in_array($pk, $pks)) { - $collection[] = $object; - $pks[] = $pk; - } - } - } else { - // only many-to-one relationships - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $collection[] = $this->getAllObjectsFromRow($row); - } - } - $stmt->closeCursor(); - - return $collection; - } - - public function formatOne(PDOStatement $stmt) - { - $this->checkInit(); - $result = null; - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $result = $this->getAllObjectsFromRow($row); - } - $stmt->closeCursor(); - - return $result; - } - - public function isObjectFormatter() - { - return true; - } - - /** - * Hydrates a series of objects from a result row - * The first object to hydrate is the model of the Criteria - * The following objects (the ones added by way of ModelCriteria::with()) are linked to the first one - * - * @param array $row associative array indexed by column number, - * as returned by PDOStatement::fetch(PDO::FETCH_NUM) - * - * @return BaseObject - */ - public function getAllObjectsFromRow($row) - { - // main object - list($obj, $col) = call_user_func(array($this->peer, 'populateObject'), $row); - // related objects added using with() - foreach ($this->getWith() as $class => $modelWith) { - list($endObject, $col) = call_user_func(array($modelWith->getModelPeerName(), 'populateObject'), $row, $col); - // as we may be in a left join, the endObject may be empty - // in which case it should not be related to the previous object - if (null === $endObject || $endObject->isPrimaryKeyNull()) { - continue; - } - if (isset($hydrationChain)) { - $hydrationChain[$class] = $endObject; - } else { - $hydrationChain = array($class => $endObject); - } - $startObject = $modelWith->isPrimary() ? $obj : $hydrationChain[$modelWith->getRelatedClass()]; - call_user_func(array($startObject, $modelWith->getRelationMethod()), $endObject); - } - // columns added using withColumn() - foreach ($this->getAsColumns() as $alias => $clause) { - $obj->setVirtualColumn($alias, $row[$col]); - $col++; - } - return $obj; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/PropelOnDemandFormatter.php b/airtime_mvc/library/propel/runtime/lib/formatter/PropelOnDemandFormatter.php deleted file mode 100644 index f717ccb20..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/PropelOnDemandFormatter.php +++ /dev/null @@ -1,96 +0,0 @@ -isSingleTableInheritance = $criteria->getTableMap()->isSingleTableInheritance(); - - return $this; - } - - public function format(PDOStatement $stmt) - { - $this->checkInit(); - if ($this->isWithOneToMany()) { - throw new PropelException('PropelOnDemandFormatter cannot hydrate related objects using a one-to-many relationship. Try removing with() from your query.'); - } - $class = $this->collectionName; - $collection = new $class(); - $collection->setModel($this->class); - $collection->initIterator($this, $stmt); - - return $collection; - } - - /** - * Hydrates a series of objects from a result row - * The first object to hydrate is the model of the Criteria - * The following objects (the ones added by way of ModelCriteria::with()) are linked to the first one - * - * @param array $row associative array indexed by column number, - * as returned by PDOStatement::fetch(PDO::FETCH_NUM) - * - * @return BaseObject - */ - public function getAllObjectsFromRow($row) - { - $col = 0; - // main object - $class = $this->isSingleTableInheritance ? call_user_func(array($his->peer, 'getOMClass'), $row, $col, false) : $this->class; - $obj = $this->getSingleObjectFromRow($row, $class, $col); - // related objects using 'with' - foreach ($this->getWith() as $modelWith) { - if ($modelWith->isSingleTableInheritance()) { - $class = call_user_func(array($modelWith->getModelPeerName(), 'getOMClass'), $row, $col, false); - $refl = new ReflectionClass($class); - if ($refl->isAbstract()) { - $col += constant($class . 'Peer::NUM_COLUMNS'); - continue; - } - } else { - $class = $modelWith->getModelName(); - } - $endObject = $this->getSingleObjectFromRow($row, $class, $col); - // as we may be in a left join, the endObject may be empty - // in which case it should not be related to the previous object - if (null === $endObject || $endObject->isPrimaryKeyNull()) { - continue; - } - if (isset($hydrationChain)) { - $hydrationChain[$class] = $endObject; - } else { - $hydrationChain = array($class => $endObject); - } - $startObject = $modelWith->isPrimary() ? $obj : $hydrationChain[$modelWith->getRelatedClass()]; - call_user_func(array($startObject, $modelWith->getRelationMethod()), $endObject); - } - foreach ($this->getAsColumns() as $alias => $clause) { - $obj->setVirtualColumn($alias, $row[$col]); - $col++; - } - return $obj; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/formatter/PropelStatementFormatter.php b/airtime_mvc/library/propel/runtime/lib/formatter/PropelStatementFormatter.php deleted file mode 100644 index 5103c8234..000000000 --- a/airtime_mvc/library/propel/runtime/lib/formatter/PropelStatementFormatter.php +++ /dev/null @@ -1,45 +0,0 @@ -rowCount() == 0) { - return null; - } else { - return $stmt; - } - } - - public function formatRecord($record = null) - { - throw new PropelException('The Statement formatter cannot transform a record into a statement'); - } - - public function isObjectFormatter() - { - return false; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/logger/BasicLogger.php b/airtime_mvc/library/propel/runtime/lib/logger/BasicLogger.php deleted file mode 100644 index ce335d2ee..000000000 --- a/airtime_mvc/library/propel/runtime/lib/logger/BasicLogger.php +++ /dev/null @@ -1,91 +0,0 @@ - - * and Jon Parise . - * - * @author Hans Lellelid - * @version $Revision: 1612 $ - * @package propel.runtime.logger - */ -interface BasicLogger -{ - - /** - * A convenience function for logging an alert event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function alert($message); - - /** - * A convenience function for logging a critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function crit($message); - - /** - * A convenience function for logging an error event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function err($message); - - /** - * A convenience function for logging a warning event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function warning($message); - /** - * A convenience function for logging an critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function notice($message); - /** - * A convenience function for logging an critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function info($message); - - /** - * A convenience function for logging a debug event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function debug($message); - - /** - * Primary method to handle logging. - * - * @param mixed $message String or Exception object containing the message - * to log. - * @param int $severity The numeric severity. Defaults to null so that no - * assumptions are made about the logging backend. - */ - public function log($message, $severity = null); - -} diff --git a/airtime_mvc/library/propel/runtime/lib/logger/MojaviLogAdapter.php b/airtime_mvc/library/propel/runtime/lib/logger/MojaviLogAdapter.php deleted file mode 100644 index af8e48423..000000000 --- a/airtime_mvc/library/propel/runtime/lib/logger/MojaviLogAdapter.php +++ /dev/null @@ -1,160 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.logger - */ -class MojaviLogAdapter implements BasicLogger -{ - - /** - * Instance of mojavi logger - */ - private $logger = null; - - /** - * constructor for setting up Mojavi log adapter - * - * @param ErrorLog $logger instance of Mojavi error log obtained by - * calling LogManager::getLogger(); - */ - public function __construct($logger = null) - { - $this->logger = $logger; - } - - /** - * A convenience function for logging an alert event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function alert($message) - { - $this->log($message, 'alert'); - } - - /** - * A convenience function for logging a critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function crit($message) - { - $this->log($message, 'crit'); - } - - /** - * A convenience function for logging an error event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function err($message) - { - $this->log($message, 'err'); - } - - /** - * A convenience function for logging a warning event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function warning($message) - { - $this->log($message, 'warning'); - } - - - /** - * A convenience function for logging an critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function notice($message) - { - $this->log($message, 'notice'); - } - /** - * A convenience function for logging an critical event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function info($message) - { - $this->log($message, 'info'); - } - - /** - * A convenience function for logging a debug event. - * - * @param mixed $message String or Exception object containing the message - * to log. - */ - public function debug($message) - { - $this->log($message, 'debug'); - } - - /** - * Primary method to handle logging. - * - * @param mixed $message String or Exception object containing the message - * to log. - * @param int $severity The numeric severity. Defaults to null so that no - * assumptions are made about the logging backend. - */ - public function log($message, $severity = null) - { - if (is_null($this->logger)) - $this->logger = LogManager::getLogger('propel'); - - switch($severity) - { - case 'crit': - $method = 'fatal'; - break; - case 'err': - $method = 'error'; - break; - case 'alert': - case 'warning': - $method = 'warning'; - break; - case 'notice': - case 'info': - $method = 'info'; - break; - case 'debug': - default: - $method = 'debug'; - } - - // get a backtrace to pass class, function, file, & line to Mojavi logger - $trace = debug_backtrace(); - - // call the appropriate Mojavi logger method - $this->logger->{$method} ( - $message, - $trace[2]['class'], - $trace[2]['function'], - $trace[1]['file'], - $trace[1]['line'] - ); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/map/ColumnMap.php b/airtime_mvc/library/propel/runtime/lib/map/ColumnMap.php deleted file mode 100644 index 69868ced5..000000000 --- a/airtime_mvc/library/propel/runtime/lib/map/ColumnMap.php +++ /dev/null @@ -1,464 +0,0 @@ - (Propel) - * @author John D. McNally (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.map - */ -class ColumnMap -{ - - // Propel type of the column - protected $type; - - // Size of the column - protected $size = 0; - - // Is it a primary key? - protected $pk = false; - - // Is null value allowed? - protected $notNull = false; - - // The default value for this column - protected $defaultValue; - - // Name of the table that this column is related to - protected $relatedTableName = ""; - - // Name of the column that this column is related to - protected $relatedColumnName = ""; - - // The TableMap for this column - protected $table; - - // The name of the column - protected $columnName; - - // The php name of the column - protected $phpName; - - // The validators for this column - protected $validators = array(); - - /** - * Constructor. - * - * @param string $name The name of the column. - * @param TableMap containingTable TableMap of the table this column is in. - */ - public function __construct($name, TableMap $containingTable) - { - $this->columnName = $name; - $this->table = $containingTable; - } - - /** - * Get the name of a column. - * - * @return string A String with the column name. - */ - public function getName() - { - return $this->columnName; - } - - /** - * Get the table map this column belongs to. - * @return TableMap - */ - public function getTable() - { - return $this->table; - } - - /** - * Get the name of the table this column is in. - * - * @return string A String with the table name. - */ - public function getTableName() - { - return $this->table->getName(); - } - - /** - * Get the table name + column name. - * - * @return string A String with the full column name. - */ - public function getFullyQualifiedName() - { - return $this->getTableName() . "." . $this->columnName; - } - - /** - * Set the php anme of this column. - * - * @param string $phpName A string representing the PHP name. - * @return void - */ - public function setPhpName($phpName) - { - $this->phpName = $phpName; - } - - /** - * Get the name of a column. - * - * @return string A String with the column name. - */ - public function getPhpName() - { - return $this->phpName; - } - - /** - * Set the Propel type of this column. - * - * @param string $type A string representing the Propel type (e.g. PropelColumnTypes::DATE). - * @return void - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Get the Propel type of this column. - * - * @return string A string representing the Propel type (e.g. PropelColumnTypes::DATE). - */ - public function getType() - { - return $this->type; - } - - /** - * Get the PDO type of this column. - * - * @return int The PDO::PARMA_* value - */ - public function getPdoType() - { - return PropelColumnTypes::getPdoType($this->type); - } - - /** - * Whether this is a BLOB, LONGVARBINARY, or VARBINARY. - * @return boolean - */ - public function isLob() - { - return ($this->type == PropelColumnTypes::BLOB || $this->type == PropelColumnTypes::VARBINARY || $this->type == PropelColumnTypes::LONGVARBINARY); - } - - /** - * Whether this is a DATE/TIME/TIMESTAMP column. - * - * @return boolean - * @since 1.3 - */ - public function isTemporal() - { - return ($this->type == PropelColumnTypes::TIMESTAMP || $this->type == PropelColumnTypes::DATE || $this->type == PropelColumnTypes::TIME || $this->type == PropelColumnTypes::BU_DATE || $this->type == PropelColumnTypes::BU_TIMESTAMP); - } - - /** - * Whether this is a DATE/TIME/TIMESTAMP column that is post-epoch (1970). - * - * PHP cannot handle pre-epoch timestamps well -- hence the need to differentiate - * between epoch and pre-epoch timestamps. - * - * @return boolean - * @deprecated Propel supports non-epoch dates - */ - public function isEpochTemporal() - { - return ($this->type == PropelColumnTypes::TIMESTAMP || $this->type == PropelColumnTypes::DATE || $this->type == PropelColumnTypes::TIME); - } - - /** - * Whether this column is numeric (int, decimal, bigint etc). - * @return boolean - */ - public function isNumeric() - { - return ($this->type == PropelColumnTypes::NUMERIC || $this->type == PropelColumnTypes::DECIMAL || $this->type == PropelColumnTypes::TINYINT || $this->type == PropelColumnTypes::SMALLINT || $this->type == PropelColumnTypes::INTEGER || $this->type == PropelColumnTypes::BIGINT || $this->type == PropelColumnTypes::REAL || $this->type == PropelColumnTypes::FLOAT || $this->type == PropelColumnTypes::DOUBLE); - } - - /** - * Whether this column is a text column (varchar, char, longvarchar). - * @return boolean - */ - public function isText() - { - return ($this->type == PropelColumnTypes::VARCHAR || $this->type == PropelColumnTypes::LONGVARCHAR || $this->type == PropelColumnTypes::CHAR); - } - - /** - * Set the size of this column. - * - * @param int $size An int specifying the size. - * @return void - */ - public function setSize($size) - { - $this->size = $size; - } - - /** - * Get the size of this column. - * - * @return int An int specifying the size. - */ - public function getSize() - { - return $this->size; - } - - /** - * Set if this column is a primary key or not. - * - * @param boolean $pk True if column is a primary key. - * @return void - */ - public function setPrimaryKey($pk) - { - $this->pk = $pk; - } - - /** - * Is this column a primary key? - * - * @return boolean True if column is a primary key. - */ - public function isPrimaryKey() - { - return $this->pk; - } - - /** - * Set if this column may be null. - * - * @param boolean nn True if column may be null. - * @return void - */ - public function setNotNull($nn) - { - $this->notNull = $nn; - } - - /** - * Is null value allowed ? - * - * @return boolean True if column may not be null. - */ - public function isNotNull() - { - return ($this->notNull || $this->isPrimaryKey()); - } - - /** - * Sets the default value for this column. - * @param mixed $defaultValue the default value for the column - * @return void - */ - public function setDefaultValue($defaultValue) - { - $this->defaultValue = $defaultValue; - } - - /** - * Gets the default value for this column. - * @return mixed String or NULL - */ - public function getDefaultValue() - { - return $this->defaultValue; - } - - /** - * Set the foreign key for this column. - * - * @param string tableName The name of the table that is foreign. - * @param string columnName The name of the column that is foreign. - * @return void - */ - public function setForeignKey($tableName, $columnName) - { - if ($tableName && $columnName) { - $this->relatedTableName = $tableName; - $this->relatedColumnName = $columnName; - } else { - $this->relatedTableName = ""; - $this->relatedColumnName = ""; - } - } - - /** - * Is this column a foreign key? - * - * @return boolean True if column is a foreign key. - */ - public function isForeignKey() - { - if ($this->relatedTableName) { - return true; - } else { - return false; - } - } - - /** - * Get the RelationMap object for this foreign key - */ - public function getRelation() - { - if(!$this->relatedTableName) return null; - foreach ($this->getTable()->getRelations() as $name => $relation) - { - if($relation->getType() == RelationMap::MANY_TO_ONE) - { - if ($relation->getForeignTable()->getName() == $this->getRelatedTableName() - && array_key_exists($this->getFullyQualifiedName(), $relation->getColumnMappings())) - { - return $relation; - } - } - } - } - - /** - * Get the table.column that this column is related to. - * - * @return string A String with the full name for the related column. - */ - public function getRelatedName() - { - return $this->relatedTableName . "." . $this->relatedColumnName; - } - - /** - * Get the table name that this column is related to. - * - * @return string A String with the name for the related table. - */ - public function getRelatedTableName() - { - return $this->relatedTableName; - } - - /** - * Get the column name that this column is related to. - * - * @return string A String with the name for the related column. - */ - public function getRelatedColumnName() - { - return $this->relatedColumnName; - } - - /** - * Get the TableMap object that this column is related to. - * - * @return TableMap The related TableMap object - * @throws PropelException when called on a column with no foreign key - */ - public function getRelatedTable() - { - if ($this->relatedTableName) { - return $this->table->getDatabaseMap()->getTable($this->relatedTableName); - } else { - throw new PropelException("Cannot fetch RelatedTable for column with no foreign key: " . $this->columnName); - } - } - - /** - * Get the TableMap object that this column is related to. - * - * @return ColumnMap The related ColumnMap object - * @throws PropelException when called on a column with no foreign key - */ - public function getRelatedColumn() - { - return $this->getRelatedTable()->getColumn($this->relatedColumnName); - } - - public function addValidator($validator) - { - $this->validators[] = $validator; - } - - public function hasValidators() - { - return count($this->validators) > 0; - } - - public function getValidators() - { - return $this->validators; - } - - /** - * Performs DB-specific ignore case, but only if the column type necessitates it. - * @param string $str The expression we want to apply the ignore case formatting to (e.g. the column name). - * @param DBAdapter $db - */ - public function ignoreCase($str, DBAdapter $db) - { - if ($this->isText()) { - return $db->ignoreCase($str); - } else { - return $str; - } - } - - /** - * Normalizes the column name, removing table prefix and uppercasing. - * - * article.first_name becomes FIRST_NAME - * - * @param string $name - * @return string Normalized column name. - */ - public static function normalizeName($name) - { - if (false !== ($pos = strpos($name, '.'))) { - $name = substr($name, $pos + 1); - } - $name = strtoupper($name); - return $name; - } - - // deprecated methods - - /** - * Gets column name - * @deprecated Use getName() instead - * @return string - * @deprecated Use getName() instead. - */ - public function getColumnName() - { - return $this->getName(); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/map/DatabaseMap.php b/airtime_mvc/library/propel/runtime/lib/map/DatabaseMap.php deleted file mode 100644 index e4e29e444..000000000 --- a/airtime_mvc/library/propel/runtime/lib/map/DatabaseMap.php +++ /dev/null @@ -1,191 +0,0 @@ - (Propel) - * @author John D. McNally (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1802 $ - * @package propel.runtime.map - */ -class DatabaseMap -{ - - /** @var string Name of the database. */ - protected $name; - - /** @var array TableMap[] Tables in the database, using table name as key */ - protected $tables = array(); - - /** @var array TableMap[] Tables in the database, using table phpName as key */ - protected $tablesByPhpName = array(); - - /** - * Constructor. - * - * @param string $name Name of the database. - */ - public function __construct($name) - { - $this->name = $name; - } - - /** - * Get the name of this database. - * - * @return string The name of the database. - */ - public function getName() - { - return $this->name; - } - - /** - * Add a new table to the database by name. - * - * @param string $tableName The name of the table. - * @return TableMap The newly created TableMap. - */ - public function addTable($tableName) - { - $this->tables[$tableName] = new TableMap($tableName, $this); - return $this->tables[$tableName]; - } - - /** - * Add a new table object to the database. - * - * @param TableMap $table The table to add - */ - public function addTableObject(TableMap $table) - { - $table->setDatabaseMap($this); - $this->tables[$table->getName()] = $table; - $this->tablesByPhpName[$table->getClassname()] = $table; - } - - /** - * Add a new table to the database, using the tablemap class name. - * - * @param string $tableMapClass The name of the table map to add - * @return TableMap The TableMap object - */ - public function addTableFromMapClass($tableMapClass) - { - $table = new $tableMapClass(); - if(!$this->hasTable($table->getName())) { - $this->addTableObject($table); - return $table; - } else { - return $this->getTable($table->getName()); - } - } - - /** - * Does this database contain this specific table? - * - * @param string $name The String representation of the table. - * @return boolean True if the database contains the table. - */ - public function hasTable($name) - { - if ( strpos($name, '.') > 0) { - $name = substr($name, 0, strpos($name, '.')); - } - return array_key_exists($name, $this->tables); - } - - /** - * Get a TableMap for the table by name. - * - * @param string $name Name of the table. - * @return TableMap A TableMap - * @throws PropelException if the table is undefined - */ - public function getTable($name) - { - if (!isset($this->tables[$name])) { - throw new PropelException("Cannot fetch TableMap for undefined table: " . $name ); - } - return $this->tables[$name]; - } - - /** - * Get a TableMap[] of all of the tables in the database. - * - * @return array A TableMap[]. - */ - public function getTables() - { - return $this->tables; - } - - /** - * Get a ColumnMap for the column by name. - * Name must be fully qualified, e.g. book.AUTHOR_ID - * - * @param $qualifiedColumnName Name of the column. - * @return ColumnMap A TableMap - * @throws PropelException if the table is undefined, or if the table is undefined - */ - public function getColumn($qualifiedColumnName) - { - list($tableName, $columnName) = explode('.', $qualifiedColumnName); - return $this->getTable($tableName)->getColumn($columnName, false); - } - - // deprecated methods - - /** - * Does this database contain this specific table? - * - * @deprecated Use hasTable() instead - * @param string $name The String representation of the table. - * @return boolean True if the database contains the table. - */ - public function containsTable($name) - { - return $this->hasTable($name); - } - - public function getTableByPhpName($phpName) - { - if (array_key_exists($phpName, $this->tablesByPhpName)) { - return $this->tablesByPhpName[$phpName]; - } else if (class_exists($tmClass = $phpName . 'TableMap')) { - $this->addTableFromMapClass($tmClass); - return $this->tablesByPhpName[$phpName]; - } else if (class_exists($tmClass = substr_replace($phpName, '\\map\\', strrpos($phpName, '\\'), 1) . 'TableMap')) { - $this->addTableFromMapClass($tmClass); - return $this->tablesByPhpName[$phpName]; - } else { - throw new PropelException("Cannot fetch TableMap for undefined table phpName: " . $phpName); - } - } - - /** - * Convenience method to get the DBAdapter registered with Propel for this database. - * @return DBAdapter - * @see Propel::getDB(string) - */ - public function getDBAdapter() - { - return Propel::getDB($this->name); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/map/RelationMap.php b/airtime_mvc/library/propel/runtime/lib/map/RelationMap.php deleted file mode 100644 index 059cd00a4..000000000 --- a/airtime_mvc/library/propel/runtime/lib/map/RelationMap.php +++ /dev/null @@ -1,299 +0,0 @@ -name = $name; - } - - /** - * Get the name of this relation. - * - * @return string The name of the relation. - */ - public function getName() - { - return $this->name; - } - - /** - * Set the type - * - * @param integer $type The relation type (either self::MANY_TO_ONE, self::ONE_TO_MANY, or self::ONE_TO_ONE) - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Get the type - * - * @return integer the relation type - */ - public function getType() - { - return $this->type; - } - - /** - * Set the local table - * - * @param TableMap $table The local table for this relationship - */ - public function setLocalTable($table) - { - $this->localTable = $table; - } - - /** - * Get the local table - * - * @return TableMap The local table for this relationship - */ - public function getLocalTable() - { - return $this->localTable; - } - - /** - * Set the foreign table - * - * @param TableMap $table The foreign table for this relationship - */ - public function setForeignTable($table) - { - $this->foreignTable = $table; - } - - /** - * Get the foreign table - * - * @return TableMap The foreign table for this relationship - */ - public function getForeignTable() - { - return $this->foreignTable; - } - - /** - * Get the left table of the relation - * - * @return TableMap The left table for this relationship - */ - public function getLeftTable() - { - return ($this->getType() == RelationMap::MANY_TO_ONE) ? $this->getLocalTable() : $this->getForeignTable(); - } - - /** - * Get the right table of the relation - * - * @return TableMap The right table for this relationship - */ - public function getRightTable() - { - return ($this->getType() == RelationMap::MANY_TO_ONE) ? $this->getForeignTable() : $this->getLocalTable(); - } - - /** - * Add a column mapping - * - * @param ColumnMap $local The local column - * @param ColumnMap $foreign The foreign column - */ - public function addColumnMapping(ColumnMap $local, ColumnMap $foreign) - { - $this->localColumns[] = $local; - $this->foreignColumns[] = $foreign; - } - - /** - * Get an associative array mapping local column names to foreign column names - * The arrangement of the returned array depends on the $direction parameter: - * - If the value is RelationMap::LOCAL_TO_FOREIGN, then the returned array is local => foreign - * - If the value is RelationMap::LEFT_TO_RIGHT, then the returned array is left => right - * - * @param int $direction How the associative array must return columns - * @return Array Associative array (local => foreign) of fully qualified column names - */ - public function getColumnMappings($direction = RelationMap::LOCAL_TO_FOREIGN) - { - $h = array(); - if ($direction == RelationMap::LEFT_TO_RIGHT && $this->getType() == RelationMap::MANY_TO_ONE) { - $direction = RelationMap::LOCAL_TO_FOREIGN; - } - for ($i=0, $size=count($this->localColumns); $i < $size; $i++) { - if ($direction == RelationMap::LOCAL_TO_FOREIGN) { - $h[$this->localColumns[$i]->getFullyQualifiedName()] = $this->foreignColumns[$i]->getFullyQualifiedName(); - } else { - $h[$this->foreignColumns[$i]->getFullyQualifiedName()] = $this->localColumns[$i]->getFullyQualifiedName(); - } - } - return $h; - } - - /** - * Returns true if the relation has more than one column mapping - * - * @return boolean - */ - public function isComposite() - { - return $this->countColumnMappings() > 1; - } - - /** - * Return the number of column mappings - * - * @return int - */ - public function countColumnMappings() - { - return count($this->localColumns); - } - - /** - * Get the local columns - * - * @return Array list of ColumnMap objects - */ - public function getLocalColumns() - { - return $this->localColumns; - } - - /** - * Get the foreign columns - * - * @return Array list of ColumnMap objects - */ - public function getForeignColumns() - { - return $this->foreignColumns; - } - - /** - * Get the left columns of the relation - * - * @return array of ColumnMap objects - */ - public function getLeftColumns() - { - return ($this->getType() == RelationMap::MANY_TO_ONE) ? $this->getLocalColumns() : $this->getForeignColumns(); - } - - /** - * Get the right columns of the relation - * - * @return array of ColumnMap objects - */ - public function getRightColumns() - { - return ($this->getType() == RelationMap::MANY_TO_ONE) ? $this->getForeignColumns() : $this->getLocalColumns(); - } - - - /** - * Set the onUpdate behavior - * - * @param string $onUpdate - */ - public function setOnUpdate($onUpdate) - { - $this->onUpdate = $onUpdate; - } - - /** - * Get the onUpdate behavior - * - * @return integer the relation type - */ - public function getOnUpdate() - { - return $this->onUpdate; - } - - /** - * Set the onDelete behavior - * - * @param string $onDelete - */ - public function setOnDelete($onDelete) - { - $this->onDelete = $onDelete; - } - - /** - * Get the onDelete behavior - * - * @return integer the relation type - */ - public function getOnDelete() - { - return $this->onDelete; - } - - /** - * Gets the symmetrical relation - * - * @return RelationMap - */ - public function getSymmetricalRelation() - { - $localMapping = array($this->getLeftColumns(), $this->getRightColumns()); - foreach ($this->getRightTable()->getRelations() as $relation) { - if ($localMapping == array($relation->getRightColumns(), $relation->getLeftColumns())) { - return $relation; - } - } - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/map/TableMap.php b/airtime_mvc/library/propel/runtime/lib/map/TableMap.php deleted file mode 100644 index 164e137f5..000000000 --- a/airtime_mvc/library/propel/runtime/lib/map/TableMap.php +++ /dev/null @@ -1,712 +0,0 @@ - (Propel) - * @author John D. McNally (Torque) - * @author Daniel Rall (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.map - */ -class TableMap -{ - - /** - * Columns in the table - * @var array TableMap[] - */ - protected $columns = array(); - - /** - * Columns in the table, using table phpName as key - * @var array TableMap[] - */ - protected $columnsByPhpName = array(); - - // The database this table belongs to - protected $dbMap; - - // The name of the table - protected $tableName; - - // The PHP name of the table - protected $phpName; - - // The Classname for this table - protected $classname; - - // The Package for this table - protected $package; - - // Whether to use an id generator for pkey - protected $useIdGenerator; - - // Whether the table uses single table inheritance - protected $isSingleTableInheritance = false; - - // The primary key columns in the table - protected $primaryKeys = array(); - - // The foreign key columns in the table - protected $foreignKeys = array(); - - // The relationships in the table - protected $relations = array(); - - // Relations are lazy loaded. This property tells if the relations are loaded or not - protected $relationsBuilt = false; - - // Object to store information that is needed if the for generating primary keys - protected $pkInfo; - - /** - * Construct a new TableMap. - * - */ - public function __construct($name = null, $dbMap = null) - { - if (null !== $name) { - $this->setName($name); - } - if (null !== $dbMap) { - $this->setDatabaseMap($dbMap); - } - $this->initialize(); - } - - /** - * Initialize the TableMap to build columns, relations, etc - * This method should be overridden by descendents - */ - public function initialize() - { - } - - /** - * Set the DatabaseMap containing this TableMap. - * - * @param DatabaseMap $dbMap A DatabaseMap. - */ - public function setDatabaseMap(DatabaseMap $dbMap) - { - $this->dbMap = $dbMap; - } - - /** - * Get the DatabaseMap containing this TableMap. - * - * @return DatabaseMap A DatabaseMap. - */ - public function getDatabaseMap() - { - return $this->dbMap; - } - - /** - * Set the name of the Table. - * - * @param string $name The name of the table. - */ - public function setName($name) - { - $this->tableName = $name; - } - - /** - * Get the name of the Table. - * - * @return string A String with the name of the table. - */ - public function getName() - { - return $this->tableName; - } - - /** - * Set the PHP name of the Table. - * - * @param string $phpName The PHP Name for this table - */ - public function setPhpName($phpName) - { - $this->phpName = $phpName; - } - - /** - * Get the PHP name of the Table. - * - * @return string A String with the name of the table. - */ - public function getPhpName() - { - return $this->phpName; - } - - /** - * Set the Classname of the Table. Could be useful for calling - * Peer and Object methods dynamically. - * @param string $classname The Classname - */ - public function setClassname($classname) - { - $this->classname = $classname; - } - - /** - * Get the Classname of the Propel Class belonging to this table. - * @return string - */ - public function getClassname() - { - return $this->classname; - } - - /** - * Get the Peer Classname of the Propel Class belonging to this table. - * @return string - */ - public function getPeerClassname() - { - return constant($this->classname . '::PEER'); - } - - /** - * Set the Package of the Table - * - * @param string $package The Package - */ - public function setPackage($package) - { - $this->package = $package; - } - - /** - * Get the Package of the table. - * @return string - */ - public function getPackage() - { - return $this->package; - } - - /** - * Set whether or not to use Id generator for primary key. - * @param boolean $bit - */ - public function setUseIdGenerator($bit) - { - $this->useIdGenerator = $bit; - } - - /** - * Whether to use Id generator for primary key. - * @return boolean - */ - public function isUseIdGenerator() - { - return $this->useIdGenerator; - } - - /** - * Set whether or not to this table uses single table inheritance - * @param boolean $bit - */ - public function setSingleTableInheritance($bit) - { - $this->isSingleTableInheritance = $bit; - } - - /** - * Whether this table uses single table inheritance - * @return boolean - */ - public function isSingleTableInheritance() - { - return $this->isSingleTableInheritance; - } - - /** - * Sets the pk information needed to generate a key - * - * @param $pkInfo information needed to generate a key - */ - public function setPrimaryKeyMethodInfo($pkInfo) - { - $this->pkInfo = $pkInfo; - } - - /** - * Get the information used to generate a primary key - * - * @return An Object. - */ - public function getPrimaryKeyMethodInfo() - { - return $this->pkInfo; - } - - /** - * Add a column to the table. - * - * @param string name A String with the column name. - * @param string $type A string specifying the Propel type. - * @param boolean $isNotNull Whether column does not allow NULL values. - * @param int $size An int specifying the size. - * @param boolean $pk True if column is a primary key. - * @param string $fkTable A String with the foreign key table name. - * @param $fkColumn A String with the foreign key column name. - * @param string $defaultValue The default value for this column. - * @return ColumnMap The newly created column. - */ - public function addColumn($name, $phpName, $type, $isNotNull = false, $size = null, $defaultValue = null, $pk = false, $fkTable = null, $fkColumn = null) - { - $col = new ColumnMap($name, $this); - $col->setType($type); - $col->setSize($size); - $col->setPhpName($phpName); - $col->setNotNull($isNotNull); - $col->setDefaultValue($defaultValue); - - if ($pk) { - $col->setPrimaryKey(true); - $this->primaryKeys[$name] = $col; - } - - if ($fkTable && $fkColumn) { - $col->setForeignKey($fkTable, $fkColumn); - $this->foreignKeys[$name] = $col; - } - - $this->columns[$name] = $col; - $this->columnsByPhpName[$phpName] = $col; - - return $col; - } - - /** - * Add a pre-created column to this table. It will replace any - * existing column. - * - * @param ColumnMap $cmap A ColumnMap. - * @return ColumnMap The added column map. - */ - public function addConfiguredColumn($cmap) - { - $this->columns[ $cmap->getColumnName() ] = $cmap; - return $cmap; - } - - /** - * Does this table contain the specified column? - * - * @param mixed $name name of the column or ColumnMap instance - * @param boolean $normalize Normalize the column name (if column name not like FIRST_NAME) - * @return boolean True if the table contains the column. - */ - public function hasColumn($name, $normalize = true) - { - if ($name instanceof ColumnMap) { - $name = $name->getColumnName(); - } else if($normalize) { - $name = ColumnMap::normalizeName($name); - } - return isset($this->columns[$name]); - } - - /** - * Get a ColumnMap for the table. - * - * @param string $name A String with the name of the table. - * @param boolean $normalize Normalize the column name (if column name not like FIRST_NAME) - * @return ColumnMap A ColumnMap. - * @throws PropelException if the column is undefined - */ - public function getColumn($name, $normalize = true) - { - if ($normalize) { - $name = ColumnMap::normalizeName($name); - } - if (!$this->hasColumn($name, false)) { - throw new PropelException("Cannot fetch ColumnMap for undefined column: " . $name); - } - return $this->columns[$name]; - } - - /** - * Does this table contain the specified column? - * - * @param mixed $phpName name of the column - * @return boolean True if the table contains the column. - */ - public function hasColumnByPhpName($phpName) - { - return isset($this->columnsByPhpName[$phpName]); - } - - /** - * Get a ColumnMap for the table. - * - * @param string $phpName A String with the name of the table. - * @return ColumnMap A ColumnMap. - * @throws PropelException if the column is undefined - */ - public function getColumnByPhpName($phpName) - { - if (!isset($this->columnsByPhpName[$phpName])) { - throw new PropelException("Cannot fetch ColumnMap for undefined column phpName: " . $phpName); - } - return $this->columnsByPhpName[$phpName]; - } - - /** - * Get a ColumnMap[] of the columns in this table. - * - * @return array A ColumnMap[]. - */ - public function getColumns() - { - return $this->columns; - } - - /** - * Add a primary key column to this Table. - * - * @param string $columnName A String with the column name. - * @param string $type A string specifying the Propel type. - * @param boolean $isNotNull Whether column does not allow NULL values. - * @param $size An int specifying the size. - * @return ColumnMap Newly added PrimaryKey column. - */ - public function addPrimaryKey($columnName, $phpName, $type, $isNotNull = false, $size = null, $defaultValue = null) - { - return $this->addColumn($columnName, $phpName, $type, $isNotNull, $size, $defaultValue, true, null, null); - } - - /** - * Add a foreign key column to the table. - * - * @param string $columnName A String with the column name. - * @param string $type A string specifying the Propel type. - * @param string $fkTable A String with the foreign key table name. - * @param string $fkColumn A String with the foreign key column name. - * @param boolean $isNotNull Whether column does not allow NULL values. - * @param int $size An int specifying the size. - * @param string $defaultValue The default value for this column. - * @return ColumnMap Newly added ForeignKey column. - */ - public function addForeignKey($columnName, $phpName, $type, $fkTable, $fkColumn, $isNotNull = false, $size = 0, $defaultValue = null) - { - return $this->addColumn($columnName, $phpName, $type, $isNotNull, $size, $defaultValue, false, $fkTable, $fkColumn); - } - - /** - * Add a foreign primary key column to the table. - * - * @param string $columnName A String with the column name. - * @param string $type A string specifying the Propel type. - * @param string $fkTable A String with the foreign key table name. - * @param string $fkColumn A String with the foreign key column name. - * @param boolean $isNotNull Whether column does not allow NULL values. - * @param int $size An int specifying the size. - * @param string $defaultValue The default value for this column. - * @return ColumnMap Newly created foreign pkey column. - */ - public function addForeignPrimaryKey($columnName, $phpName, $type, $fkTable, $fkColumn, $isNotNull = false, $size = 0, $defaultValue = null) - { - return $this->addColumn($columnName, $phpName, $type, $isNotNull, $size, $defaultValue, true, $fkTable, $fkColumn); - } - - /** - * Returns array of ColumnMap objects that make up the primary key for this table - * - * @return array ColumnMap[] - */ - public function getPrimaryKeys() - { - return $this->primaryKeys; - } - - /** - * Returns array of ColumnMap objects that are foreign keys for this table - * - * @return array ColumnMap[] - */ - public function getForeignKeys() - { - return $this->foreignKeys; - } - - /** - * Add a validator to a table's column - * - * @param string $columnName The name of the validator's column - * @param string $name The rule name of this validator - * @param string $classname The dot-path name of class to use (e.g. myapp.propel.MyValidator) - * @param string $value - * @param string $message The error message which is returned on invalid values - * @return void - */ - public function addValidator($columnName, $name, $classname, $value, $message) - { - if (false !== ($pos = strpos($columnName, '.'))) { - $columnName = substr($columnName, $pos + 1); - } - - $col = $this->getColumn($columnName); - if ($col !== null) { - $validator = new ValidatorMap($col); - $validator->setName($name); - $validator->setClass($classname); - $validator->setValue($value); - $validator->setMessage($message); - $col->addValidator($validator); - } - } - - /** - * Build relations - * Relations are lazy loaded for performance reasons - * This method should be overridden by descendents - */ - public function buildRelations() - { - } - - /** - * Adds a RelationMap to the table - * - * @param string $name The relation name - * @param string $tablePhpName The related table name - * @param integer $type The relation type (either RelationMap::MANY_TO_ONE, RelationMap::ONE_TO_MANY, or RelationMAp::ONE_TO_ONE) - * @param array $columnMapping An associative array mapping column names (local => foreign) - * @return RelationMap the built RelationMap object - */ - public function addRelation($name, $tablePhpName, $type, $columnMapping = array(), $onDelete = null, $onUpdate = null) - { - // note: using phpName for the second table allows the use of DatabaseMap::getTableByPhpName() - // and this method autoloads the TableMap if the table isn't loaded yet - $relation = new RelationMap($name); - $relation->setType($type); - $relation->setOnUpdate($onUpdate); - $relation->setOnDelete($onDelete); - // set tables - if ($type == RelationMap::MANY_TO_ONE) { - $relation->setLocalTable($this); - $relation->setForeignTable($this->dbMap->getTableByPhpName($tablePhpName)); - } else { - $relation->setLocalTable($this->dbMap->getTableByPhpName($tablePhpName)); - $relation->setForeignTable($this); - $columnMapping = array_flip($columnMapping); - } - // set columns - foreach ($columnMapping as $local => $foreign) { - $relation->addColumnMapping( - $relation->getLocalTable()->getColumn($local), - $relation->getForeignTable()->getColumn($foreign) - ); - } - $this->relations[$name] = $relation; - return $relation; - } - - /** - * Gets a RelationMap of the table by relation name - * This method will build the relations if they are not built yet - * - * @param String $name The relation name - * @return boolean true if the relation exists - */ - public function hasRelation($name) - { - return array_key_exists($name, $this->getRelations()); - } - - /** - * Gets a RelationMap of the table by relation name - * This method will build the relations if they are not built yet - * - * @param String $name The relation name - * @return RelationMap The relation object - * @throws PropelException When called on an inexistent relation - */ - public function getRelation($name) - { - if (!array_key_exists($name, $this->getRelations())) - { - throw new PropelException('Calling getRelation() on an unknown relation, ' . $name); - } - return $this->relations[$name]; - } - - /** - * Gets the RelationMap objects of the table - * This method will build the relations if they are not built yet - * - * @return Array list of RelationMap objects - */ - public function getRelations() - { - if(!$this->relationsBuilt) - { - $this->buildRelations(); - $this->relationsBuilt = true; - } - return $this->relations; - } - - /** - * - * Gets the list of behaviors registered for this table - * - * @return array - */ - public function getBehaviors() - { - return array(); - } - - // Deprecated methods and attributres, to be removed - - /** - * Does this table contain the specified column? - * - * @deprecated Use hasColumn instead - * @param mixed $name name of the column or ColumnMap instance - * @param boolean $normalize Normalize the column name (if column name not like FIRST_NAME) - * @return boolean True if the table contains the column. - */ - public function containsColumn($name, $normalize = true) - { - return $this->hasColumn($name, $normalize); - } - - /** - * Normalizes the column name, removing table prefix and uppercasing. - * article.first_name becomes FIRST_NAME - * - * @deprecated Use ColumnMap::normalizeColumName() instead - * @param string $name - * @return string Normalized column name. - */ - protected function normalizeColName($name) - { - return ColumnMap::normalizeName($name); - } - - /** - * Returns array of ColumnMap objects that make up the primary key for this table. - * - * @deprecated Use getPrimaryKeys instead - * @return array ColumnMap[] - */ - public function getPrimaryKeyColumns() - { - return array_values($this->primaryKeys); - } - - //---Utility methods for doing intelligent lookup of table names - - /** - * The prefix on the table name. - * @deprecated Not used anywhere in Propel - */ - private $prefix; - - /** - * Get table prefix name. - * - * @deprecated Not used anywhere in Propel - * @return string A String with the prefix. - */ - public function getPrefix() - { - return $this->prefix; - } - - /** - * Set table prefix name. - * - * @deprecated Not used anywhere in Propel - * @param string $prefix The prefix for the table name (ie: SCARAB for - * SCARAB_PROJECT). - * @return void - */ - public function setPrefix($prefix) - { - $this->prefix = $prefix; - } - - /** - * Tell me if i have PREFIX in my string. - * - * @deprecated Not used anywhere in Propel - * @param data A String. - * @return boolean True if prefix is contained in data. - */ - protected function hasPrefix($data) - { - return (strpos($data, $this->prefix) === 0); - } - - /** - * Removes the PREFIX if found - * - * @deprecated Not used anywhere in Propel - * @param string $data A String. - * @return string A String with data, but with prefix removed. - */ - protected function removePrefix($data) - { - return $this->hasPrefix($data) ? substr($data, strlen($this->prefix)) : $data; - } - - /** - * Removes the PREFIX, removes the underscores and makes - * first letter caps. - * - * SCARAB_FOO_BAR becomes FooBar. - * - * @deprecated Not used anywhere in Propel. At buildtime, use Column::generatePhpName() for that purpose - * @param data A String. - * @return string A String with data processed. - */ - public final function removeUnderScores($data) - { - $out = ''; - $tmp = $this->removePrefix($data); - $tok = strtok($tmp, '_'); - while ($tok) { - $out .= ucfirst($tok); - $tok = strtok('_'); - } - return $out; - } - - /** - * Makes the first letter caps and the rest lowercase. - * - * @deprecated Not used anywhere in Propel. - * @param string $data A String. - * @return string A String with data processed. - */ - private function firstLetterCaps($data) - { - return(ucfirst(strtolower($data))); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/map/ValidatorMap.php b/airtime_mvc/library/propel/runtime/lib/map/ValidatorMap.php deleted file mode 100644 index 11f18c0a7..000000000 --- a/airtime_mvc/library/propel/runtime/lib/map/ValidatorMap.php +++ /dev/null @@ -1,92 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.map - */ -class ValidatorMap -{ - /** rule name of this validator */ - private $name; - /** the dot-path to class to use for validator */ - private $classname; - /** value to check against */ - private $value; - /** execption message thrown on invalid input */ - private $message; - /** related column */ - private $column; - - public function __construct($containingColumn) - { - $this->column = $containingColumn; - } - - public function getColumn() - { - return $this->column; - } - - public function getColumnName() - { - return $this->column->getColumnName(); - } - - public function setName($name) - { - $this->name = $name; - } - - public function setClass($classname) - { - $this->classname = $classname; - } - - public function setValue($value) - { - $this->value = $value; - } - - public function setMessage($message) - { - $this->message = $message; - } - - public function getName() - { - return $this->name; - } - - public function getClass() - { - return $this->classname; - } - - public function getValue() - { - return $this->value; - } - - public function getMessage() - { - return $this->message; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/om/BaseObject.php b/airtime_mvc/library/propel/runtime/lib/om/BaseObject.php deleted file mode 100644 index a0a7d126e..000000000 --- a/airtime_mvc/library/propel/runtime/lib/om/BaseObject.php +++ /dev/null @@ -1,319 +0,0 @@ - (Propel) - * @author Frank Y. Kim (Torque) - * @author John D. McNally (Torque) - * @version $Revision: 1673 $ - * @package propel.runtime.om - */ -abstract class BaseObject -{ - - /** - * attribute to determine if this object has previously been saved. - * @var boolean - */ - protected $_new = true; - - /** - * attribute to determine whether this object has been deleted. - * @var boolean - */ - protected $_deleted = false; - - /** - * The columns that have been modified in current object. - * Tracking modified columns allows us to only update modified columns. - * @var array - */ - protected $modifiedColumns = array(); - - /** - * The (virtual) columns that are added at runtime - * The formatters can add supplementary columns based on a resultset - * @var array - */ - protected $virtualColumns = array(); - - /** - * Empty constructor (this allows people with their own BaseObject implementation to use its constructor) - */ - public function __construct() { - - } - - /** - * Returns whether the object has been modified. - * - * @return boolean True if the object has been modified. - */ - public function isModified() - { - return !empty($this->modifiedColumns); - } - - /** - * Has specified column been modified? - * - * @param string $col column fully qualified name (BasePeer::TYPE_COLNAME), e.g. Book::AUTHOR_ID - * @return boolean True if $col has been modified. - */ - public function isColumnModified($col) - { - return in_array($col, $this->modifiedColumns); - } - - /** - * Get the columns that have been modified in this object. - * @return array A unique list of the modified column names for this object. - */ - public function getModifiedColumns() - { - return array_unique($this->modifiedColumns); - } - - /** - * Returns whether the object has ever been saved. This will - * be false, if the object was retrieved from storage or was created - * and then saved. - * - * @return true, if the object has never been persisted. - */ - public function isNew() - { - return $this->_new; - } - - /** - * Setter for the isNew attribute. This method will be called - * by Propel-generated children and Peers. - * - * @param boolean $b the state of the object. - */ - public function setNew($b) - { - $this->_new = (boolean) $b; - } - - /** - * Whether this object has been deleted. - * @return boolean The deleted state of this object. - */ - public function isDeleted() - { - return $this->_deleted; - } - - /** - * Specify whether this object has been deleted. - * @param boolean $b The deleted state of this object. - * @return void - */ - public function setDeleted($b) - { - $this->_deleted = (boolean) $b; - } - - /** - * Code to be run before persisting the object - * @param PropelPDO $con - * @return bloolean - */ - public function preSave(PropelPDO $con = null) - { - return true; - } - - /** - * Code to be run after persisting the object - * @param PropelPDO $con - */ - public function postSave(PropelPDO $con = null) { } - - /** - * Code to be run before inserting to database - * @param PropelPDO $con - * @return boolean - */ - public function preInsert(PropelPDO $con = null) - { - return true; - } - - /** - * Code to be run after inserting to database - * @param PropelPDO $con - */ - public function postInsert(PropelPDO $con = null) { } - - /** - * Code to be run before updating the object in database - * @param PropelPDO $con - * @return boolean - */ - public function preUpdate(PropelPDO $con = null) - { - return true; - } - - /** - * Code to be run after updating the object in database - * @param PropelPDO $con - */ - public function postUpdate(PropelPDO $con = null) { } - - /** - * Code to be run before deleting the object in database - * @param PropelPDO $con - * @return boolean - */ - public function preDelete(PropelPDO $con = null) - { - return true; - } - - /** - * Code to be run after deleting the object in database - * @param PropelPDO $con - */ - public function postDelete(PropelPDO $con = null) { } - - /** - * Sets the modified state for the object to be false. - * @param string $col If supplied, only the specified column is reset. - * @return void - */ - public function resetModified($col = null) - { - if ($col !== null) { - while (($offset = array_search($col, $this->modifiedColumns)) !== false) { - array_splice($this->modifiedColumns, $offset, 1); - } - } else { - $this->modifiedColumns = array(); - } - } - - /** - * Compares this with another BaseObject instance. If - * obj is an instance of BaseObject, delegates to - * equals(BaseObject). Otherwise, returns false. - * - * @param obj The object to compare to. - * @return Whether equal to the object specified. - */ - public function equals($obj) - { - $thisclazz = get_class($this); - if (is_object($obj) && $obj instanceof $thisclazz) { - if ($this === $obj) { - return true; - } elseif ($this->getPrimaryKey() === null || $obj->getPrimaryKey() === null) { - return false; - } else { - return ($this->getPrimaryKey() === $obj->getPrimaryKey()); - } - } else { - return false; - } - } - - /** - * If the primary key is not null, return the hashcode of the - * primary key. Otherwise calls Object.hashCode(). - * - * @return int Hashcode - */ - public function hashCode() - { - $ok = $this->getPrimaryKey(); - if ($ok === null) { - return crc32(serialize($this)); - } - return crc32(serialize($ok)); // serialize because it could be an array ("ComboKey") - } - - /** - * Get the associative array of the virtual columns in this object - * - * @param string $name The virtual column name - * - * @return array - */ - public function getVirtualColumns() - { - return $this->virtualColumns; - } - - /** - * Checks the existence of a virtual column in this object - * - * @return boolean - */ - public function hasVirtualColumn($name) - { - return array_key_exists($name, $this->virtualColumns); - } - - /** - * Get the value of a virtual column in this object - * - * @return mixed - */ - public function getVirtualColumn($name) - { - if (!$this->hasVirtualColumn($name)) { - throw new PropelException('Cannot get value of inexistent virtual column ' . $name); - } - return $this->virtualColumns[$name]; - } - - /** - * Get the value of a virtual column in this object - * - * @param string $name The virtual column name - * @param mixed $value The value to give to the virtual column - * - * @return BaseObject The current object, for fluid interface - */ - public function setVirtualColumn($name, $value) - { - $this->virtualColumns[$name] = $value; - return $this; - } - - /** - * Logs a message using Propel::log(). - * - * @param string $msg - * @param int $priority One of the Propel::LOG_* logging levels - * @return boolean - */ - protected function log($msg, $priority = Propel::LOG_INFO) - { - return Propel::log(get_class($this) . ': ' . $msg, $priority); - } - - /** - * Clean up internal collections prior to serializing - * Avoids recursive loops that turn into segmentation faults when serializing - */ - public function __sleep() - { - $this->clearAllReferences(); - return array_keys(get_object_vars($this)); - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/om/NestedSetRecursiveIterator.php b/airtime_mvc/library/propel/runtime/lib/om/NestedSetRecursiveIterator.php deleted file mode 100644 index 97a83028c..000000000 --- a/airtime_mvc/library/propel/runtime/lib/om/NestedSetRecursiveIterator.php +++ /dev/null @@ -1,86 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.om - */ -class NestedSetRecursiveIterator implements RecursiveIterator -{ - protected $topNode = null; - - protected $curNode = null; - - public function __construct($node) - { - $this->topNode = $node; - $this->curNode = $node; - } - - public function rewind() - { - $this->curNode = $this->topNode; - } - - public function valid() - { - return ($this->curNode !== null); - } - - public function current() - { - return $this->curNode; - } - - public function key() - { - $method = method_exists($this->curNode, 'getPath') ? 'getPath' : 'getAncestors'; - $key = array(); - foreach ($this->curNode->$method() as $node) { - $key[] = $node->getPrimaryKey(); - } - return implode('.', $key); - } - - public function next() - { - $nextNode = null; - $method = method_exists($this->curNode, 'retrieveNextSibling') ? 'retrieveNextSibling' : 'getNextSibling'; - if ($this->valid()) { - while (null === $nextNode) { - if (null === $this->curNode) { - break; - } - - if ($this->curNode->hasNextSibling()) { - $nextNode = $this->curNode->$method(); - } else { - break; - } - } - $this->curNode = $nextNode; - } - return $this->curNode; - } - - public function hasChildren() - { - return $this->curNode->hasChildren(); - } - - public function getChildren() - { - $method = method_exists($this->curNode, 'retrieveFirstChild') ? 'retrieveFirstChild' : 'getFirstChild'; - return new NestedSetRecursiveIterator($this->curNode->$method()); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/om/NodeObject.php b/airtime_mvc/library/propel/runtime/lib/om/NodeObject.php deleted file mode 100644 index 9353fe671..000000000 --- a/airtime_mvc/library/propel/runtime/lib/om/NodeObject.php +++ /dev/null @@ -1,324 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.runtime.om - */ -interface NodeObject extends IteratorAggregate -{ - /** - * If object is saved without left/right values, set them as undefined (0) - * - * @param PropelPDO $con Connection to use. - * @return void - * @throws PropelException - */ - public function save(PropelPDO $con = null); - - /** - * Delete node and descendants - * - * @param PropelPDO $con Connection to use. - * @return void - * @throws PropelException - */ - public function delete(PropelPDO $con = null); - - /** - * Sets node properties to make it a root node. - * - * @return object The current object (for fluent API support) - * @throws PropelException - */ - public function makeRoot(); - - /** - * Gets the level if set, otherwise calculates this and returns it - * - * @param PropelPDO $con Connection to use. - * @return int - */ - public function getLevel(PropelPDO $con = null); - - /** - * Get the path to the node in the tree - * - * @param PropelPDO $con Connection to use. - * @return array - */ - public function getPath(PropelPDO $con = null); - - /** - * Gets the number of children for the node (direct descendants) - * - * @param PropelPDO $con Connection to use. - * @return int - */ - public function getNumberOfChildren(PropelPDO $con = null); - - /** - * Gets the total number of desceandants for the node - * - * @param PropelPDO $con Connection to use. - * @return int - */ - public function getNumberOfDescendants(PropelPDO $con = null); - - /** - * Gets the children for the node - * - * @param PropelPDO $con Connection to use. - * @return array - */ - public function getChildren(PropelPDO $con = null); - - /** - * Gets the descendants for the node - * - * @param PropelPDO $con Connection to use. - * @return array - */ - public function getDescendants(PropelPDO $con = null); - - /** - * Sets the level of the node in the tree - * - * @param int $v new value - * @return object The current object (for fluent API support) - */ - public function setLevel($level); - - /** - * Sets the children array of the node in the tree - * - * @param array of Node $children array of Propel node object - * @return object The current object (for fluent API support) - */ - public function setChildren(array $children); - - /** - * Sets the parentNode of the node in the tree - * - * @param Node $parent Propel node object - * @return object The current object (for fluent API support) - */ - public function setParentNode(NodeObject $parent = null); - - /** - * Sets the previous sibling of the node in the tree - * - * @param Node $node Propel node object - * @return object The current object (for fluent API support) - */ - public function setPrevSibling(NodeObject $node = null); - - /** - * Sets the next sibling of the node in the tree - * - * @param Node $node Propel node object - * @return object The current object (for fluent API support) - */ - public function setNextSibling(NodeObject $node = null); - - /** - * Determines if the node is the root node - * - * @return bool - */ - public function isRoot(); - - /** - * Determines if the node is a leaf node - * - * @return bool - */ - public function isLeaf(); - - /** - * Tests if object is equal to $node - * - * @param object $node Propel object for node to compare to - * @return bool - */ - public function isEqualTo(NodeObject $node); - - /** - * Tests if object has an ancestor - * - * @param PropelPDO $con Connection to use. - * @return bool - */ - public function hasParent(PropelPDO $con = null); - - /** - * Determines if the node has children / descendants - * - * @return bool - */ - public function hasChildren(); - - /** - * Determines if the node has previous sibling - * - * @param PropelPDO $con Connection to use. - * @return bool - */ - public function hasPrevSibling(PropelPDO $con = null); - - /** - * Determines if the node has next sibling - * - * @param PropelPDO $con Connection to use. - * @return bool - */ - public function hasNextSibling(PropelPDO $con = null); - - /** - * Gets ancestor for the given node if it exists - * - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveParent(PropelPDO $con = null); - - /** - * Gets first child if it exists - * - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveFirstChild(PropelPDO $con = null); - - /** - * Gets last child if it exists - * - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveLastChild(PropelPDO $con = null); - - /** - * Gets prev sibling for the given node if it exists - * - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrievePrevSibling(PropelPDO $con = null); - - /** - * Gets next sibling for the given node if it exists - * - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public function retrieveNextSibling(PropelPDO $con = null); - - /** - * Inserts as first child of destination node $parent - * - * @param object $parent Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return object The current object (for fluent API support) - */ - public function insertAsFirstChildOf(NodeObject $parent, PropelPDO $con = null); - - /** - * Inserts as last child of destination node $parent - * - * @param object $parent Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return object The current object (for fluent API support) - */ - public function insertAsLastChildOf(NodeObject $parent, PropelPDO $con = null); - - /** - * Inserts node as previous sibling to destination node $dest - * - * @param object $dest Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return object The current object (for fluent API support) - */ - public function insertAsPrevSiblingOf(NodeObject $dest, PropelPDO $con = null); - - /** - * Inserts node as next sibling to destination node $dest - * - * @param object $dest Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return object The current object (for fluent API support) - */ - public function insertAsNextSiblingOf(NodeObject $dest, PropelPDO $con = null); - - /** - * Moves node to be first child of $parent - * - * @param object $parent Propel object for destination node - * @param PropelPDO $con Connection to use. - * @return void - */ - public function moveToFirstChildOf(NodeObject $parent, PropelPDO $con = null); - - /** - * Moves node to be last child of $parent - * - * @param object $parent Propel object for destination node - * @param PropelPDO $con Connection to use. - * @return void - */ - public function moveToLastChildOf(NodeObject $parent, PropelPDO $con = null); - - /** - * Moves node to be prev sibling to $dest - * - * @param object $dest Propel object for destination node - * @param PropelPDO $con Connection to use. - * @return void - */ - public function moveToPrevSiblingOf(NodeObject $dest, PropelPDO $con = null); - - /** - * Moves node to be next sibling to $dest - * - * @param object $dest Propel object for destination node - * @param PropelPDO $con Connection to use. - * @return void - */ - public function moveToNextSiblingOf(NodeObject $dest, PropelPDO $con = null); - - /** - * Inserts node as parent of given node. - * - * @param object $node Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return void - * @throws Exception When trying to insert node as parent of a root node - */ - public function insertAsParentOf(NodeObject $node, PropelPDO $con = null); - - /** - * Wraps the getter for the scope value - * - * @return int - */ - public function getScopeIdValue(); - - /** - * Set the value of scope column - * - * @param int $v new value - * @return object The current object (for fluent API support) - */ - public function setScopeIdValue($v); -} // NodeObject diff --git a/airtime_mvc/library/propel/runtime/lib/om/Persistent.php b/airtime_mvc/library/propel/runtime/lib/om/Persistent.php deleted file mode 100644 index 02d6c20d9..000000000 --- a/airtime_mvc/library/propel/runtime/lib/om/Persistent.php +++ /dev/null @@ -1,108 +0,0 @@ - (Propel) - * @author John D. McNally (Torque) - * @author Fedor K. (Torque) - * @version $Revision: 1612 $ - * @package propel.runtime.om - */ -interface Persistent -{ - - /** - * getter for the object primaryKey. - * - * @return ObjectKey the object primaryKey as an Object - */ - public function getPrimaryKey(); - - /** - * Sets the PrimaryKey for the object. - * - * @param mixed $primaryKey The new PrimaryKey object or string (result of PrimaryKey.toString()). - * @return void - * @throws Exception, This method might throw an exceptions - */ - public function setPrimaryKey($primaryKey); - - - /** - * Returns whether the object has been modified, since it was - * last retrieved from storage. - * - * @return boolean True if the object has been modified. - */ - public function isModified(); - - /** - * Has specified column been modified? - * - * @param string $col - * @return boolean True if $col has been modified. - */ - public function isColumnModified($col); - - /** - * Returns whether the object has ever been saved. This will - * be false, if the object was retrieved from storage or was created - * and then saved. - * - * @return boolean True, if the object has never been persisted. - */ - public function isNew(); - - /** - * Setter for the isNew attribute. This method will be called - * by Propel-generated children and Peers. - * - * @param boolean $b the state of the object. - */ - public function setNew($b); - - /** - * Resets (to false) the "modified" state for this object. - * - * @return void - */ - public function resetModified(); - - /** - * Whether this object has been deleted. - * @return boolean The deleted state of this object. - */ - public function isDeleted(); - - /** - * Specify whether this object has been deleted. - * @param boolean $b The deleted state of this object. - * @return void - */ - public function setDeleted($b); - - /** - * Deletes the object. - * @param PropelPDO $con - * @return void - * @throws Exception - */ - public function delete(PropelPDO $con = null); - - /** - * Saves the object. - * @param PropelPDO $con - * @return void - * @throws Exception - */ - public function save(PropelPDO $con = null); -} diff --git a/airtime_mvc/library/propel/runtime/lib/om/PreOrderNodeIterator.php b/airtime_mvc/library/propel/runtime/lib/om/PreOrderNodeIterator.php deleted file mode 100644 index 0afde7f91..000000000 --- a/airtime_mvc/library/propel/runtime/lib/om/PreOrderNodeIterator.php +++ /dev/null @@ -1,78 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.om - */ -class PreOrderNodeIterator implements Iterator -{ - private $topNode = null; - - private $curNode = null; - - private $querydb = false; - - private $con = null; - - public function __construct($node, $opts) { - $this->topNode = $node; - $this->curNode = $node; - - if (isset($opts['con'])) - $this->con = $opts['con']; - - if (isset($opts['querydb'])) - $this->querydb = $opts['querydb']; - } - - public function rewind() { - $this->curNode = $this->topNode; - } - - public function valid() { - return ($this->curNode !== null); - } - - public function current() { - return $this->curNode; - } - - public function key() { - return $this->curNode->getNodePath(); - } - - public function next() { - - if ($this->valid()) - { - $nextNode = $this->curNode->getFirstChildNode($this->querydb, $this->con); - - while ($nextNode === null) - { - if ($this->curNode === null || $this->curNode->equals($this->topNode)) - break; - - $nextNode = $this->curNode->getSiblingNode(false, $this->querydb, $this->con); - - if ($nextNode === null) - $this->curNode = $this->curNode->getParentNode($this->querydb, $this->con); - } - - $this->curNode = $nextNode; - } - - return $this->curNode; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/query/Criteria.php b/airtime_mvc/library/propel/runtime/lib/query/Criteria.php deleted file mode 100644 index cbb3317f1..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/Criteria.php +++ /dev/null @@ -1,1561 +0,0 @@ - (Propel) - * @author Kaspars Jaudzems (Propel) - * @author Frank Y. Kim (Torque) - * @author John D. McNally (Torque) - * @author Brett McLaughlin (Torque) - * @author Eric Dobbs (Torque) - * @author Henning P. Schmiedehausen (Torque) - * @author Sam Joseph (Torque) - * @version $Revision: 1765 $ - * @package propel.runtime.query - */ -class Criteria implements IteratorAggregate -{ - - /** Comparison type. */ - const EQUAL = "="; - - /** Comparison type. */ - const NOT_EQUAL = "<>"; - - /** Comparison type. */ - const ALT_NOT_EQUAL = "!="; - - /** Comparison type. */ - const GREATER_THAN = ">"; - - /** Comparison type. */ - const LESS_THAN = "<"; - - /** Comparison type. */ - const GREATER_EQUAL = ">="; - - /** Comparison type. */ - const LESS_EQUAL = "<="; - - /** Comparison type. */ - const LIKE = " LIKE "; - - /** Comparison type. */ - const NOT_LIKE = " NOT LIKE "; - - /** PostgreSQL comparison type */ - const ILIKE = " ILIKE "; - - /** PostgreSQL comparison type */ - const NOT_ILIKE = " NOT ILIKE "; - - /** Comparison type. */ - const CUSTOM = "CUSTOM"; - - /** Comparison type for update */ - const CUSTOM_EQUAL = "CUSTOM_EQUAL"; - - /** Comparison type. */ - const DISTINCT = "DISTINCT"; - - /** Comparison type. */ - const IN = " IN "; - - /** Comparison type. */ - const NOT_IN = " NOT IN "; - - /** Comparison type. */ - const ALL = "ALL"; - - /** Comparison type. */ - const JOIN = "JOIN"; - - /** Binary math operator: AND */ - const BINARY_AND = "&"; - - /** Binary math operator: OR */ - const BINARY_OR = "|"; - - /** "Order by" qualifier - ascending */ - const ASC = "ASC"; - - /** "Order by" qualifier - descending */ - const DESC = "DESC"; - - /** "IS NULL" null comparison */ - const ISNULL = " IS NULL "; - - /** "IS NOT NULL" null comparison */ - const ISNOTNULL = " IS NOT NULL "; - - /** "CURRENT_DATE" ANSI SQL function */ - const CURRENT_DATE = "CURRENT_DATE"; - - /** "CURRENT_TIME" ANSI SQL function */ - const CURRENT_TIME = "CURRENT_TIME"; - - /** "CURRENT_TIMESTAMP" ANSI SQL function */ - const CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP"; - - /** "LEFT JOIN" SQL statement */ - const LEFT_JOIN = "LEFT JOIN"; - - /** "RIGHT JOIN" SQL statement */ - const RIGHT_JOIN = "RIGHT JOIN"; - - /** "INNER JOIN" SQL statement */ - const INNER_JOIN = "INNER JOIN"; - - /** logical OR operator */ - const LOGICAL_OR = "OR"; - - /** logical AND operator */ - const LOGICAL_AND = "AND"; - - protected $ignoreCase = false; - protected $singleRecord = false; - - /** - * Storage of select data. Collection of column names. - * @var array - */ - protected $selectColumns = array(); - - /** - * Storage of aliased select data. Collection of column names. - * @var array - */ - protected $asColumns = array(); - - /** - * Storage of select modifiers data. Collection of modifier names. - * @var array - */ - protected $selectModifiers = array(); - - /** - * Storage of conditions data. Collection of Criterion objects. - * @var array - */ - protected $map = array(); - - /** - * Storage of ordering data. Collection of column names. - * @var array - */ - protected $orderByColumns = array(); - - /** - * Storage of grouping data. Collection of column names. - * @var array - */ - protected $groupByColumns = array(); - - /** - * Storage of having data. - * @var Criterion - */ - protected $having = null; - - /** - * Storage of join data. colleciton of Join objects. - * @var array - */ - protected $joins = array(); - - /** - * The name of the database. - * @var string - */ - protected $dbName; - - /** - * The primary table for this Criteria. - * Useful in cases where there are no select or where - * columns. - * @var string - */ - protected $primaryTableName; - - /** The name of the database as given in the contructor. */ - protected $originalDbName; - - /** - * To limit the number of rows to return. 0 means return all - * rows. - */ - protected $limit = 0; - - /** To start the results at a row other than the first one. */ - protected $offset = 0; - - /** - * Comment to add to the SQL query - * @var string - */ - protected $queryComment; - - // flag to note that the criteria involves a blob. - protected $blobFlag = null; - - protected $aliases = array(); - - protected $useTransaction = false; - - /** - * Storage for Criterions expected to be combined - * @var array - */ - protected $namedCriterions = array(); - - /** - * Creates a new instance with the default capacity which corresponds to - * the specified database. - * - * @param dbName The dabase name. - */ - public function __construct($dbName = null) - { - $this->setDbName($dbName); - $this->originalDbName = $dbName; - } - - /** - * Implementing SPL IteratorAggregate interface. This allows - * you to foreach () over a Criteria object. - */ - public function getIterator() - { - return new CriterionIterator($this); - } - - /** - * Get the criteria map, i.e. the array of Criterions - * @return array - */ - public function getMap() - { - return $this->map; - } - - /** - * Brings this criteria back to its initial state, so that it - * can be reused as if it was new. Except if the criteria has grown in - * capacity, it is left at the current capacity. - * @return void - */ - public function clear() - { - $this->map = array(); - $this->namedCriterions = array(); - $this->ignoreCase = false; - $this->singleRecord = false; - $this->selectModifiers = array(); - $this->selectColumns = array(); - $this->orderByColumns = array(); - $this->groupByColumns = array(); - $this->having = null; - $this->asColumns = array(); - $this->joins = array(); - $this->dbName = $this->originalDbName; - $this->offset = 0; - $this->limit = -1; - $this->blobFlag = null; - $this->aliases = array(); - $this->useTransaction = false; - } - - /** - * Add an AS clause to the select columns. Usage: - * - * - * Criteria myCrit = new Criteria(); - * myCrit->addAsColumn("alias", "ALIAS(".MyPeer::ID.")"); - * - * - * @param string $name Wanted Name of the column (alias). - * @param string $clause SQL clause to select from the table - * - * If the name already exists, it is replaced by the new clause. - * - * @return Criteria A modified Criteria object. - */ - public function addAsColumn($name, $clause) - { - $this->asColumns[$name] = $clause; - return $this; - } - - /** - * Get the column aliases. - * - * @return array An assoc array which map the column alias names - * to the alias clauses. - */ - public function getAsColumns() - { - return $this->asColumns; - } - - /** - * Returns the column name associated with an alias (AS-column). - * - * @param string $alias - * @return string $string - */ - public function getColumnForAs($as) - { - if (isset($this->asColumns[$as])) { - return $this->asColumns[$as]; - } - } - - /** - * Allows one to specify an alias for a table that can - * be used in various parts of the SQL. - * - * @param string $alias - * @param string $table - * - * @return Criteria A modified Criteria object. - */ - public function addAlias($alias, $table) - { - $this->aliases[$alias] = $table; - - return $this; - } - - /** - * Remove an alias for a table (useful when merging Criterias). - * - * @param string $alias - * - * @return Criteria A modified Criteria object. - */ - public function removeAlias($alias) - { - unset($this->aliases[$alias]); - - return $this; - } - - /** - * Returns the aliases for this Criteria - * - * @return array - */ - public function getAliases() - { - return $this->aliases; - } - - /** - * Returns the table name associated with an alias. - * - * @param string $alias - * @return string $string - */ - public function getTableForAlias($alias) - { - if (isset($this->aliases[$alias])) { - return $this->aliases[$alias]; - } - } - - /** - * Get the keys of the criteria map, i.e. the list of columns bearing a condition - * - * print_r($c->keys()); - * => array('book.price', 'book.title', 'author.first_name') - * - * - * @return array - */ - public function keys() - { - return array_keys($this->map); - } - - /** - * Does this Criteria object contain the specified key? - * - * @param string $column [table.]column - * @return boolean True if this Criteria object contain the specified key. - */ - public function containsKey($column) - { - // must use array_key_exists() because the key could - // exist but have a NULL value (that'd be valid). - return array_key_exists($column, $this->map); - } - - /** - * Does this Criteria object contain the specified key and does it have a value set for the key - * - * @param string $column [table.]column - * @return boolean True if this Criteria object contain the specified key and a value for that key - */ - public function keyContainsValue($column) - { - // must use array_key_exists() because the key could - // exist but have a NULL value (that'd be valid). - return (array_key_exists($column, $this->map) && ($this->map[$column]->getValue() !== null) ); - } - - /** - * Whether this Criteria has any where columns. - * - * This counts conditions added with the add() method. - * - * @return boolean - * @see add() - */ - public function hasWhereClause() - { - return !empty($this->map); - } - - /** - * Will force the sql represented by this criteria to be executed within - * a transaction. This is here primarily to support the oid type in - * postgresql. Though it can be used to require any single sql statement - * to use a transaction. - * @return void - */ - public function setUseTransaction($v) - { - $this->useTransaction = (boolean) $v; - } - - /** - * Whether the sql command specified by this criteria must be wrapped - * in a transaction. - * - * @return boolean - */ - public function isUseTransaction() - { - return $this->useTransaction; - } - - /** - * Method to return criteria related to columns in a table. - * - * Make sure you call containsKey($column) prior to calling this method, - * since no check on the existence of the $column is made in this method. - * - * @param string $column Column name. - * @return Criterion A Criterion object. - */ - public function getCriterion($column) - { - return $this->map[$column]; - } - - /** - * Method to return the latest Criterion in a table. - * - * @return Criterion A Criterion or null no Criterion is added. - */ - public function getLastCriterion() - { - if($cnt = count($this->map)) { - $map = array_values($this->map); - return $map[$cnt - 1]; - } - return null; - } - - /** - * Method to return criterion that is not added automatically - * to this Criteria. This can be used to chain the - * Criterions to form a more complex where clause. - * - * @param string $column Full name of column (for example TABLE.COLUMN). - * @param mixed $value - * @param string $comparison - * @return Criterion - */ - public function getNewCriterion($column, $value = null, $comparison = self::EQUAL) - { - return new Criterion($this, $column, $value, $comparison); - } - - /** - * Method to return a String table name. - * - * @param string $name Name of the key. - * @return string The value of the object at key. - */ - public function getColumnName($name) - { - if (isset($this->map[$name])) { - return $this->map[$name]->getColumn(); - } - return null; - } - - /** - * Shortcut method to get an array of columns indexed by table. - * - * print_r($c->getTablesColumns()); - * => array( - * 'book' => array('book.price', 'book.title'), - * 'author' => array('author.first_name') - * ) - * - * - * @return array array(table => array(table.column1, table.column2)) - */ - public function getTablesColumns() - { - $tables = array(); - foreach ($this->keys() as $key) { - $tableName = substr($key, 0, strrpos($key, '.' )); - $tables[$tableName][] = $key; - } - return $tables; - } - - /** - * Method to return a comparison String. - * - * @param string $key String name of the key. - * @return string A String with the value of the object at key. - */ - public function getComparison($key) - { - if ( isset ( $this->map[$key] ) ) { - return $this->map[$key]->getComparison(); - } - return null; - } - - /** - * Get the Database(Map) name. - * - * @return string A String with the Database(Map) name. - */ - public function getDbName() - { - return $this->dbName; - } - - /** - * Set the DatabaseMap name. If null is supplied, uses value - * provided by Propel::getDefaultDB(). - * - * @param string $dbName The Database (Map) name. - * @return void - */ - public function setDbName($dbName = null) - { - $this->dbName = ($dbName === null ? Propel::getDefaultDB() : $dbName); - } - - /** - * Get the primary table for this Criteria. - * - * This is useful for cases where a Criteria may not contain - * any SELECT columns or WHERE columns. This must be explicitly - * set, of course, in order to be useful. - * - * @return string - */ - public function getPrimaryTableName() - { - return $this->primaryTableName; - } - - /** - * Sets the primary table for this Criteria. - * - * This is useful for cases where a Criteria may not contain - * any SELECT columns or WHERE columns. This must be explicitly - * set, of course, in order to be useful. - * - * @param string $v - */ - public function setPrimaryTableName($tableName) - { - $this->primaryTableName = $tableName; - } - - /** - * Method to return a String table name. - * - * @param string $name The name of the key. - * @return string The value of table for criterion at key. - */ - public function getTableName($name) - { - if (isset($this->map[$name])) { - return $this->map[$name]->getTable(); - } - return null; - } - - /** - * Method to return the value that was added to Criteria. - * - * @param string $name A String with the name of the key. - * @return mixed The value of object at key. - */ - public function getValue($name) - { - if (isset($this->map[$name])) { - return $this->map[$name]->getValue(); - } - return null; - } - - /** - * An alias to getValue() -- exposing a Hashtable-like interface. - * - * @param string $key An Object. - * @return mixed The value within the Criterion (not the Criterion object). - */ - public function get($key) - { - return $this->getValue($key); - } - - /** - * Overrides Hashtable put, so that this object is returned - * instead of the value previously in the Criteria object. - * The reason is so that it more closely matches the behavior - * of the add() methods. If you want to get the previous value - * then you should first Criteria.get() it yourself. Note, if - * you attempt to pass in an Object that is not a String, it will - * throw a NPE. The reason for this is that none of the add() - * methods support adding anything other than a String as a key. - * - * @param string $key - * @param mixed $value - * @return Instance of self. - */ - public function put($key, $value) - { - return $this->add($key, $value); - } - - /** - * Copies all of the mappings from the specified Map to this Criteria - * These mappings will replace any mappings that this Criteria had for any - * of the keys currently in the specified Map. - * - * if the map was another Criteria, its attributes are copied to this - * Criteria, overwriting previous settings. - * - * @param mixed $t Mappings to be stored in this map. - */ - public function putAll($t) - { - if (is_array($t)) { - foreach ($t as $key=>$value) { - if ($value instanceof Criterion) { - $this->map[$key] = $value; - } else { - $this->put($key, $value); - } - } - } elseif ($t instanceof Criteria) { - $this->joins = $t->joins; - } - } - - /** - * This method adds a new criterion to the list of criterias. - * If a criterion for the requested column already exists, it is - * replaced. If is used as follow: - * - * - * $crit = new Criteria(); - * $crit->add($column, $value, Criteria::GREATER_THAN); - * - * - * Any comparison can be used. - * - * The name of the table must be used implicitly in the column name, - * so the Column name must be something like 'TABLE.id'. - * - * @param string $critOrColumn The column to run the comparison on, or Criterion object. - * @param mixed $value - * @param string $comparison A String. - * - * @return A modified Criteria object. - */ - public function add($p1, $value = null, $comparison = null) - { - if ($p1 instanceof Criterion) { - $this->map[$p1->getTable() . '.' . $p1->getColumn()] = $p1; - } else { - $criterion = new Criterion($this, $p1, $value, $comparison); - $this->map[$p1] = $criterion; - } - return $this; - } - - /** - * This method creates a new criterion but keeps it for later use with combine() - * Until combine() is called, the condition is not added to the query - * - * - * $crit = new Criteria(); - * $crit->addCond('cond1', $column1, $value1, Criteria::GREATER_THAN); - * $crit->addCond('cond2', $column2, $value2, Criteria::EQUAL); - * $crit->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - * - * - * Any comparison can be used. - * - * The name of the table must be used implicitly in the column name, - * so the Column name must be something like 'TABLE.id'. - * - * @param string $name name to combine the criterion later - * @param string $p1 The column to run the comparison on, or Criterion object. - * @param mixed $value - * @param string $comparison A String. - * - * @return A modified Criteria object. - */ - public function addCond($name, $p1, $value = null, $comparison = null) - { - if ($p1 instanceof Criterion) { - $this->namedCriterions[$name] = $p1; - } else { - $criterion = new Criterion($this, $p1, $value, $comparison); - $this->namedCriterions[$name] = $criterion; - } - return $this; - } - - /** - * Combine several named criterions with a logical operator - * - * @param array $criterions array of the name of the criterions to combine - * @param string $operator logical operator, either Criteria::LOGICAL_AND, or Criteria::LOGICAL_OR - * @param string $name optional name to combine the criterion later - */ - public function combine($criterions = array(), $operator = self::LOGICAL_AND, $name = null) - { - $operatorMethod = (strtoupper($operator) == self::LOGICAL_AND) ? 'addAnd' : 'addOr'; - $namedCriterions = array(); - foreach ($criterions as $key) { - if (array_key_exists($key, $this->namedCriterions)) { - $namedCriterions[]= $this->namedCriterions[$key]; - unset($this->namedCriterions[$key]); - } else { - throw new PropelException('Cannot combine unknown condition ' . $key); - } - } - $firstCriterion = array_shift($namedCriterions); - foreach ($namedCriterions as $criterion) { - $firstCriterion->$operatorMethod($criterion); - } - if ($name === null) { - $this->add($firstCriterion, null, null); - } else { - $this->addCond($name, $firstCriterion, null, null); - } - - return $this; - } - - /** - * This is the way that you should add a join of two tables. - * Example usage: - * - * $c->addJoin(ProjectPeer::ID, FooPeer::PROJECT_ID, Criteria::LEFT_JOIN); - * // LEFT JOIN FOO ON PROJECT.ID = FOO.PROJECT_ID - * - * - * @param mixed $left A String with the left side of the join. - * @param mixed $right A String with the right side of the join. - * @param mixed $operator A String with the join operator - * among Criteria::INNER_JOIN, Criteria::LEFT_JOIN, - * and Criteria::RIGHT_JOIN - * - * @return Criteria A modified Criteria object. - */ - public function addJoin($left, $right, $operator = null) - { - $join = new Join(); - if (!is_array($left)) { - // simple join - $join->addCondition($left, $right); - } else { - // join with multiple conditions - // deprecated: use addMultipleJoin() instead - foreach ($left as $key => $value) - { - $join->addCondition($value, $right[$key]); - } - } - $join->setJoinType($operator); - - return $this->addJoinObject($join); - } - - /** - * Add a join with multiple conditions - * @see http://propel.phpdb.org/trac/ticket/167, http://propel.phpdb.org/trac/ticket/606 - * - * Example usage: - * $c->addMultipleJoin(array( - * array(LeftPeer::LEFT_COLUMN, RightPeer::RIGHT_COLUMN), // if no third argument, defaults to Criteria::EQUAL - * array(FoldersPeer::alias( 'fo', FoldersPeer::LFT ), FoldersPeer::alias( 'parent', FoldersPeer::RGT ), Criteria::LESS_EQUAL ) - * ), - * Criteria::LEFT_JOIN - * ); - * - * @see addJoin() - * @param array $conditions An array of conditions, each condition being an array (left, right, operator) - * @param string $joinType A String with the join operator. Defaults to an implicit join. - * - * @return Criteria A modified Criteria object. - */ - public function addMultipleJoin($conditions, $joinType = null) - { - $join = new Join(); - foreach ($conditions as $condition) { - $join->addCondition($condition[0], $condition[1], isset($condition[2]) ? $condition[2] : Criteria::EQUAL); - } - $join->setJoinType($joinType); - - return $this->addJoinObject($join); - } - - /** - * Add a join object to the Criteria - * - * @param Join $join A join object - * - * @return Criteria A modified Criteria object - */ - public function addJoinObject(Join $join) - { - if (!in_array($join, $this->joins)) { // compare equality, NOT identity - $this->joins[] = $join; - } - return $this; - } - - - /** - * Get the array of Joins. - * @return array Join[] - */ - public function getJoins() - { - return $this->joins; - } - - /** - * Adds "ALL" modifier to the SQL statement. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setAll() - { - $this->removeSelectModifier(self::DISTINCT); - $this->addSelectModifier(self::ALL); - - return $this; - } - - /** - * Adds "DISTINCT" modifier to the SQL statement. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setDistinct() - { - $this->removeSelectModifier(self::ALL); - $this->addSelectModifier(self::DISTINCT); - - return $this; - } - - /** - * Adds a modifier to the SQL statement. - * e.g. self::ALL, self::DISTINCT, 'SQL_CALC_FOUND_ROWS', 'HIGH_PRIORITY', etc. - * - * @param string $modifier The modifier to add - * - * @return Criteria Modified Criteria object (for fluent API) - */ - public function addSelectModifier($modifier) - { - //only allow the keyword once - if (!$this->hasSelectModifier($modifier)) { - $this->selectModifiers[] = $modifier; - } - - return $this; - } - - /** - * Removes a modifier to the SQL statement. - * Checks for existence before removal - * - * @param string $modifier The modifier to add - * - * @return Criteria Modified Criteria object (for fluent API) - */ - public function removeSelectModifier($modifier) - { - $this->selectModifiers = array_values(array_diff($this->selectModifiers, array($modifier))); - - return $this; - } - - /** - * Checks the existence of a SQL select modifier - * - * @param string $modifier The modifier to add - * - * @return bool - */ - public function hasSelectModifier($modifier) - { - return in_array($modifier, $this->selectModifiers); - } - - /** - * Sets ignore case. - * - * @param boolean $b True if case should be ignored. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setIgnoreCase($b) - { - $this->ignoreCase = (boolean) $b; - return $this; - } - - /** - * Is ignore case on or off? - * - * @return boolean True if case is ignored. - */ - public function isIgnoreCase() - { - return $this->ignoreCase; - } - - /** - * Set single record? Set this to true if you expect the query - * to result in only a single result record (the default behaviour is to - * throw a PropelException if multiple records are returned when the query - * is executed). This should be used in situations where returning multiple - * rows would indicate an error of some sort. If your query might return - * multiple records but you are only interested in the first one then you - * should be using setLimit(1). - * - * @param boolean $b Set to TRUE if you expect the query to select just one record. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setSingleRecord($b) - { - $this->singleRecord = (boolean) $b; - return $this; - } - - /** - * Is single record? - * - * @return boolean True if a single record is being returned. - */ - public function isSingleRecord() - { - return $this->singleRecord; - } - - /** - * Set limit. - * - * @param limit An int with the value for limit. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setLimit($limit) - { - // TODO: do we enforce int here? 32bit issue if we do - $this->limit = $limit; - return $this; - } - - /** - * Get limit. - * - * @return int An int with the value for limit. - */ - public function getLimit() - { - return $this->limit; - } - - /** - * Set offset. - * - * @param int $offset An int with the value for offset. (Note this values is - * cast to a 32bit integer and may result in truncatation) - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setOffset($offset) - { - $this->offset = (int) $offset; - return $this; - } - - /** - * Get offset. - * - * @return An int with the value for offset. - */ - public function getOffset() - { - return $this->offset; - } - - /** - * Add select column. - * - * @param string $name Name of the select column. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function addSelectColumn($name) - { - $this->selectColumns[] = $name; - return $this; - } - - /** - * Set the query comment, that appears after the first verb in the SQL query - * - * @param string $comment The comment to add to the query, without comment sign - * @return Criteria Modified Criteria object (for fluent API) - */ - public function setComment($comment = null) - { - $this->queryComment = $comment; - - return $this; - } - - /** - * Get the query comment, that appears after the first verb in the SQL query - * - * @return string The comment to add to the query, without comment sign - */ - public function getComment() - { - return $this->queryComment; - } - - /** - * Whether this Criteria has any select columns. - * - * This will include columns added with addAsColumn() method. - * - * @return boolean - * @see addAsColumn() - * @see addSelectColumn() - */ - public function hasSelectClause() - { - return (!empty($this->selectColumns) || !empty($this->asColumns)); - } - - /** - * Get select columns. - * - * @return array An array with the name of the select columns. - */ - public function getSelectColumns() - { - return $this->selectColumns; - } - - /** - * Clears current select columns. - * - * @return Criteria Modified Criteria object (for fluent API) - */ - public function clearSelectColumns() - { - $this->selectColumns = $this->asColumns = array(); - return $this; - } - - /** - * Get select modifiers. - * - * @return An array with the select modifiers. - */ - public function getSelectModifiers() - { - return $this->selectModifiers; - } - - /** - * Add group by column name. - * - * @param string $groupBy The name of the column to group by. - * @return A modified Criteria object. - */ - public function addGroupByColumn($groupBy) - { - $this->groupByColumns[] = $groupBy; - return $this; - } - - /** - * Add order by column name, explicitly specifying ascending. - * - * @param name The name of the column to order by. - * @return A modified Criteria object. - */ - public function addAscendingOrderByColumn($name) - { - $this->orderByColumns[] = $name . ' ' . self::ASC; - return $this; - } - - /** - * Add order by column name, explicitly specifying descending. - * - * @param string $name The name of the column to order by. - * @return Criteria Modified Criteria object (for fluent API) - */ - public function addDescendingOrderByColumn($name) - { - $this->orderByColumns[] = $name . ' ' . self::DESC; - return $this; - } - - /** - * Get order by columns. - * - * @return array An array with the name of the order columns. - */ - public function getOrderByColumns() - { - return $this->orderByColumns; - } - - /** - * Clear the order-by columns. - * - * @return Criteria Modified Criteria object (for fluent API) - */ - public function clearOrderByColumns() - { - $this->orderByColumns = array(); - return $this; - } - - /** - * Clear the group-by columns. - * - * @return Criteria - */ - public function clearGroupByColumns() - { - $this->groupByColumns = array(); - return $this; - } - - /** - * Get group by columns. - * - * @return array - */ - public function getGroupByColumns() - { - return $this->groupByColumns; - } - - /** - * Get Having Criterion. - * - * @return Criterion A Criterion object that is the having clause. - */ - public function getHaving() - { - return $this->having; - } - - /** - * Remove an object from the criteria. - * - * @param string $key A string with the key to be removed. - * @return mixed The removed value. - */ - public function remove($key) - { - if ( isset ( $this->map[$key] ) ) { - $removed = $this->map[$key]; - unset ( $this->map[$key] ); - if ( $removed instanceof Criterion ) { - return $removed->getValue(); - } - return $removed; - } - } - - /** - * Build a string representation of the Criteria. - * - * @return string A String with the representation of the Criteria. - */ - public function toString() - { - - $sb = "Criteria:"; - try { - - $params = array(); - $sb .= "\nSQL (may not be complete): " - . BasePeer::createSelectSql($this, $params); - - $sb .= "\nParams: "; - $paramstr = array(); - foreach ($params as $param) { - $paramstr[] = $param['table'] . '.' . $param['column'] . ' => ' . var_export($param['value'], true); - } - $sb .= implode(", ", $paramstr); - - } catch (Exception $exc) { - $sb .= "(Error: " . $exc->getMessage() . ")"; - } - - return $sb; - } - - /** - * Returns the size (count) of this criteria. - * @return int - */ - public function size() - { - return count($this->map); - } - - /** - * This method checks another Criteria to see if they contain - * the same attributes and hashtable entries. - * @return boolean - */ - public function equals($crit) - { - if ($crit === null || !($crit instanceof Criteria)) { - return false; - } elseif ($this === $crit) { - return true; - } elseif ($this->size() === $crit->size()) { - - // Important: nested criterion objects are checked - - $criteria = $crit; // alias - if ($this->offset === $criteria->getOffset() - && $this->limit === $criteria->getLimit() - && $this->ignoreCase === $criteria->isIgnoreCase() - && $this->singleRecord === $criteria->isSingleRecord() - && $this->dbName === $criteria->getDbName() - && $this->selectModifiers === $criteria->getSelectModifiers() - && $this->selectColumns === $criteria->getSelectColumns() - && $this->asColumns === $criteria->getAsColumns() - && $this->orderByColumns === $criteria->getOrderByColumns() - && $this->groupByColumns === $criteria->getGroupByColumns() - && $this->aliases === $criteria->getAliases() - ) // what about having ?? - { - foreach ($criteria->keys() as $key) { - if ($this->containsKey($key)) { - $a = $this->getCriterion($key); - $b = $criteria->getCriterion($key); - if (!$a->equals($b)) { - return false; - } - } else { - return false; - } - } - $joins = $criteria->getJoins(); - if (count($joins) != count($this->joins)) { - return false; - } - foreach ($joins as $key => $join) { - if (!$join->equals($this->joins[$key])) { - return false; - } - } - return true; - } else { - return false; - } - } - return false; - } - - /** - * Add the content of a Criteria to the current Criteria - * In case of conflict, the current Criteria keeps its properties - * - * @param Criteria $criteria The criteria to read properties from - * @param string $operator The logical operator used to combine conditions - * Defaults to Criteria::LOGICAL_AND, also accapts Criteria::LOGICAL_OR - * - * @return Criteria The current criteria object - */ - public function mergeWith(Criteria $criteria, $operator = Criteria::LOGICAL_AND) - { - // merge limit - $limit = $criteria->getLimit(); - if($limit != 0 && $this->getLimit() == 0) { - $this->limit = $limit; - } - - // merge offset - $offset = $criteria->getOffset(); - if($offset != 0 && $this->getOffset() == 0) { - $this->offset = $offset; - } - - // merge select modifiers - $selectModifiers = $criteria->getSelectModifiers(); - if ($selectModifiers && ! $this->selectModifiers){ - $this->selectModifiers = $selectModifiers; - } - - // merge select columns - $this->selectColumns = array_merge($this->getSelectColumns(), $criteria->getSelectColumns()); - - // merge as columns - $commonAsColumns = array_intersect_key($this->getAsColumns(), $criteria->getAsColumns()); - if (!empty($commonAsColumns)) { - throw new PropelException('The given criteria contains an AsColumn with an alias already existing in the current object'); - } - $this->asColumns = array_merge($this->getAsColumns(), $criteria->getAsColumns()); - - // merge orderByColumns - $orderByColumns = array_merge($this->getOrderByColumns(), $criteria->getOrderByColumns()); - $this->orderByColumns = array_unique($orderByColumns); - - // merge groupByColumns - $groupByColumns = array_merge($this->getGroupByColumns(), $criteria->getGroupByColumns()); - $this->groupByColumns = array_unique($groupByColumns); - - // merge where conditions - if ($operator == Criteria::LOGICAL_AND) { - foreach ($criteria->getMap() as $key => $criterion) { - if ($this->containsKey($key)) { - $this->addAnd($criterion); - } else { - $this->add($criterion); - } - } - } else { - foreach ($criteria->getMap() as $key => $criterion) { - $this->addOr($criterion); - } - } - - - // merge having - if ($having = $criteria->getHaving()) { - if ($this->getHaving()) { - $this->addHaving($this->getHaving()->addAnd($having)); - } else { - $this->addHaving($having); - } - } - - // merge alias - $commonAliases = array_intersect_key($this->getAliases(), $criteria->getAliases()); - if (!empty($commonAliases)) { - throw new PropelException('The given criteria contains an alias already existing in the current object'); - } - $this->aliases = array_merge($this->getAliases(), $criteria->getAliases()); - - // merge join - $this->joins = array_merge($this->getJoins(), $criteria->getJoins()); - - return $this; - } - - /** - * This method adds a prepared Criterion object to the Criteria as a having clause. - * You can get a new, empty Criterion object with the - * getNewCriterion() method. - * - *

- * - * $crit = new Criteria(); - * $c = $crit->getNewCriterion(BasePeer::ID, 5, Criteria::LESS_THAN); - * $crit->addHaving($c); - * - * - * @param having A Criterion object - * - * @return A modified Criteria object. - */ - public function addHaving(Criterion $having) - { - $this->having = $having; - return $this; - } - - /** - * If a criterion for the requested column already exists, the condition is "AND"ed to the existing criterion (necessary for Propel 1.4 compatibility). - * If no criterion for the requested column already exists, the condition is "AND"ed to the latest criterion. - * If no criterion exist, the condition is added a new criterion - * - * Any comparison can be used. - * - * Supports a number of different signatures: - * - addAnd(column, value, comparison) - * - addAnd(column, value) - * - addAnd(Criterion) - * - * @return Criteria A modified Criteria object. - */ - public function addAnd($p1, $p2 = null, $p3 = null, $preferColumnCondition = true) - { - $criterion = ($p1 instanceof Criterion) ? $p1 : new Criterion($this, $p1, $p2, $p3); - - $key = $criterion->getTable() . '.' . $criterion->getColumn(); - if ($preferColumnCondition && $this->containsKey($key)) { - // FIXME: addAnd() operates preferably on existing conditions on the same column - // this may cause unexpected results, but it's there for BC with Propel 14 - $this->getCriterion($key)->addAnd($criterion); - } else { - // simply add the condition to the list - this is the expected behavior - $this->add($criterion); - } - - return $this; - } - - /** - * If a criterion for the requested column already exists, the condition is "OR"ed to the existing criterion (necessary for Propel 1.4 compatibility). - * If no criterion for the requested column already exists, the condition is "OR"ed to the latest criterion. - * If no criterion exist, the condition is added a new criterion - * - * Any comparison can be used. - * - * Supports a number of different signatures: - * - addOr(column, value, comparison) - * - addOr(column, value) - * - addOr(Criterion) - * - * @return Criteria A modified Criteria object. - */ - public function addOr($p1, $p2 = null, $p3 = null, $preferColumnCondition = true) - { - $rightCriterion = ($p1 instanceof Criterion) ? $p1 : new Criterion($this, $p1, $p2, $p3); - - $key = $rightCriterion->getTable() . '.' . $rightCriterion->getColumn(); - if ($preferColumnCondition && $this->containsKey($key)) { - // FIXME: addOr() operates preferably on existing conditions on the same column - // this may cause unexpected results, but it's there for BC with Propel 14 - $leftCriterion = $this->getCriterion($key); - } else { - // fallback to the latest condition - this is the expected behavior - $leftCriterion = $this->getLastCriterion(); - } - - if ($leftCriterion !== null) { - // combine the given criterion with the existing one with an 'OR' - $leftCriterion->addOr($rightCriterion); - } else { - // nothing to do OR / AND with, so make it first condition - $this->add($rightCriterion); - } - - return $this; - } - - // Fluid Conditions - - /** - * Returns the current object if the condition is true, - * or a PropelConditionalProxy instance otherwise. - * Allows for conditional statements in a fluid interface. - * - * @param bool $cond - * - * @return PropelConditionalProxy|Criteria - */ - public function _if($cond) - { - if($cond) { - return $this; - } else { - return new PropelConditionalProxy($this); - } - } - - /** - * Returns a PropelConditionalProxy instance. - * Allows for conditional statements in a fluid interface. - * - * @param bool $cond ignored - * - * @return PropelConditionalProxy - */ - public function _elseif($cond) - { - return new PropelConditionalProxy($this); - } - - /** - * Returns a PropelConditionalProxy instance. - * Allows for conditional statements in a fluid interface. - * - * @return PropelConditionalProxy - */ - public function _else() - { - return new PropelConditionalProxy($this); - } - - /** - * Returns the current object - * Allows for conditional statements in a fluid interface. - * - * @return Criteria - */ - public function _endif() - { - return $this; - } - - /** - * Ensures deep cloning of attached objects - */ - public function __clone() - { - foreach ($this->map as $key => $criterion) { - $this->map[$key] = clone $criterion; - } - foreach ($this->joins as $key => $join) { - $this->joins[$key] = clone $join; - } - if (null !== $this->having) { - $this->having = clone $this->having; - } - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/query/Criterion.php b/airtime_mvc/library/propel/runtime/lib/query/Criterion.php deleted file mode 100644 index cc412bc05..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/Criterion.php +++ /dev/null @@ -1,543 +0,0 @@ - (Propel) - * @version $Revision: 1740 $ - * @package propel.runtime.query - */ -class Criterion -{ - - const UND = " AND "; - const ODER = " OR "; - - /** Value of the CO. */ - protected $value; - - /** Comparison value. - * @var SqlEnum - */ - protected $comparison; - - /** Table name. */ - protected $table; - - /** Real table name */ - protected $realtable; - - /** Column name. */ - protected $column; - - /** flag to ignore case in comparison */ - protected $ignoreStringCase = false; - - /** - * The DBAdaptor which might be used to get db specific - * variations of sql. - */ - protected $db; - - /** - * other connected criteria and their conjunctions. - */ - protected $clauses = array(); - protected $conjunctions = array(); - - /** "Parent" Criteria class */ - protected $parent; - - /** - * Create a new instance. - * - * @param Criteria $parent The outer class (this is an "inner" class). - * @param string $column TABLE.COLUMN format. - * @param mixed $value - * @param string $comparison - */ - public function __construct(Criteria $outer, $column, $value, $comparison = null) - { - $this->value = $value; - $dotPos = strrpos($column, '.'); - if ($dotPos === false) { - // no dot => aliased column - $this->table = null; - $this->column = $column; - } else { - $this->table = substr($column, 0, $dotPos); - $this->column = substr($column, $dotPos + 1); - } - $this->comparison = ($comparison === null) ? Criteria::EQUAL : $comparison; - $this->init($outer); - } - - /** - * Init some properties with the help of outer class - * @param Criteria $criteria The outer class - */ - public function init(Criteria $criteria) - { - // init $this->db - try { - $db = Propel::getDB($criteria->getDbName()); - $this->setDB($db); - } catch (Exception $e) { - // we are only doing this to allow easier debugging, so - // no need to throw up the exception, just make note of it. - Propel::log("Could not get a DBAdapter, sql may be wrong", Propel::LOG_ERR); - } - - // init $this->realtable - $realtable = $criteria->getTableForAlias($this->table); - $this->realtable = $realtable ? $realtable : $this->table; - - } - - /** - * Get the column name. - * - * @return string A String with the column name. - */ - public function getColumn() - { - return $this->column; - } - - /** - * Set the table name. - * - * @param name A String with the table name. - * @return void - */ - public function setTable($name) - { - $this->table = $name; - } - - /** - * Get the table name. - * - * @return string A String with the table name. - */ - public function getTable() - { - return $this->table; - } - - /** - * Get the comparison. - * - * @return string A String with the comparison. - */ - public function getComparison() - { - return $this->comparison; - } - - /** - * Get the value. - * - * @return mixed An Object with the value. - */ - public function getValue() - { - return $this->value; - } - - /** - * Get the value of db. - * The DBAdapter which might be used to get db specific - * variations of sql. - * @return DBAdapter value of db. - */ - public function getDB() - { - return $this->db; - } - - /** - * Set the value of db. - * The DBAdapter might be used to get db specific variations of sql. - * @param DBAdapter $v Value to assign to db. - * @return void - */ - public function setDB(DBAdapter $v) - { - $this->db = $v; - foreach ( $this->clauses as $clause ) { - $clause->setDB($v); - } - } - - /** - * Sets ignore case. - * - * @param boolean $b True if case should be ignored. - * @return Criterion A modified Criterion object. - */ - public function setIgnoreCase($b) - { - $this->ignoreStringCase = (boolean) $b; - return $this; - } - - /** - * Is ignore case on or off? - * - * @return boolean True if case is ignored. - */ - public function isIgnoreCase() - { - return $this->ignoreStringCase; - } - - /** - * Get the list of clauses in this Criterion. - * @return array - */ - private function getClauses() - { - return $this->clauses; - } - - /** - * Get the list of conjunctions in this Criterion - * @return array - */ - public function getConjunctions() - { - return $this->conjunctions; - } - - /** - * Append an AND Criterion onto this Criterion's list. - */ - public function addAnd(Criterion $criterion) - { - $this->clauses[] = $criterion; - $this->conjunctions[] = self::UND; - return $this; - } - - /** - * Append an OR Criterion onto this Criterion's list. - * @return Criterion - */ - public function addOr(Criterion $criterion) - { - $this->clauses[] = $criterion; - $this->conjunctions[] = self::ODER; - return $this; - } - - /** - * Appends a Prepared Statement representation of the Criterion - * onto the buffer. - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - * @return void - * @throws PropelException - if the expression builder cannot figure out how to turn a specified - * expression into proper SQL. - */ - public function appendPsTo(&$sb, array &$params) - { - $sb .= str_repeat ( '(', count($this->clauses) ); - - $this->dispatchPsHandling($sb, $params); - - foreach ($this->clauses as $key => $clause) { - $sb .= $this->conjunctions[$key]; - $clause->appendPsTo($sb, $params); - $sb .= ')'; - } - } - - /** - * Figure out which Criterion method to use - * to build the prepared statement and parameters using to the Criterion comparison - * and call it to append the prepared statement and the parameters of the current clause - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function dispatchPsHandling(&$sb, array &$params) - { - switch ($this->comparison) { - case Criteria::CUSTOM: - // custom expression with no parameter binding - $this->appendCustomToPs($sb, $params); - break; - case Criteria::IN: - case Criteria::NOT_IN: - // table.column IN (?, ?) or table.column NOT IN (?, ?) - $this->appendInToPs($sb, $params); - break; - case Criteria::LIKE: - case Criteria::NOT_LIKE: - case Criteria::ILIKE: - case Criteria::NOT_ILIKE: - // table.column LIKE ? or table.column NOT LIKE ? (or ILIKE for Postgres) - $this->appendLikeToPs($sb, $params); - break; - default: - // table.column = ? or table.column >= ? etc. (traditional expressions, the default) - $this->appendBasicToPs($sb, $params); - } - } - - /** - * Appends a Prepared Statement representation of the Criterion onto the buffer - * For custom expressions with no binding, e.g. 'NOW() = 1' - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function appendCustomToPs(&$sb, array &$params) - { - if ($this->value !== "") { - $sb .= (string) $this->value; - } - } - - /** - * Appends a Prepared Statement representation of the Criterion onto the buffer - * For IN expressions, e.g. table.column IN (?, ?) or table.column NOT IN (?, ?) - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function appendInToPs(&$sb, array &$params) - { - if ($this->value !== "") { - $bindParams = array(); - $index = count($params); // to avoid counting the number of parameters for each element in the array - foreach ((array) $this->value as $value) { - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $value); - $index++; // increment this first to correct for wanting bind params to start with :p1 - $bindParams[] = ':p' . $index; - } - if (count($bindParams)) { - $field = ($this->table === null) ? $this->column : $this->table . '.' . $this->column; - $sb .= $field . $this->comparison . '(' . implode(',', $bindParams) . ')'; - } else { - $sb .= ($this->comparison === Criteria::IN) ? "1<>1" : "1=1"; - } - } - } - - /** - * Appends a Prepared Statement representation of the Criterion onto the buffer - * For LIKE expressions, e.g. table.column LIKE ? or table.column NOT LIKE ? (or ILIKE for Postgres) - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function appendLikeToPs(&$sb, array &$params) - { - $field = ($this->table === null) ? $this->column : $this->table . '.' . $this->column; - $db = $this->getDb(); - // If selection is case insensitive use ILIKE for PostgreSQL or SQL - // UPPER() function on column name for other databases. - if ($this->ignoreStringCase) { - if ($db instanceof DBPostgres) { - if ($this->comparison === Criteria::LIKE) { - $this->comparison = Criteria::ILIKE; - } elseif ($this->comparison === Criteria::NOT_LIKE) { - $this->comparison = Criteria::NOT_ILIKE; - } - } else { - $field = $db->ignoreCase($field); - } - } - - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $this->value); - - $sb .= $field . $this->comparison; - - // If selection is case insensitive use SQL UPPER() function - // on criteria or, if Postgres we are using ILIKE, so not necessary. - if ($this->ignoreStringCase && !($db instanceof DBPostgres)) { - $sb .= $db->ignoreCase(':p'.count($params)); - } else { - $sb .= ':p'.count($params); - } - } - - /** - * Appends a Prepared Statement representation of the Criterion onto the buffer - * For traditional expressions, e.g. table.column = ? or table.column >= ? etc. - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function appendBasicToPs(&$sb, array &$params) - { - $field = ($this->table === null) ? $this->column : $this->table . '.' . $this->column; - // NULL VALUES need special treatment because the SQL syntax is different - // i.e. table.column IS NULL rather than table.column = null - if ($this->value !== null) { - - // ANSI SQL functions get inserted right into SQL (not escaped, etc.) - if ($this->value === Criteria::CURRENT_DATE || $this->value === Criteria::CURRENT_TIME || $this->value === Criteria::CURRENT_TIMESTAMP) { - $sb .= $field . $this->comparison . $this->value; - } else { - - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $this->value); - - // default case, it is a normal col = value expression; value - // will be replaced w/ '?' and will be inserted later using PDO bindValue() - if ($this->ignoreStringCase) { - $sb .= $this->getDb()->ignoreCase($field) . $this->comparison . $this->getDb()->ignoreCase(':p'.count($params)); - } else { - $sb .= $field . $this->comparison . ':p'.count($params); - } - - } - } else { - - // value is null, which means it was either not specified or specifically - // set to null. - if ($this->comparison === Criteria::EQUAL || $this->comparison === Criteria::ISNULL) { - $sb .= $field . Criteria::ISNULL; - } elseif ($this->comparison === Criteria::NOT_EQUAL || $this->comparison === Criteria::ISNOTNULL) { - $sb .= $field . Criteria::ISNOTNULL; - } else { - // for now throw an exception, because not sure how to interpret this - throw new PropelException("Could not build SQL for expression: $field " . $this->comparison . " NULL"); - } - - } - } - - /** - * This method checks another Criteria to see if they contain - * the same attributes and hashtable entries. - * @return boolean - */ - public function equals($obj) - { - // TODO: optimize me with early outs - if ($this === $obj) { - return true; - } - - if (($obj === null) || !($obj instanceof Criterion)) { - return false; - } - - $crit = $obj; - - $isEquiv = ( ( ($this->table === null && $crit->getTable() === null) - || ( $this->table !== null && $this->table === $crit->getTable() ) - ) - && $this->column === $crit->getColumn() - && $this->comparison === $crit->getComparison()); - - // check chained criterion - - $clausesLength = count($this->clauses); - $isEquiv &= (count($crit->getClauses()) == $clausesLength); - $critConjunctions = $crit->getConjunctions(); - $critClauses = $crit->getClauses(); - for ($i=0; $i < $clausesLength && $isEquiv; $i++) { - $isEquiv &= ($this->conjunctions[$i] === $critConjunctions[$i]); - $isEquiv &= ($this->clauses[$i] === $critClauses[$i]); - } - - if ($isEquiv) { - $isEquiv &= $this->value === $crit->getValue(); - } - - return $isEquiv; - } - - /** - * Returns a hash code value for the object. - */ - public function hashCode() - { - $h = crc32(serialize($this->value)) ^ crc32($this->comparison); - - if ($this->table !== null) { - $h ^= crc32($this->table); - } - - if ($this->column !== null) { - $h ^= crc32($this->column); - } - - foreach ( $this->clauses as $clause ) { - // TODO: i KNOW there is a php incompatibility with the following line - // but i dont remember what it is, someone care to look it up and - // replace it if it doesnt bother us? - // $clause->appendPsTo($sb='',$params=array()); - $sb = ''; - $params = array(); - $clause->appendPsTo($sb,$params); - $h ^= crc32(serialize(array($sb,$params))); - unset ( $sb, $params ); - } - - return $h; - } - - /** - * Get all tables from nested criterion objects - * @return array - */ - public function getAllTables() - { - $tables = array(); - $this->addCriterionTable($this, $tables); - return $tables; - } - - /** - * method supporting recursion through all criterions to give - * us a string array of tables from each criterion - * @return void - */ - private function addCriterionTable(Criterion $c, array &$s) - { - $s[] = $c->getTable(); - foreach ( $c->getClauses() as $clause ) { - $this->addCriterionTable($clause, $s); - } - } - - /** - * get an array of all criterion attached to this - * recursing through all sub criterion - * @return array Criterion[] - */ - public function getAttachedCriterion() - { - $criterions = array($this); - foreach ($this->getClauses() as $criterion) { - $criterions = array_merge($criterions, $criterion->getAttachedCriterion()); - } - return $criterions; - } - - /** - * Ensures deep cloning of attached objects - */ - public function __clone() - { - foreach ($this->clauses as $key => $criterion) { - $this->clauses[$key] = clone $criterion; - } - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/query/CriterionIterator.php b/airtime_mvc/library/propel/runtime/lib/query/CriterionIterator.php deleted file mode 100644 index 12f29ff66..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/CriterionIterator.php +++ /dev/null @@ -1,54 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.query - */ -class CriterionIterator implements Iterator -{ - - private $idx = 0; - private $criteria; - private $criteriaKeys; - private $criteriaSize; - - public function __construct(Criteria $criteria) { - $this->criteria = $criteria; - $this->criteriaKeys = $criteria->keys(); - $this->criteriaSize = count($this->criteriaKeys); - } - - public function rewind() { - $this->idx = 0; - } - - public function valid() { - return $this->idx < $this->criteriaSize; - } - - public function key() { - return $this->criteriaKeys[$this->idx]; - } - - public function current() { - return $this->criteria->getCriterion($this->criteriaKeys[$this->idx]); - } - - public function next() { - $this->idx++; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/query/Join.php b/airtime_mvc/library/propel/runtime/lib/query/Join.php deleted file mode 100644 index de7b92b5e..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/Join.php +++ /dev/null @@ -1,250 +0,0 @@ - - * table_a LEFT JOIN table_b ON table_a.id = table_b.a_id - * - * - * @author Francois Zaninotto (Propel) - * @author Hans Lellelid (Propel) - * @author Kaspars Jaudzems (Propel) - * @author Frank Y. Kim (Torque) - * @author John D. McNally (Torque) - * @author Brett McLaughlin (Torque) - * @author Eric Dobbs (Torque) - * @author Henning P. Schmiedehausen (Torque) - * @author Sam Joseph (Torque) - * @package propel.runtime.query - */ -class Join -{ - // default comparison type - const EQUAL = "="; - - // the left parts of the join condition - protected $left = array(); - - // the right parts of the join condition - protected $right = array(); - - // the comparison operators for each pair of columns in the join condition - protected $operator = array(); - - // the type of the join (LEFT JOIN, ...), or null for an implicit join - protected $joinType = null; - - // the number of conditions in the join - protected $count = 0; - - /** - * Constructor - * Use it preferably with no arguments, and then use addCondition() and setJoinType() - * Syntax with arguments used mainly for backwards compatibility - * - * @param string $leftColumn The left column of the join condition - * (may contain an alias name) - * @param string $rightColumn The right column of the join condition - * (may contain an alias name) - * @param string $joinType The type of the join. Valid join types are null (implicit join), - * Criteria::LEFT_JOIN, Criteria::RIGHT_JOIN, and Criteria::INNER_JOIN - */ - public function __construct($leftColumn = null, $rightColumn = null, $joinType = null) - { - if(!is_null($leftColumn)) { - if (!is_array($leftColumn)) { - // simple join - $this->addCondition($leftColumn, $rightColumn); - } else { - // join with multiple conditions - if (count($leftColumn) != count($rightColumn) ) { - throw new PropelException("Unable to create join because the left column count isn't equal to the right column count"); - } - foreach ($leftColumn as $key => $value) - { - $this->addCondition($value, $rightColumn[$key]); - } - } - $this->setJoinType($joinType); - } - } - - /** - * Join condition definition - * - * @param string $left The left column of the join condition - * (may contain an alias name) - * @param string $right The right column of the join condition - * (may contain an alias name) - * @param string $operator The comparison operator of the join condition, default Join::EQUAL - */ - public function addCondition($left, $right, $operator = self::EQUAL) - { - $this->left[] = $left; - $this->right[] = $right; - $this->operator[] = $operator; - $this->count++; - } - - /** - * Retrieve the number of conditions in the join - * - * @return integer The number of conditions in the join - */ - public function countConditions() - { - return $this->count; - } - - /** - * Return an array of the join conditions - * - * @return array An array of arrays representing (left, comparison, right) for each condition - */ - public function getConditions() - { - $conditions = array(); - for ($i=0; $i < $this->count; $i++) { - $conditions[] = array( - 'left' => $this->getLeftColumn($i), - 'operator' => $this->getOperator($i), - 'right' => $this->getRightColumn($i) - ); - } - return $conditions; - } - - /** - * @return the comparison operator for the join condition - */ - public function getOperator($index = 0) - { - return $this->operator[$index]; - } - - public function getOperators() - { - return $this->operator; - } - - /** - * Set the join type - * - * @param string $joinType The type of the join. Valid join types are - * null (adding the join condition to the where clause), - * Criteria::LEFT_JOIN(), Criteria::RIGHT_JOIN(), and Criteria::INNER_JOIN() - */ - public function setJoinType($joinType = null) - { - $this->joinType = $joinType; - } - - /** - * Get the join type - * - * @return string The type of the join, i.e. Criteria::LEFT_JOIN(), ..., - * or null for adding the join condition to the where Clause - */ - public function getJoinType() - { - return $this->joinType; - } - - /** - * @return the left column of the join condition - */ - public function getLeftColumn($index = 0) - { - return $this->left[$index]; - } - - /** - * @return all right columns of the join condition - */ - public function getLeftColumns() - { - return $this->left; - } - - - public function getLeftColumnName($index = 0) - { - return substr($this->left[$index], strrpos($this->left[$index], '.') + 1); - } - - public function getLeftTableName($index = 0) - { - return substr($this->left[$index], 0, strrpos($this->left[$index], '.')); - } - - /** - * @return the right column of the join condition - */ - public function getRightColumn($index = 0) - { - return $this->right[$index]; - } - - /** - * @return all right columns of the join condition - */ - public function getRightColumns() - { - return $this->right; - } - - public function getRightColumnName($index = 0) - { - return substr($this->right[$index], strrpos($this->right[$index], '.') + 1); - } - - public function getRightTableName($index = 0) - { - return substr($this->right[$index], 0, strrpos($this->right[$index], '.')); - } - - public function equals($join) - { - return $join !== null - && $join instanceof Join - && $this->joinType == $join->getJoinType() - && $this->getConditions() == $join->getConditions(); - } - - /** - * returns a String representation of the class, - * mainly for debugging purposes - * - * @return string A String representation of the class - */ - public function toString() - { - $result = ''; - if ($this->joinType !== null) { - $result .= $this->joinType . ' : '; - } - foreach ($this->getConditions() as $index => $condition) { - $result .= implode($condition); - if ($index + 1 < $this->count) { - $result .= ' AND '; - } - } - $result .= '(ignoreCase not considered)'; - - return $result; - } - - public function __toString() - { - return $this->toString(); - } -} - \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/query/ModelCriteria.php b/airtime_mvc/library/propel/runtime/lib/query/ModelCriteria.php deleted file mode 100644 index 4082133a9..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/ModelCriteria.php +++ /dev/null @@ -1,1841 +0,0 @@ -join from going wrong - protected $isKeepQuery = false; // whether to clone the current object before termination methods - - /** - * Creates a new instance with the default capacity which corresponds to - * the specified database. - * - * @param string $dbName The dabase name - * @param string $modelName The phpName of a model, e.g. 'Book' - * @param string $modelAlias The alias for the model in this query, e.g. 'b' - */ - public function __construct($dbName = null, $modelName, $modelAlias = null) - { - $this->setDbName($dbName); - $this->originalDbName = $dbName; - $this->modelName = $modelName; - $this->modelPeerName = constant($this->modelName . '::PEER'); - $this->modelAlias = $modelAlias; - $this->tableMap = Propel::getDatabaseMap($this->getDbName())->getTableByPhpName($this->modelName); - } - - /** - * Returns the name of the class for this model criteria - * - * @return string - */ - public function getModelName() - { - return $this->modelName; - } - - /** - * Sets the alias for the model in this query - * - * @param string $modelAlias The model alias - * @param boolean $useAliasInSQL Whether to use the alias in the SQL code (false by default) - * - * @return ModelCriteria The current object, for fluid interface - */ - public function setModelAlias($modelAlias, $useAliasInSQL = false) - { - if ($useAliasInSQL) { - $this->addAlias($modelAlias, $this->tableMap->getName()); - $this->useAliasInSQL = true; - } - $this->modelAlias = $modelAlias; - - return $this; - } - - /** - * Returns the alias of the main class for this model criteria - * - * @return string The model alias - */ - public function getModelAlias() - { - return $this->modelAlias; - } - - /** - * Return the string to use in a clause as a model prefix for the main model - * - * @return string The model alias if it exists, the model name if not - */ - public function getModelAliasOrName() - { - return $this->modelAlias ? $this->modelAlias : $this->modelName; - } - - /** - * Returns the name of the Peer class for this model criteria - * - * @return string - */ - public function getModelPeerName() - { - return $this->modelPeerName; - } - - /** - * Returns the TabkleMap object for this Criteria - * - * @return TableMap - */ - public function getTableMap() - { - return $this->tableMap; - } - - /** - * Sets the formatter to use for the find() output - * Formatters must extend PropelFormatter - * Use the ModelCriteria constants for class names: - * - * $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - * - * - * @param string|PropelFormatter $formatter a formatter class name, or a formatter instance - * @return ModelCriteria The current object, for fluid interface - */ - public function setFormatter($formatter) - { - if(is_string($formatter)) { - $formatter = new $formatter(); - } - if (!$formatter instanceof PropelFormatter) { - throw new PropelException('setFormatter() only accepts classes extending PropelFormatter'); - } - $this->formatter = $formatter; - - return $this; - } - - /** - * Gets the formatter to use for the find() output - * Defaults to an instance of ModelCriteria::$defaultFormatterClass, i.e. PropelObjectsFormatter - * - * @return PropelFormatter - */ - public function getFormatter() - { - if (null === $this->formatter) { - $formatterClass = $this->defaultFormatterClass; - $this->formatter = new $formatterClass(); - } - return $this->formatter; - } - - /** - * Adds a condition on a column based on a pseudo SQL clause - * but keeps it for later use with combine() - * Until combine() is called, the condition is not added to the query - * Uses introspection to translate the column phpName into a fully qualified name - * - * $c->condition('cond1', 'b.Title = ?', 'foo'); - * - * - * @see Criteria::add() - * - * @param string $conditionName A name to store the condition for a later combination with combine() - * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?' - * @param mixed $value A value for the condition - * - * @return ModelCriteria The current object, for fluid interface - */ - public function condition($conditionName, $clause, $value = null) - { - $this->addCond($conditionName, $this->getCriterionForClause($clause, $value), null, null); - - return $this; - } - - /** - * Adds a condition on a column based on a column phpName and a value - * Uses introspection to translate the column phpName into a fully qualified name - * Warning: recognizes only the phpNames of the main Model (not joined tables) - * - * $c->filterBy('Title', 'foo'); - * - * - * @see Criteria::add() - * - * @param string $column A string representing thecolumn phpName, e.g. 'AuthorId' - * @param mixed $value A value for the condition - * @param string $comparison What to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ModelCriteria The current object, for fluid interface - */ - public function filterBy($column, $value, $comparison = Criteria::EQUAL) - { - return $this->add($this->getRealColumnName($column), $value, $comparison); - } - - /** - * Adds a list of conditions on the columns of the current model - * Uses introspection to translate the column phpName into a fully qualified name - * Warning: recognizes only the phpNames of the main Model (not joined tables) - * - * $c->filterByArray(array( - * 'Title' => 'War And Peace', - * 'Publisher' => $publisher - * )); - * - * - * @see filterBy() - * - * @param mixed $conditions An array of conditions, using column phpNames as key - * - * @return ModelCriteria The current object, for fluid interface - */ - public function filterByArray($conditions) - { - foreach ($conditions as $column => $args) { - call_user_func_array(array($this, 'filterBy' . $column), (array) $args); - } - - return $this; - } - - /** - * Adds a condition on a column based on a pseudo SQL clause - * Uses introspection to translate the column phpName into a fully qualified name - * - * // simple clause - * $c->where('b.Title = ?', 'foo'); - * // named conditions - * $c->condition('cond1', 'b.Title = ?', 'foo'); - * $c->condition('cond2', 'b.ISBN = ?', 12345); - * $c->where(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - * - * - * @see Criteria::add() - * - * @param mixed $clause A string representing the pseudo SQL clause, e.g. 'Book.AuthorId = ?' - * Or an array of condition names - * @param mixed $value A value for the condition - * - * @return ModelCriteria The current object, for fluid interface - */ - public function where($clause, $value = null) - { - if (is_array($clause)) { - // where(array('cond1', 'cond2'), Criteria::LOGICAL_OR) - $criterion = $this->getCriterionForConditions($clause, $value); - } else { - // where('Book.AuthorId = ?', 12) - $criterion = $this->getCriterionForClause($clause, $value); - } - $this->addAnd($criterion, null, null); - - return $this; - } - - /** - * Adds a condition on a column based on a pseudo SQL clause - * Uses introspection to translate the column phpName into a fully qualified name - * - * // simple clause - * $c->orWhere('b.Title = ?', 'foo'); - * // named conditions - * $c->condition('cond1', 'b.Title = ?', 'foo'); - * $c->condition('cond2', 'b.ISBN = ?', 12345); - * $c->orWhere(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - * - * - * @see Criteria::addOr() - * - * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?' - * @param mixed $value A value for the condition - * - * @return ModelCriteria The current object, for fluid interface - */ - public function orWhere($clause, $value = null) - { - if (is_array($clause)) { - // orWhere(array('cond1', 'cond2'), Criteria::LOGICAL_OR) - $criterion = $this->getCriterionForConditions($clause, $value); - } else { - // orWhere('Book.AuthorId = ?', 12) - $criterion = $this->getCriterionForClause($clause, $value); - } - $this->addOr($criterion, null, null); - - return $this; - } - - /** - * Adds a having condition on a column based on a pseudo SQL clause - * Uses introspection to translate the column phpName into a fully qualified name - * - * // simple clause - * $c->having('b.Title = ?', 'foo'); - * // named conditions - * $c->condition('cond1', 'b.Title = ?', 'foo'); - * $c->condition('cond2', 'b.ISBN = ?', 12345); - * $c->having(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - * - * - * @see Criteria::addHaving() - * - * @param mixed $clause A string representing the pseudo SQL clause, e.g. 'Book.AuthorId = ?' - * Or an array of condition names - * @param mixed $value A value for the condition - * - * @return ModelCriteria The current object, for fluid interface - */ - public function having($clause, $value = null) - { - if (is_array($clause)) { - // having(array('cond1', 'cond2'), Criteria::LOGICAL_OR) - $criterion = $this->getCriterionForConditions($clause, $value); - } else { - // having('Book.AuthorId = ?', 12) - $criterion = $this->getCriterionForClause($clause, $value); - } - $this->addHaving($criterion); - - return $this; - } - - /** - * Adds an ORDER BY clause to the query - * Usability layer on top of Criteria::addAscendingOrderByColumn() and Criteria::addDescendingOrderByColumn() - * Infers $column and $order from $columnName and some optional arguments - * Examples: - * $c->orderBy('Book.CreatedAt') - * => $c->addAscendingOrderByColumn(BookPeer::CREATED_AT) - * $c->orderBy('Book.CategoryId', 'desc') - * => $c->addDescendingOrderByColumn(BookPeer::CATEGORY_ID) - * - * @param string $columnName The column to order by - * @param string $order The sorting order. Criteria::ASC by default, also accepts Criteria::DESC - * - * @return ModelCriteria The current object, for fluid interface - */ - public function orderBy($columnName, $order = Criteria::ASC) - { - list($column, $realColumnName) = $this->getColumnFromName($columnName, false); - $order = strtoupper($order); - switch ($order) { - case Criteria::ASC: - $this->addAscendingOrderByColumn($realColumnName); - break; - case Criteria::DESC: - $this->addDescendingOrderByColumn($realColumnName); - break; - default: - throw new PropelException('ModelCriteria::orderBy() only accepts Criteria::ASC or Criteria::DESC as argument'); - } - - return $this; - } - - /** - * Adds a GROUB BY clause to the query - * Usability layer on top of Criteria::addGroupByColumn() - * Infers $column $columnName - * Examples: - * $c->groupBy('Book.AuthorId') - * => $c->addGroupByColumn(BookPeer::AUTHOR_ID) - * - * @param string $columnName The column to group by - * - * @return ModelCriteria The current object, for fluid interface - */ - public function groupBy($columnName) - { - list($column, $realColumnName) = $this->getColumnFromName($columnName, false); - $this->addGroupByColumn($realColumnName); - - return $this; - } - - /** - * Adds a DISTINCT clause to the query - * Alias for Criteria::setDistinct() - * - * @return ModelCriteria The current object, for fluid interface - */ - public function distinct() - { - $this->setDistinct(); - - return $this; - } - - /** - * Adds a LIMIT clause (or its subselect equivalent) to the query - * Alias for Criteria:::setLimit() - * - * @param int $limit Maximum number of results to return by the query - * - * @return ModelCriteria The current object, for fluid interface - */ - public function limit($limit) - { - $this->setLimit($limit); - - return $this; - } - - /** - * Adds an OFFSET clause (or its subselect equivalent) to the query - * Alias for of Criteria::setOffset() - * - * @param int $offset Offset of the first result to return - * - * @return ModelCriteria The current object, for fluid interface - */ - public function offset($offset) - { - $this->setOffset($offset); - - return $this; - } - - /** - * This method returns the previousJoin for this ModelCriteria, - * by default this is null, but after useQuery this is set the to the join of that use - * - * @return Join the previousJoin for this ModelCriteria - */ - public function getPreviousJoin() - { - return $this->previousJoin; - } - - /** - * This method sets the previousJoin for this ModelCriteria, - * by default this is null, but after useQuery this is set the to the join of that use - * - * @param Join $previousJoin The previousJoin for this ModelCriteria - */ - public function setPreviousJoin(Join $previousJoin) - { - $this->previousJoin = $previousJoin; - } - - /** - * This method returns an already defined join clause from the query - * - * @param string $name The name of the join clause - * - * @return Join A join object - */ - public function getJoin($name) - { - return $this->joins[$name]; - } - - /** - * Adds a JOIN clause to the query - * Infers the ON clause from a relation name - * Uses the Propel table maps, based on the schema, to guess the related columns - * Beware that the default JOIN operator is INNER JOIN, while Criteria defaults to WHERE - * Examples: - * - * $c->join('Book.Author'); - * => $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::INNER_JOIN); - * $c->join('Book.Author', Criteria::RIGHT_JOIN); - * => $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::RIGHT_JOIN); - * $c->join('Book.Author a', Criteria::RIGHT_JOIN); - * => $c->addAlias('a', AuthorPeer::TABLE_NAME); - * => $c->addJoin(BookPeer::AUTHOR_ID, 'a.ID', Criteria::RIGHT_JOIN); - * - * - * @param string $relation Relation to use for the join - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return ModelCriteria The current object, for fluid interface - */ - public function join($relation, $joinType = Criteria::INNER_JOIN) - { - // relation looks like '$leftName.$relationName $relationAlias' - list($fullName, $relationAlias) = self::getClassAndAlias($relation); - if (strpos($fullName, '.') === false) { - // simple relation name, refers to the current table - $leftName = $this->getModelAliasOrName(); - $relationName = $fullName; - $previousJoin = $this->getPreviousJoin(); - $tableMap = $this->getTableMap(); - } else { - list($leftName, $relationName) = explode('.', $fullName); - // find the TableMap for the left table using the $leftName - if ($leftName == $this->getModelAliasOrName()) { - $previousJoin = $this->getPreviousJoin(); - $tableMap = $this->getTableMap(); - } elseif (isset($this->joins[$leftName])) { - $previousJoin = $this->joins[$leftName]; - $tableMap = $previousJoin->getTableMap(); - } else { - throw new PropelException('Unknown table or alias ' . $leftName); - } - } - $leftTableAlias = isset($this->aliases[$leftName]) ? $leftName : null; - - // find the RelationMap in the TableMap using the $relationName - if(!$tableMap->hasRelation($relationName)) { - throw new PropelException('Unknown relation ' . $relationName . ' on the ' . $leftName .' table'); - } - $relationMap = $tableMap->getRelation($relationName); - - // create a ModelJoin object for this join - $join = new ModelJoin(); - $join->setJoinType($joinType); - if(null !== $previousJoin) { - $join->setPreviousJoin($previousJoin); - } - $join->setRelationMap($relationMap, $leftTableAlias, $relationAlias); - - // add the ModelJoin to the current object - if($relationAlias !== null) { - $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); - $this->addJoinObject($join, $relationAlias); - } else { - $this->addJoinObject($join, $relationName); - } - - return $this; - } - - /** - * Add a join object to the Criteria - * @see Criteria::addJoinObject() - * @param Join $join A join object - * - * @return ModelCriteria The current object, for fluid interface - */ - public function addJoinObject(Join $join, $name = null) - { - if (!in_array($join, $this->joins)) { // compare equality, NOT identity - $this->joins[$name] = $join; - } - return $this; - } - - /** - * Adds a JOIN clause to the query and hydrates the related objects - * Shortcut for $c->join()->with() - * - * $c->joinWith('Book.Author'); - * => $c->join('Book.Author'); - * => $c->with('Author'); - * $c->joinWith('Book.Author a', Criteria::RIGHT_JOIN); - * => $c->join('Book.Author a', Criteria::RIGHT_JOIN); - * => $c->with('a'); - * - * - * @param string $relation Relation to use for the join - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return ModelCriteria The current object, for fluid interface - */ - public function joinWith($relation, $joinType = Criteria::INNER_JOIN) - { - $this->join($relation, $joinType); - $this->with(self::getRelationName($relation)); - - return $this; - } - - /** - * Adds a relation to hydrate together with the main object - * The relation must be initialized via a join() prior to calling with() - * Examples: - * - * $c->join('Book.Author'); - * $c->with('Author'); - * - * $c->join('Book.Author a', Criteria::RIGHT_JOIN); - * $c->with('a'); - * - * WARNING: on a one-to-many relationship, the use of with() combined with limit() - * will return a wrong number of results for the related objects - * - * @param string $relation Relation to use for the join - * - * @return ModelCriteria The current object, for fluid interface - */ - public function with($relation) - { - if (!isset($this->joins[$relation])) { - throw new PropelException('Unknown relation name or alias ' . $relation); - } - $join = $this->joins[$relation]; - if ($join->getRelationMap()->getType() == RelationMap::MANY_TO_MANY) { - throw new PropelException('with() does not allow hydration for many-to-many relationships'); - } elseif ($join->getRelationMap()->getType() == RelationMap::ONE_TO_MANY) { - // For performance reasons, the formatters will use a special routine in this case - $this->isWithOneToMany = true; - } - - // check that the columns of the main class are already added (but only if this isn't a useQuery) - if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) { - $this->addSelfSelectColumns(); - } - // add the columns of the related class - $this->addRelationSelectColumns($relation); - - // list the join for later hydration in the formatter - $this->with[$relation] = $join; - - return $this; - } - - /** - * Gets the array of ModelWith specifying which objects must be hydrated - * together with the main object. - * - * @see with() - * @return array - */ - public function getWith() - { - return $this->with; - } - - public function isWithOneToMany() - { - return $this->isWithOneToMany; - } - - /** - * Adds a supplementary column to the select clause - * These columns can later be retrieved from the hydrated objects using getVirtualColumn() - * - * @param string $clause The SQL clause with object model column names - * e.g. 'UPPER(Author.FirstName)' - * @param string $name Optional alias for the added column - * If no alias is provided, the clause is used as a column alias - * This alias is used for retrieving the column via BaseObject::getVirtualColumn($alias) - * - * @return ModelCriteria The current object, for fluid interface - */ - public function withColumn($clause, $name = null) - { - if (null === $name) { - $name = str_replace(array('.', '(', ')'), '', $clause); - } - $clause = trim($clause); - $this->replaceNames($clause); - // check that the columns of the main class are already added (if this is the primary ModelCriteria) - if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) { - $this->addSelfSelectColumns(); - } - $this->addAsColumn($name, $clause); - - return $this; - } - - /** - * Initializes a secondary ModelCriteria object, to be later merged with the current object - * - * @see ModelCriteria::endUse() - * @param string $relationName Relation name or alias - * @param string $secondCriteriaClass Classname for the ModelCriteria to be used - * - * @return ModelCriteria The secondary criteria object - */ - public function useQuery($relationName, $secondaryCriteriaClass = null) - { - if (!isset($this->joins[$relationName])) { - throw new PropelException('Unknown class or alias ' . $relationName); - } - $className = $this->joins[$relationName]->getTableMap()->getPhpName(); - if (null === $secondaryCriteriaClass) { - $secondaryCriteria = PropelQuery::from($className); - } else { - $secondaryCriteria = new $secondaryCriteriaClass(); - } - if ($className != $relationName) { - $secondaryCriteria->setModelAlias($relationName, $relationName == $this->joins[$relationName]->getRelationMap()->getName() ? false : true); - } - $secondaryCriteria->setPrimaryCriteria($this, $this->joins[$relationName]); - - return $secondaryCriteria; - } - - /** - * Finalizes a secondary criteria and merges it with its primary Criteria - * - * @see Criteria::mergeWith() - * - * @return ModelCriteria The primary criteria object - */ - public function endUse() - { - if (isset($this->aliases[$this->modelAlias])) { - $this->removeAlias($this->modelAlias); - } - $primaryCriteria = $this->getPrimaryCriteria(); - $primaryCriteria->mergeWith($this); - - return $primaryCriteria; - } - - /** - * Add the content of a Criteria to the current Criteria - * In case of conflict, the current Criteria keeps its properties - * @see Criteria::mergeWith() - * - * @param Criteria $criteria The criteria to read properties from - * @param string $operator The logical operator used to combine conditions - * Defaults to Criteria::LOGICAL_AND, also accapts Criteria::LOGICAL_OR - * - * @return ModelCriteria The primary criteria object - */ - public function mergeWith(Criteria $criteria, $operator = Criteria::LOGICAL_AND) - { - parent::mergeWith($criteria, $operator); - - // merge with - if ($criteria instanceof ModelCriteria) { - $this->with = array_merge($this->getWith(), $criteria->getWith()); - } - - return $this; - } - - /** - * Clear the conditions to allow the reuse of the query object. - * The ModelCriteria's Model and alias 'all the properties set by construct) will remain. - * - * @return ModelCriteria The primary criteria object - */ - public function clear() - { - parent::clear(); - - $this->with = array(); - $this->primaryCriteria = null; - $this->formatter=null; - - return $this; - } - /** - * Sets the primary Criteria for this secondary Criteria - * - * @param ModelCriteria $criteria The primary criteria - * @param Join $previousJoin The previousJoin for this ModelCriteria - */ - public function setPrimaryCriteria(ModelCriteria $criteria, Join $previousJoin) - { - $this->primaryCriteria = $criteria; - $this->setPreviousJoin($previousJoin); - } - - /** - * Gets the primary criteria for this secondary Criteria - * - * @return ModelCriteria The primary criteria - */ - public function getPrimaryCriteria() - { - return $this->primaryCriteria; - } - - /** - * Adds the select columns for a the current table - * - * @return ModelCriteria The current object, for fluid interface - */ - public function addSelfSelectColumns() - { - call_user_func(array($this->modelPeerName, 'addSelectColumns'), $this, $this->useAliasInSQL ? $this->modelAlias : null); - - return $this; - } - - /** - * Adds the select columns for a relation - * - * @param string $relation The relation name or alias, as defined in join() - * - * @return ModelCriteria The current object, for fluid interface - */ - public function addRelationSelectColumns($relation) - { - $join = $this->joins[$relation]; - call_user_func(array($join->getTableMap()->getPeerClassname(), 'addSelectColumns'), $this, $join->getRelationAlias()); - - return $this; - } - - /** - * Returns the class and alias of a string representing a model or a relation - * e.g. 'Book b' => array('Book', 'b') - * e.g. 'Book' => array('Book', null) - * - * @param string $class The classname to explode - * - * @return array list($className, $aliasName) - */ - public static function getClassAndAlias($class) - { - if(strpos($class, ' ') !== false) { - list($class, $alias) = explode(' ', $class); - } else { - $alias = null; - } - return array($class, $alias); - } - - /** - * Returns the name of a relation from a string. - * The input looks like '$leftName.$relationName $relationAlias' - * - * @param string $relation Relation to use for the join - * @return string the relationName used in the join - */ - public static function getRelationName($relation) - { - // get the relationName - list($fullName, $relationAlias) = self::getClassAndAlias($relation); - if ($relationAlias) { - $relationName = $relationAlias; - } elseif (false === strpos($fullName, '.')) { - $relationName = $fullName; - } else { - list($leftName, $relationName) = explode('.', $fullName); - } - - return $relationName; - } - - /** - * Triggers the automated cloning on termination. - * By default, temrination methods don't clone the current object, - * even though they modify it. If the query must be reused after termination, - * you must call this method prior to temrination. - * - * @param boolean $isKeepQuery - * - * @return ModelCriteria The current object, for fluid interface - */ - public function keepQuery($isKeepQuery = true) - { - $this->isKeepQuery = (bool) $isKeepQuery; - - return $this; - } - - /** - * Checks whether the automated cloning on termination is enabled. - * - * @return boolean true if cloning must be done before termination - */ - public function isKeepQuery() - { - return $this->isKeepQuery; - } - - /** - * Code to execute before every SELECT statement - * - * @param PropelPDO $con The connection object used by the query - */ - protected function basePreSelect(PropelPDO $con) - { - return $this->preSelect($con); - } - - protected function preSelect(PropelPDO $con) - { - } - - /** - * Issue a SELECT query based on the current ModelCriteria - * and format the list of results with the current formatter - * By default, returns an array of model objects - * - * @param PropelPDO $con an optional connection object - * - * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter - */ - public function find($con = null) - { - $criteria = $this->isKeepQuery() ? clone $this : $this; - $stmt = $criteria->getSelectStatement($con); - - return $criteria->getFormatter()->init($criteria)->format($stmt); - } - - /** - * Issue a SELECT ... LIMIT 1 query based on the current ModelCriteria - * and format the result with the current formatter - * By default, returns a model object - * - * @param PropelPDO $con an optional connection object - * - * @return mixed the result, formatted by the current formatter - */ - public function findOne($con = null) - { - $criteria = $this->isKeepQuery() ? clone $this : $this; - $criteria->limit(1); - $stmt = $criteria->getSelectStatement($con); - - return $criteria->getFormatter()->init($criteria)->formatOne($stmt); - } - - /** - * Issue a SELECT ... LIMIT 1 query based on the current ModelCriteria - * and format the result with the current formatter - * By default, returns a model object - * - * @param PropelPDO $con an optional connection object - * - * @return mixed the result, formatted by the current formatter - */ - public function findOneOrCreate($con = null) - { - $criteria = $this->isKeepQuery() ? clone $this : $this; - $criteria->limit(1); - $stmt = $criteria->getSelectStatement($con); - if (!$ret = $this->findOne($con)) { - $class = $this->getModelName(); - $obj = new $class(); - foreach ($this->keys() as $key) { - $obj->setByName($key, $this->getValue($key), BasePeer::TYPE_COLNAME); - } - $ret = $this->getFormatter()->formatRecord($obj); - } - return $ret; - } - - /** - * Find object by primary key - * Behaves differently if the model has simple or composite primary key - * - * // simple primary key - * $book = $c->findPk(12, $con); - * // composite primary key - * $bookOpinion = $c->findPk(array(34, 634), $con); - * - * @param mixed $key Primary key to use for the query - * @param PropelPDO $con an optional connection object - * - * @return mixed the result, formatted by the current formatter - */ - public function findPk($key, $con = null) - { - $pkCols = $this->getTableMap()->getPrimaryKeyColumns(); - if (count($pkCols) == 1) { - // simple primary key - $pkCol = $pkCols[0]; - $this->add($pkCol->getFullyQualifiedName(), $key); - return $this->findOne($con); - } else { - // composite primary key - foreach ($pkCols as $pkCol) { - $keyPart = array_shift($key); - $this->add($pkCol->getFullyQualifiedName(), $keyPart); - } - return $this->findOne($con); - } - } - - /** - * Find objects by primary key - * Behaves differently if the model has simple or composite primary key - * - * // simple primary key - * $books = $c->findPks(array(12, 56, 832), $con); - * // composite primary key - * $bookOpinion = $c->findPks(array(array(34, 634), array(45, 518), array(34, 765)), $con); - * - * @param array $keys Primary keys to use for the query - * @param PropelPDO $con an optional connection object - * - * @return mixed the list of results, formatted by the current formatter - */ - public function findPks($keys, $con = null) - { - $pkCols = $this->getTableMap()->getPrimaryKeyColumns(); - if (count($pkCols) == 1) { - // simple primary key - $pkCol = array_shift($pkCols); - $this->add($pkCol->getFullyQualifiedName(), $keys, Criteria::IN); - } else { - // composite primary key - throw new PropelException('Multiple object retrieval is not implemented for composite primary keys'); - } - return $this->find($con); - } - - protected function getSelectStatement($con = null) - { - $dbMap = Propel::getDatabaseMap($this->getDbName()); - $db = Propel::getDB($this->getDbName()); - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); - } - - // check that the columns of the main class are already added (if this is the primary ModelCriteria) - if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) { - $this->addSelfSelectColumns(); - } - - $con->beginTransaction(); - try { - $this->basePreSelect($con); - $params = array(); - $sql = BasePeer::createSelectSql($this, $params); - $stmt = $con->prepare($sql); - BasePeer::populateStmtValues($stmt, $params, $dbMap, $db); - $stmt->execute(); - $con->commit(); - } catch (Exception $e) { - if ($stmt) { - $stmt = null; // close - } - $con->rollBack(); - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e); - } - - return $stmt; - } - - /** - * Apply a condition on a column and issues the SELECT query - * - * @see filterBy() - * @see find() - * - * @param string $column A string representing the column phpName, e.g. 'AuthorId' - * @param mixed $value A value for the condition - * @param PropelPDO $con An optional connection object - * - * @return mixed the list of results, formatted by the current formatter - */ - public function findBy($column, $value, $con = null) - { - $method = 'filterBy' . $column; - $this->$method($value); - - return $this->find($con); - } - - /** - * Apply a list of conditions on columns and issues the SELECT query - * - * $c->findByArray(array( - * 'Title' => 'War And Peace', - * 'Publisher' => $publisher - * ), $con); - * - * - * @see filterByArray() - * @see find() - * - * @param mixed $conditions An array of conditions, using column phpNames as key - * @param PropelPDO $con an optional connection object - * - * @return mixed the list of results, formatted by the current formatter - */ - public function findByArray($conditions, $con = null) - { - $this->filterByArray($conditions); - - return $this->find($con); - } - - /** - * Apply a condition on a column and issues the SELECT ... LIMIT 1 query - * - * @see filterBy() - * @see findOne() - * - * @param mixed $column A string representing thecolumn phpName, e.g. 'AuthorId' - * @param mixed $value A value for the condition - * @param PropelPDO $con an optional connection object - * - * @return mixed the result, formatted by the current formatter - */ - public function findOneBy($column, $value, $con = null) - { - $method = 'filterBy' . $column; - $this->$method($value); - - return $this->findOne($con); - } - - /** - * Apply a list of conditions on columns and issues the SELECT ... LIMIT 1 query - * - * $c->findOneByArray(array( - * 'Title' => 'War And Peace', - * 'Publisher' => $publisher - * ), $con); - * - * - * @see filterByArray() - * @see findOne() - * - * @param mixed $conditions An array of conditions, using column phpNames as key - * @param PropelPDO $con an optional connection object - * - * @return mixed the list of results, formatted by the current formatter - */ - public function findOneByArray($conditions, $con = null) - { - $this->filterByArray($conditions); - - return $this->findOne($con); - } - - /** - * Issue a SELECT COUNT(*) query based on the current ModelCriteria - * - * @param PropelPDO $con an optional connection object - * - * @return integer the number of results - */ - public function count($con = null) - { - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); - } - - $criteria = $this->isKeepQuery() ? clone $this : $this; - $criteria->setDbName($this->getDbName()); // Set the correct dbName - $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count - - // We need to set the primary table name, since in the case that there are no WHERE columns - // it will be impossible for the BasePeer::createSelectSql() method to determine which - // tables go into the FROM clause. - $criteria->setPrimaryTableName(constant($this->modelPeerName.'::TABLE_NAME')); - - $stmt = $criteria->getCountStatement($con); - if ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $count = (int) $row[0]; - } else { - $count = 0; // no rows returned; we infer that means 0 matches. - } - $stmt->closeCursor(); - - return $count; - } - - protected function getCountStatement($con = null) - { - $dbMap = Propel::getDatabaseMap($this->getDbName()); - $db = Propel::getDB($this->getDbName()); - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); - } - - // check that the columns of the main class are already added (if this is the primary ModelCriteria) - if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) { - $this->addSelfSelectColumns(); - } - - $needsComplexCount = $this->getGroupByColumns() - || $this->getOffset() - || $this->getLimit() - || $this->getHaving() - || in_array(Criteria::DISTINCT, $this->getSelectModifiers()); - - $con->beginTransaction(); - try { - $this->basePreSelect($con); - $params = array(); - if ($needsComplexCount) { - if (BasePeer::needsSelectAliases($this)) { - if ($this->getHaving()) { - throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part'); - } - BasePeer::turnSelectColumnsToAliases($this); - } - $selectSql = BasePeer::createSelectSql($this, $params); - $sql = 'SELECT COUNT(*) FROM (' . $selectSql . ') propelmatch4cnt'; - } else { - // Replace SELECT columns with COUNT(*) - $this->clearSelectColumns()->addSelectColumn('COUNT(*)'); - $sql = BasePeer::createSelectSql($this, $params); - } - $stmt = $con->prepare($sql); - BasePeer::populateStmtValues($stmt, $params, $dbMap, $db); - $stmt->execute(); - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - throw $e; - } - - return $stmt; - } - - /** - * Issue a SELECT query based on the current ModelCriteria - * and uses a page and a maximum number of results per page - * to compute an offet and a limit. - * - * @param int $page number of the page to start the pager on. Page 1 means no offset - * @param int $maxPerPage maximum number of results per page. Determines the limit - * @param PropelPDO $con an optional connection object - * - * @return PropelModelPager a pager object, supporting iteration - */ - public function paginate($page = 1, $maxPerPage = 10, $con = null) - { - $criteria = $this->isKeepQuery() ? clone $this : $this; - $pager = new PropelModelPager($criteria, $maxPerPage); - $pager->setPage($page); - $pager->init(); - - return $pager; - } - - /** - * Code to execute before every DELETE statement - * - * @param PropelPDO $con The connection object used by the query - */ - protected function basePreDelete(PropelPDO $con) - { - return $this->preDelete($con); - } - - protected function preDelete(PropelPDO $con) - { - } - - /** - * Code to execute after every DELETE statement - * - * @param int $affectedRows the number of deleted rows - * @param PropelPDO $con The connection object used by the query - */ - protected function basePostDelete($affectedRows, PropelPDO $con) - { - return $this->postDelete($affectedRows, $con); - } - - protected function postDelete($affectedRows, PropelPDO $con) - { - } - - /** - * Issue a DELETE query based on the current ModelCriteria - * An optional hook on basePreDelete() can prevent the actual deletion - * - * @param PropelPDO $con an optional connection object - * - * @return integer the number of deleted rows - */ - public function delete($con = null) - { - if (count($this->getMap()) == 0) { - throw new PropelException('delete() expects a Criteria with at least one condition. Use deleteAll() to delete all the rows of a table'); - } - - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); - } - - $criteria = $this->isKeepQuery() ? clone $this : $this; - $criteria->setDbName($this->getDbName()); - - $con->beginTransaction(); - try { - if(!$affectedRows = $criteria->basePreDelete($con)) { - $affectedRows = $criteria->doDelete($con); - } - $criteria->basePostDelete($affectedRows, $con); - $con->commit(); - } catch (PropelException $e) { - $con->rollback(); - throw $e; - } - - return $affectedRows; - } - - /** - * Issue a DELETE query based on the current ModelCriteria - * This method is called by ModelCriteria::delete() inside a transaction - * - * @param PropelPDO $con a connection object - * - * @return integer the number of deleted rows - */ - public function doDelete($con) - { - $affectedRows = call_user_func(array($this->modelPeerName, 'doDelete'), $this, $con); - - return $affectedRows; - } - - /** - * Issue a DELETE query based on the current ModelCriteria deleting all rows in the table - * An optional hook on basePreDelete() can prevent the actual deletion - * - * @param PropelPDO $con an optional connection object - * - * @return integer the number of deleted rows - */ - public function deleteAll($con = null) - { - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_WRITE); - } - $con->beginTransaction(); - try { - if(!$affectedRows = $this->basePreDelete($con)) { - $affectedRows = $this->doDeleteAll($con); - } - $this->basePostDelete($affectedRows, $con); - $con->commit(); - return $affectedRows; - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - - return $affectedRows; - } - - /** - * Issue a DELETE query based on the current ModelCriteria deleting all rows in the table - * This method is called by ModelCriteria::deleteAll() inside a transaction - * - * @param PropelPDO $con a connection object - * - * @return integer the number of deleted rows - */ - public function doDeleteAll($con) - { - $affectedRows = call_user_func(array($this->modelPeerName, 'doDeleteAll'), $con); - - return $affectedRows; - } - - /** - * Code to execute before every UPDATE statement - * - * @param array $values The associatiove array of columns and values for the update - * @param PropelPDO $con The connection object used by the query - * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects - */ - protected function basePreUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false) - { - return $this->preUpdate($values, $con, $forceIndividualSaves); - } - - protected function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false) - { - } - - /** - * Code to execute after every UPDATE statement - * - * @param int $affectedRows the number of updated rows - * @param PropelPDO $con The connection object used by the query - */ - protected function basePostUpdate($affectedRows, PropelPDO $con) - { - return $this->postUpdate($affectedRows, $con); - } - - protected function postUpdate($affectedRows, PropelPDO $con) - { - } - - /** - * Issue an UPDATE query based the current ModelCriteria and a list of changes. - * An optional hook on basePreUpdate() can prevent the actual update. - * Beware that behaviors based on hooks in the object's save() method - * will only be triggered if you force individual saves, i.e. if you pass true as second argument. - * - * @param array $values Associative array of keys and values to replace - * @param PropelPDO $con an optional connection object - * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects - * - * @return Integer Number of updated rows - */ - public function update($values, $con = null, $forceIndividualSaves = false) - { - if (!is_array($values)) { - throw new PropelException('set() expects an array as first argument'); - } - if (count($this->getJoins())) { - throw new PropelException('set() does not support multitable updates, please do not use join()'); - } - - if ($con === null) { - $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_WRITE); - } - - $criteria = $this->isKeepQuery() ? clone $this : $this; - $criteria->setPrimaryTableName(constant($this->modelPeerName.'::TABLE_NAME')); - - $con->beginTransaction(); - try { - - if(!$affectedRows = $criteria->basePreUpdate($values, $con, $forceIndividualSaves)) { - $affectedRows = $criteria->doUpdate($values, $con, $forceIndividualSaves); - } - $criteria->basePostUpdate($affectedRows, $con); - - $con->commit(); - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - - return $affectedRows; - } - - /** - * Issue an UPDATE query based the current ModelCriteria and a list of changes. - * This method is called by ModelCriteria::update() inside a transaction. - * - * @param array $values Associative array of keys and values to replace - * @param PropelPDO $con a connection object - * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects - * - * @return Integer Number of updated rows - */ - public function doUpdate($values, $con, $forceIndividualSaves = false) - { - if($forceIndividualSaves) { - - // Update rows one by one - $objects = $this->setFormatter(ModelCriteria::FORMAT_OBJECT)->find($con); - foreach ($objects as $object) { - foreach ($values as $key => $value) { - $object->setByName($key, $value); - } - } - $objects->save($con); - $affectedRows = count($objects); - - } else { - - // update rows in a single query - $set = new Criteria(); - foreach ($values as $columnName => $value) { - $realColumnName = $this->getTableMap()->getColumnByPhpName($columnName)->getFullyQualifiedName(); - $set->add($realColumnName, $value); - } - $affectedRows = BasePeer::doUpdate($this, $set, $con); - call_user_func(array($this->modelPeerName, 'clearInstancePool')); - call_user_func(array($this->modelPeerName, 'clearRelatedInstancePool')); - } - - return $affectedRows; - } - - /** - * Creates a Criterion object based on a list of existing condition names and a comparator - * - * @param array $conditions The list of condition names, e.g. array('cond1', 'cond2') - * @param string $comparator A comparator, Criteria::LOGICAL_AND (default) or Criteria::LOGICAL_OR - * - * @return Criterion a Criterion or ModelCriterion object - */ - protected function getCriterionForConditions($conditions, $comparator = null) - { - $comparator = (null === $comparator) ? Criteria::LOGICAL_AND : $comparator; - $this->combine($conditions, $comparator, 'propel_temp_name'); - $criterion = $this->namedCriterions['propel_temp_name']; - unset($this->namedCriterions['propel_temp_name']); - - return $criterion; - } - - /** - * Creates a Criterion object based on a SQL clause and a value - * Uses introspection to translate the column phpName into a fully qualified name - * - * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?' - * @param mixed $value A value for the condition - * - * @return Criterion a Criterion or ModelCriterion object - */ - protected function getCriterionForClause($clause, $value) - { - $clause = trim($clause); - if($this->replaceNames($clause)) { - // at least one column name was found and replaced in the clause - // this is enough to determine the type to bind the parameter to - if (preg_match('/IN \?$/i', $clause) !== 0) { - $operator = ModelCriteria::MODEL_CLAUSE_ARRAY; - } elseif (preg_match('/LIKE \?$/i', $clause) !== 0) { - $operator = ModelCriteria::MODEL_CLAUSE_LIKE; - } elseif (substr_count($clause, '?') > 1) { - $operator = ModelCriteria::MODEL_CLAUSE_SEVERAL; - } else { - $operator = ModelCriteria::MODEL_CLAUSE; - } - $criterion = new ModelCriterion($this, $this->replacedColumns[0], $value, $operator, $clause); - if ($this->currentAlias != '') { - $criterion->setTable($this->currentAlias); - } - } else { - // no column match in clause, must be an expression like '1=1' - if (strpos($clause, '?') !== false) { - throw new PropelException("Cannot determine the column to bind to the parameter in clause '$clause'"); - } - $criterion = new Criterion($this, null, $clause, Criteria::CUSTOM); - } - return $criterion; - } - - /** - * Replaces complete column names (like Article.AuthorId) in an SQL clause - * by their exact Propel column fully qualified name (e.g. article.AUTHOR_ID) - * but ignores the column names inside quotes - * - * Note: if you know a way to do so in one step, and in an efficient way, I'm interested :) - * - * @param string $clause SQL clause to inspect (modified by the method) - * - * @return boolean Whether the method managed to find and replace at least one column name - */ - protected function replaceNames(&$clause) - { - $this->replacedColumns = array(); - $this->currentAlias = ''; - $this->foundMatch = false; - $regexp = <<foundMatch; - } - - /** - * Callback function to replace expressions containing column names with expressions using the real column names - * Handles strings properly - * e.g. 'CONCAT(Book.Title, "Book.Title") = ?' - * => 'CONCAT(book.TITLE, "Book.Title") = ?' - * - * @param array $matches Matches found by preg_replace_callback - * - * @return string the expression replacement - */ - protected function doReplaceName($matches) - { - if(!$matches[0]) { - return ''; - } - // replace names only in expressions, not in strings delimited by quotes - return $matches[1] . preg_replace_callback('/\w+\.\w+/', array($this, 'doReplaceNameInExpression'), $matches[2]); - } - - /** - * Callback function to replace column names by their real name in a clause - * e.g. 'Book.Title IN ?' - * => 'book.TITLE IN ?' - * - * @param array $matches Matches found by preg_replace_callback - * - * @return string the column name replacement - */ - protected function doReplaceNameInExpression($matches) - { - $key = $matches[0]; - list($column, $realColumnName) = $this->getColumnFromName($key); - if ($column instanceof ColumnMap) { - $this->replacedColumns[]= $column; - $this->foundMatch = true; - return $realColumnName; - } else { - return $key; - } - } - - /** - * Finds a column and a SQL translation for a pseudo SQL column name - * Respects table aliases previously registered in a join() or addAlias() - * Examples: - * - * $c->getColumnFromName('Book.Title'); - * => array($bookTitleColumnMap, 'book.TITLE') - * $c->join('Book.Author a') - * ->getColumnFromName('a.FirstName'); - * => array($authorFirstNameColumnMap, 'a.FIRST_NAME') - * - * - * @param string $phpName String representing the column name in a pseudo SQL clause, e.g. 'Book.Title' - * - * @return array List($columnMap, $realColumnName) - */ - protected function getColumnFromName($phpName, $failSilently = true) - { - if (strpos($phpName, '.') === false) { - $class = $this->getModelAliasOrName(); - } else { - list($class, $phpName) = explode('.', $phpName); - } - - if ($class == $this->getModelAliasOrName()) { - // column of the Criteria's model - $tableMap = $this->getTableMap(); - } elseif (isset($this->joins[$class])) { - // column of a relations's model - $tableMap = $this->joins[$class]->getTableMap(); - } else { - if ($failSilently) { - return array(null, null); - } else { - throw new PropelException('Unknown model or alias ' . $class); - } - } - - if ($tableMap->hasColumnByPhpName($phpName)) { - $column = $tableMap->getColumnByPhpName($phpName); - if (isset($this->aliases[$class])) { - $this->currentAlias = $class; - $realColumnName = $class . '.' . $column->getName(); - } else { - $realColumnName = $column->getFullyQualifiedName(); - } - return array($column, $realColumnName); - } elseif (isset($this->asColumns[$phpName])) { - // aliased column - return array(null, $phpName); - } else { - if ($failSilently) { - return array(null, null); - } else { - throw new PropelException('Unknown column ' . $phpName . ' on model or alias ' . $class); - } - } - } - - /** - * Return a fully qualified column name corresponding to a simple column phpName - * Uses model alias if it exists - * Warning: restricted to the columns of the main model - * e.g. => 'Title' => 'book.TITLE' - * - * @param string $columnName the Column phpName, without the table name - * - * @return string the fully qualified column name - */ - protected function getRealColumnName($columnName) - { - if (!$this->getTableMap()->hasColumnByPhpName($columnName)) { - throw new PropelException('Unkown column ' . $columnName . ' in model ' . $this->modelName); - } - if ($this->useAliasInSQL) { - return $this->modelAlias . '.' . $this->getTableMap()->getColumnByPhpName($columnName)->getName(); - } else { - return $this->getTableMap()->getColumnByPhpName($columnName)->getFullyQualifiedName(); - } - } - - /** - * Changes the table part of a a fully qualified column name if a true model alias exists - * e.g. => 'book.TITLE' => 'b.TITLE' - * This is for use as first argument of Criteria::add() - * - * @param string $colName the fully qualified column name, e.g 'book.TITLE' or BookPeer::TITLE - * - * @return string the fully qualified column name, using table alias if applicatble - */ - public function getAliasedColName($colName) - { - if ($this->useAliasInSQL) { - return $this->modelAlias . substr($colName, strpos($colName, '.')); - } else { - return $colName; - } - } - - /** - * Overrides Criteria::add() to force the use of a true table alias if it exists - * - * @see Criteria::add() - * @param string $column The colName of column to run the comparison on (e.g. BookPeer::ID) - * @param mixed $value - * @param string $comparison A String. - * - * @return ModelCriteria A modified Criteria object. - */ - public function addUsingAlias($p1, $value = null, $comparison = null) - { - $key = $this->getAliasedColName($p1); - return $this->containsKey($key) ? $this->addAnd($key, $value, $comparison) : $this->add($key, $value, $comparison); - } - - /** - * Get all the parameters to bind to this criteria - * Does part of the job of BasePeer::createSelectSql() for the cache - * - * @return array list of parameters, each parameter being an array like - * array('table' => $realtable, 'column' => $column, 'value' => $value) - */ - public function getParams() - { - $params = array(); - $dbMap = Propel::getDatabaseMap($this->getDbName()); - - foreach ($this->getMap() as $criterion) { - - $table = null; - foreach ($criterion->getAttachedCriterion() as $attachedCriterion) { - $tableName = $attachedCriterion->getTable(); - - $table = $this->getTableForAlias($tableName); - if (null === $table) { - $table = $tableName; - } - - if (($this->isIgnoreCase() || $attachedCriterion->isIgnoreCase()) - && $dbMap->getTable($table)->getColumn($attachedCriterion->getColumn())->isText()) { - $attachedCriterion->setIgnoreCase(true); - } - } - - $sb = ''; - $criterion->appendPsTo($sb, $params); - } - - $having = $this->getHaving(); - if ($having !== null) { - $sb = ''; - $having->appendPsTo($sb, $params); - } - - return $params; - } - - /** - * Handle the magic - * Supports findByXXX(), findOneByXXX(), filterByXXX(), orderByXXX(), and groupByXXX() methods, - * where XXX is a column phpName. - * Supports XXXJoin(), where XXX is a join direction (in 'left', 'right', 'inner') - */ - public function __call($name, $arguments) - { - // Maybe it's a magic call to one of the methods supporting it, e.g. 'findByTitle' - static $methods = array('findBy', 'findOneBy', 'filterBy', 'orderBy', 'groupBy'); - foreach ($methods as $method) - { - if(strpos($name, $method) === 0) - { - $columns = substr($name, strlen($method)); - if(in_array($method, array('findBy', 'findOneBy')) && strpos($columns, 'And') !== false) { - $method = $method . 'Array'; - $columns = explode('And', $columns); - $conditions = array(); - foreach ($columns as $column) { - $conditions[$column] = array_shift($arguments); - } - array_unshift($arguments, $conditions); - } else { - array_unshift($arguments, $columns); - } - return call_user_func_array(array($this, $method), $arguments); - } - } - - // Maybe it's a magic call to a qualified joinWith method, e.g. 'leftJoinWith' or 'joinWithAuthor' - if(($pos = stripos($name, 'joinWith')) !== false) { - $type = substr($name, 0, $pos); - if(in_array($type, array('left', 'right', 'inner'))) { - $joinType = strtoupper($type) . ' JOIN'; - } else { - $joinType = Criteria::INNER_JOIN; - } - if(!$relation = substr($name, $pos + 8)) { - $relation = $arguments[0]; - } - return $this->joinWith($relation, $joinType); - } - - // Maybe it's a magic call to a qualified join method, e.g. 'leftJoin' - if(($pos = strpos($name, 'Join')) > 0) - { - $type = substr($name, 0, $pos); - if(in_array($type, array('left', 'right', 'inner'))) - { - $joinType = strtoupper($type) . ' JOIN'; - // Test if first argument is suplied, else don't provide an alias to joinXXX (default value) - if (!isset($arguments[0])) { - $arguments[0] = ''; - } - array_push($arguments, $joinType); - $method = substr($name, $pos); - // no lcfirst in php<5.3... - $method[0] = strtolower($method[0]); - return call_user_func_array(array($this, $method), $arguments); - } - } - - throw new PropelException(sprintf('Undefined method %s::%s()', __CLASS__, $name)); - } - - /** - * Ensures deep cloning of attached objects - */ - public function __clone() - { - parent::__clone(); - foreach ($this->with as $key => $join) { - $this->with[$key] = clone $join; - } - if (null !== $this->formatter) { - $this->formatter = clone $this->formatter; - } - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/query/ModelCriterion.php b/airtime_mvc/library/propel/runtime/lib/query/ModelCriterion.php deleted file mode 100644 index beeeda79a..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/ModelCriterion.php +++ /dev/null @@ -1,283 +0,0 @@ -value = $value; - if ($column instanceof ColumnMap) { - $this->column = $column->getName(); - $this->table = $column->getTable()->getName(); - } else { - $dotPos = strrpos($column,'.'); - if ($dotPos === false) { - // no dot => aliased column - $this->table = null; - $this->column = $column; - } else { - $this->table = substr($column, 0, $dotPos); - $this->column = substr($column, $dotPos+1, strlen($column)); - } - } - $this->comparison = ($comparison === null ? Criteria::EQUAL : $comparison); - $this->clause = $clause; - $this->init($outer); - } - - public function getClause() - { - return $this->clause; - } - - /** - * Figure out which MocelCriterion method to use - * to build the prepared statement and parameters using to the Criterion comparison - * and call it to append the prepared statement and the parameters of the current clause. - * For performance reasons, this method tests the cases of parent::dispatchPsHandling() - * first, and that is not possible through inheritance ; that's why the parent - * code is duplicated here. - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - protected function dispatchPsHandling(&$sb, array &$params) - { - switch ($this->comparison) { - case Criteria::CUSTOM: - // custom expression with no parameter binding - $this->appendCustomToPs($sb, $params); - break; - case Criteria::IN: - case Criteria::NOT_IN: - // table.column IN (?, ?) or table.column NOT IN (?, ?) - $this->appendInToPs($sb, $params); - break; - case Criteria::LIKE: - case Criteria::NOT_LIKE: - case Criteria::ILIKE: - case Criteria::NOT_ILIKE: - // table.column LIKE ? or table.column NOT LIKE ? (or ILIKE for Postgres) - $this->appendLikeToPs($sb, $params); - break; - case ModelCriteria::MODEL_CLAUSE: - // regular model clause, e.g. 'book.TITLE = ?' - $this->appendModelClauseToPs($sb, $params); - break; - case ModelCriteria::MODEL_CLAUSE_LIKE: - // regular model clause, e.g. 'book.TITLE = ?' - $this->appendModelClauseLikeToPs($sb, $params); - break; - case ModelCriteria::MODEL_CLAUSE_SEVERAL: - // Ternary model clause, e.G 'book.ID BETWEEN ? AND ?' - $this->appendModelClauseSeveralToPs($sb, $params); - break; - case ModelCriteria::MODEL_CLAUSE_ARRAY: - // IN or NOT IN model clause, e.g. 'book.TITLE NOT IN ?' - $this->appendModelClauseArrayToPs($sb, $params); - break; - default: - // table.column = ? or table.column >= ? etc. (traditional expressions, the default) - $this->appendBasicToPs($sb, $params); - - } - } - - /** - * Appends a Prepared Statement representation of the ModelCriterion onto the buffer - * For regular model clauses, e.g. 'book.TITLE = ?' - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - public function appendModelClauseToPs(&$sb, array &$params) - { - if ($this->value !== null) { - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $this->value); - $sb .= str_replace('?', ':p'.count($params), $this->clause); - } else { - $sb .= $this->clause; - } - } - - /** - * Appends a Prepared Statement representation of the ModelCriterion onto the buffer - * For LIKE model clauses, e.g. 'book.TITLE LIKE ?' - * Handles case insensitivity for VARCHAR columns - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - public function appendModelClauseLikeToPs(&$sb, array &$params) - { - // LIKE is case insensitive in mySQL and SQLite, but not in PostGres - // If the column is case insensitive, use ILIKE / NOT ILIKE instead of LIKE / NOT LIKE - if ($this->ignoreStringCase && $this->getDb() instanceof DBPostgres) { - $this->clause = preg_replace('/LIKE \?$/i', 'ILIKE ?', $this->clause); - } - $this->appendModelClauseToPs($sb, $params); - } - - /** - * Appends a Prepared Statement representation of the ModelCriterion onto the buffer - * For ternary model clauses, e.G 'book.ID BETWEEN ? AND ?' - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - public function appendModelClauseSeveralToPs(&$sb, array &$params) - { - $clause = $this->clause; - foreach ((array) $this->value as $value) { - if ($value === null) { - // FIXME we eventually need to translate a BETWEEN to - // something like WHERE (col < :p1 OR :p1 IS NULL) AND (col < :p2 OR :p2 IS NULL) - // in order to support null values - throw new PropelException('Null values are not supported inside BETWEEN clauses'); - } - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $value); - $clause = self::strReplaceOnce('?', ':p'.count($params), $clause); - } - $sb .= $clause; - } - - /** - * Appends a Prepared Statement representation of the ModelCriterion onto the buffer - * For IN or NOT IN model clauses, e.g. 'book.TITLE NOT IN ?' - * - * @param string &$sb The string that will receive the Prepared Statement - * @param array $params A list to which Prepared Statement parameters will be appended - */ - public function appendModelClauseArrayToPs(&$sb, array &$params) - { - $_bindParams = array(); // the param names used in query building - $_idxstart = count($params); - $valuesLength = 0; - foreach ( (array) $this->value as $value ) { - $valuesLength++; // increment this first to correct for wanting bind params to start with :p1 - $params[] = array('table' => $this->realtable, 'column' => $this->column, 'value' => $value); - $_bindParams[] = ':p'.($_idxstart + $valuesLength); - } - if ($valuesLength !== 0) { - $sb .= str_replace('?', '(' . implode(',', $_bindParams) . ')', $this->clause); - } else { - $sb .= (stripos($this->clause, ' NOT IN ') === false) ? "1<>1" : "1=1"; - } - unset ( $value, $valuesLength ); - } - - /** - * This method checks another Criteria to see if they contain - * the same attributes and hashtable entries. - * @return boolean - */ - public function equals($obj) - { - // TODO: optimize me with early outs - if ($this === $obj) { - return true; - } - - if (($obj === null) || !($obj instanceof ModelCriterion)) { - return false; - } - - $crit = $obj; - - $isEquiv = ( ( ($this->table === null && $crit->getTable() === null) - || ( $this->table !== null && $this->table === $crit->getTable() ) - ) - && $this->clause === $crit->getClause() - && $this->column === $crit->getColumn() - && $this->comparison === $crit->getComparison()); - - // check chained criterion - - $clausesLength = count($this->clauses); - $isEquiv &= (count($crit->getClauses()) == $clausesLength); - $critConjunctions = $crit->getConjunctions(); - $critClauses = $crit->getClauses(); - for ($i=0; $i < $clausesLength && $isEquiv; $i++) { - $isEquiv &= ($this->conjunctions[$i] === $critConjunctions[$i]); - $isEquiv &= ($this->clauses[$i] === $critClauses[$i]); - } - - if ($isEquiv) { - $isEquiv &= $this->value === $crit->getValue(); - } - - return $isEquiv; - } - - /** - * Returns a hash code value for the object. - */ - public function hashCode() - { - $h = crc32(serialize($this->value)) ^ crc32($this->comparison) ^ crc32($this->clause); - - if ($this->table !== null) { - $h ^= crc32($this->table); - } - - if ($this->column !== null) { - $h ^= crc32($this->column); - } - - foreach ( $this->clauses as $clause ) { - // TODO: i KNOW there is a php incompatibility with the following line - // but i dont remember what it is, someone care to look it up and - // replace it if it doesnt bother us? - // $clause->appendPsTo($sb='',$params=array()); - $sb = ''; - $params = array(); - $clause->appendPsTo($sb,$params); - $h ^= crc32(serialize(array($sb,$params))); - unset ( $sb, $params ); - } - - return $h; - } - - /** - * Replace only once - * taken from http://www.php.net/manual/en/function.str-replace.php - * - */ - protected static function strReplaceOnce($search, $replace, $subject) - { - $firstChar = strpos($subject, $search); - if($firstChar !== false) { - $beforeStr = substr($subject,0,$firstChar); - $afterStr = substr($subject, $firstChar + strlen($search)); - return $beforeStr.$replace.$afterStr; - } else { - return $subject; - } - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/query/ModelJoin.php b/airtime_mvc/library/propel/runtime/lib/query/ModelJoin.php deleted file mode 100644 index 59bbfce5d..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/ModelJoin.php +++ /dev/null @@ -1,166 +0,0 @@ -getLeftColumns(); - $rightCols = $relationMap->getRightColumns(); - $nbColumns = $relationMap->countColumnMappings(); - for ($i=0; $i < $nbColumns; $i++) { - $leftColName = ($leftTableAlias ? $leftTableAlias : $leftCols[$i]->getTableName()) . '.' . $leftCols[$i]->getName(); - $rightColName = ($relationAlias ? $relationAlias : $rightCols[$i]->getTableName()) . '.' . $rightCols[$i]->getName(); - $this->addCondition($leftColName, $rightColName, Criteria::EQUAL); - } - $this->relationMap = $relationMap; - $this->leftTableAlias = $leftTableAlias; - $this->relationAlias = $relationAlias; - - return $this; - } - - public function getRelationMap() - { - return $this->relationMap; - } - - /** - * Sets the right tableMap for this join - * - * @param TableMap $tableMap The table map to use - * - * @return ModelJoin The current join object, for fluid interface - */ - public function setTableMap(TableMap $tableMap) - { - $this->tableMap = $tableMap; - - return $this; - } - - /** - * Gets the right tableMap for this join - * - * @return TableMap The table map - */ - public function getTableMap() - { - if (null === $this->tableMap && null !== $this->relationMap) - { - $this->tableMap = $this->relationMap->getRightTable(); - } - return $this->tableMap; - } - - public function setPreviousJoin(ModelJoin $join) - { - $this->previousJoin = $join; - - return $this; - } - - public function getPreviousJoin() - { - return $this->previousJoin; - } - - public function isPrimary() - { - return null === $this->previousJoin; - } - - public function setLeftTableAlias($leftTableAlias) - { - $this->leftTableAlias = $leftTableAlias; - - return $this; - } - - public function getLeftTableAlias() - { - return $this->leftTableAlias; - } - - public function hasLeftTableAlias() - { - return null !== $this->leftTableAlias; - } - - public function setRelationAlias($relationAlias) - { - $this->relationAlias = $relationAlias; - - return $this; - } - - public function getRelationAlias() - { - return $this->relationAlias; - } - - public function hasRelationAlias() - { - return null !== $this->relationAlias; - } - - /** - * This method returns the last related, but already hydrated object up until this join - * Starting from $startObject and continuously calling the getters to get - * to the base object for the current join. - * - * This method only works if PreviousJoin has been defined, - * which only happens when you provide dotted relations when calling join - * - * @param Object $startObject the start object all joins originate from and which has already hydrated - * @return Object the base Object of this join - */ - public function getObjectToRelate($startObject) - { - if($this->isPrimary()) { - return $startObject; - } else { - $previousJoin = $this->getPreviousJoin(); - $previousObject = $previousJoin->getObjectToRelate($startObject); - $method = 'get' . $previousJoin->getRelationMap()->getName(); - return $previousObject->$method(); - } - } - - public function equals($join) - { - return parent::equals($join) - && $this->relationMap == $join->getRelationMap() - && $this->previousJoin == $join->getPreviousJoin() - && $this->relationAlias == $join->getRelationAlias(); - } - - public function __toString() - { - return parent::toString() - . ' tableMap: ' . ($this->tableMap ? get_class($this->tableMap) : 'null') - . ' relationMap: ' . $this->relationMap->getName() - . ' previousJoin: ' . ($this->previousJoin ? '(' . $this->previousJoin . ')' : 'null') - . ' relationAlias: ' . $this->relationAlias; - } -} - \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/query/PropelQuery.php b/airtime_mvc/library/propel/runtime/lib/query/PropelQuery.php deleted file mode 100644 index 18f93c9b9..000000000 --- a/airtime_mvc/library/propel/runtime/lib/query/PropelQuery.php +++ /dev/null @@ -1,33 +0,0 @@ -setModelAlias($alias); - } - return $query; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/BasePeer.php b/airtime_mvc/library/propel/runtime/lib/util/BasePeer.php deleted file mode 100644 index 0e6c91254..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/BasePeer.php +++ /dev/null @@ -1,1099 +0,0 @@ - (Propel) - * @author Kaspars Jaudzems (Propel) - * @author Heltem (Propel) - * @author Frank Y. Kim (Torque) - * @author John D. McNally (Torque) - * @author Brett McLaughlin (Torque) - * @author Stephen Haberman (Torque) - * @version $Revision: 1772 $ - * @package propel.runtime.util - */ -class BasePeer -{ - - /** Array (hash) that contains the cached mapBuilders. */ - private static $mapBuilders = array(); - - /** Array (hash) that contains cached validators */ - private static $validatorMap = array(); - - /** - * phpname type - * e.g. 'AuthorId' - */ - const TYPE_PHPNAME = 'phpName'; - - /** - * studlyphpname type - * e.g. 'authorId' - */ - const TYPE_STUDLYPHPNAME = 'studlyPhpName'; - - /** - * column (peer) name type - * e.g. 'book.AUTHOR_ID' - */ - const TYPE_COLNAME = 'colName'; - - /** - * column part of the column peer name - * e.g. 'AUTHOR_ID' - */ - const TYPE_RAW_COLNAME = 'rawColName'; - - /** - * column fieldname type - * e.g. 'author_id' - */ - const TYPE_FIELDNAME = 'fieldName'; - - /** - * num type - * simply the numerical array index, e.g. 4 - */ - const TYPE_NUM = 'num'; - - static public function getFieldnames ($classname, $type = self::TYPE_PHPNAME) { - - // TODO we should take care of including the peer class here - - $peerclass = 'Base' . $classname . 'Peer'; // TODO is this always true? - $callable = array($peerclass, 'getFieldnames'); - - return call_user_func($callable, $type); - } - - static public function translateFieldname($classname, $fieldname, $fromType, $toType) { - - // TODO we should take care of including the peer class here - - $peerclass = 'Base' . $classname . 'Peer'; // TODO is this always true? - $callable = array($peerclass, 'translateFieldname'); - $args = array($fieldname, $fromType, $toType); - - return call_user_func_array($callable, $args); - } - - /** - * Method to perform deletes based on values and keys in a - * Criteria. - * - * @param Criteria $criteria The criteria to use. - * @param PropelPDO $con A PropelPDO connection object. - * @return int The number of rows affected by last statement execution. For most - * uses there is only one delete statement executed, so this number - * will correspond to the number of rows affected by the call to this - * method. Note that the return value does require that this information - * is returned (supported) by the PDO driver. - * @throws PropelException - */ - public static function doDelete(Criteria $criteria, PropelPDO $con) - { - $db = Propel::getDB($criteria->getDbName()); - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - - // Set up a list of required tables (one DELETE statement will - // be executed per table) - $tables = $criteria->getTablesColumns(); - if (empty($tables)) { - throw new PropelException("Cannot delete from an empty Criteria"); - } - - $affectedRows = 0; // initialize this in case the next loop has no iterations. - - foreach ($tables as $tableName => $columns) { - - $whereClause = array(); - $params = array(); - $stmt = null; - try { - $sql = 'DELETE '; - if ($queryComment = $criteria->getComment()) { - $sql .= '/* ' . $queryComment . ' */ '; - } - if ($realTableName = $criteria->getTableForAlias($tableName)) { - if ($db->useQuoteIdentifier()) { - $realTableName = $db->quoteIdentifierTable($realTableName); - } - $sql .= $tableName . ' FROM ' . $realTableName . ' AS ' . $tableName; - } else { - if ($db->useQuoteIdentifier()) { - $tableName = $db->quoteIdentifierTable($tableName); - } - $sql .= 'FROM ' . $tableName; - } - - foreach ($columns as $colName) { - $sb = ""; - $criteria->getCriterion($colName)->appendPsTo($sb, $params); - $whereClause[] = $sb; - } - $sql .= " WHERE " . implode(" AND ", $whereClause); - - $stmt = $con->prepare($sql); - self::populateStmtValues($stmt, $params, $dbMap, $db); - $stmt->execute(); - $affectedRows = $stmt->rowCount(); - } catch (Exception $e) { - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute DELETE statement [%s]', $sql), $e); - } - - } // for each table - - return $affectedRows; - } - - /** - * Method to deletes all contents of specified table. - * - * This method is invoked from generated Peer classes like this: - * - * public static function doDeleteAll($con = null) - * { - * if ($con === null) $con = Propel::getConnection(self::DATABASE_NAME); - * BasePeer::doDeleteAll(self::TABLE_NAME, $con, self::DATABASE_NAME); - * } - * - * - * @param string $tableName The name of the table to empty. - * @param PropelPDO $con A PropelPDO connection object. - * @param string $databaseName the name of the database. - * @return int The number of rows affected by the statement. Note - * that the return value does require that this information - * is returned (supported) by the Propel db driver. - * @throws PropelException - wrapping SQLException caught from statement execution. - */ - public static function doDeleteAll($tableName, PropelPDO $con, $databaseName = null) - { - try { - $db = Propel::getDB($databaseName); - if ($db->useQuoteIdentifier()) { - $tableName = $db->quoteIdentifierTable($tableName); - } - $sql = "DELETE FROM " . $tableName; - $stmt = $con->prepare($sql); - $stmt->execute(); - return $stmt->rowCount(); - } catch (Exception $e) { - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute DELETE ALL statement [%s]', $sql), $e); - } - } - - /** - * Method to perform inserts based on values and keys in a - * Criteria. - *

- * If the primary key is auto incremented the data in Criteria - * will be inserted and the auto increment value will be returned. - *

- * If the primary key is included in Criteria then that value will - * be used to insert the row. - *

- * If no primary key is included in Criteria then we will try to - * figure out the primary key from the database map and insert the - * row with the next available id using util.db.IDBroker. - *

- * If no primary key is defined for the table the values will be - * inserted as specified in Criteria and null will be returned. - * - * @param Criteria $criteria Object containing values to insert. - * @param PropelPDO $con A PropelPDO connection. - * @return mixed The primary key for the new row if (and only if!) the primary key - * is auto-generated. Otherwise will return null. - * @throws PropelException - */ - public static function doInsert(Criteria $criteria, PropelPDO $con) { - - // the primary key - $id = null; - - $db = Propel::getDB($criteria->getDbName()); - - // Get the table name and method for determining the primary - // key value. - $keys = $criteria->keys(); - if (!empty($keys)) { - $tableName = $criteria->getTableName( $keys[0] ); - } else { - throw new PropelException("Database insert attempted without anything specified to insert"); - } - - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - $tableMap = $dbMap->getTable($tableName); - $keyInfo = $tableMap->getPrimaryKeyMethodInfo(); - $useIdGen = $tableMap->isUseIdGenerator(); - //$keyGen = $con->getIdGenerator(); - - $pk = self::getPrimaryKey($criteria); - - // only get a new key value if you need to - // the reason is that a primary key might be defined - // but you are still going to set its value. for example: - // a join table where both keys are primary and you are - // setting both columns with your own values - - // pk will be null if there is no primary key defined for the table - // we're inserting into. - if ($pk !== null && $useIdGen && !$criteria->keyContainsValue($pk->getFullyQualifiedName()) && $db->isGetIdBeforeInsert()) { - try { - $id = $db->getId($con, $keyInfo); - } catch (Exception $e) { - throw new PropelException("Unable to get sequence id.", $e); - } - $criteria->add($pk->getFullyQualifiedName(), $id); - } - - try { - $adapter = Propel::getDB($criteria->getDBName()); - - $qualifiedCols = $criteria->keys(); // we need table.column cols when populating values - $columns = array(); // but just 'column' cols for the SQL - foreach ($qualifiedCols as $qualifiedCol) { - $columns[] = substr($qualifiedCol, strrpos($qualifiedCol, '.') + 1); - } - - // add identifiers - if ($adapter->useQuoteIdentifier()) { - $columns = array_map(array($adapter, 'quoteIdentifier'), $columns); - $tableName = $adapter->quoteIdentifierTable($tableName); - } - - $sql = 'INSERT INTO ' . $tableName - . ' (' . implode(',', $columns) . ')' - . ' VALUES ('; - // . substr(str_repeat("?,", count($columns)), 0, -1) . - for($p=1, $cnt=count($columns); $p <= $cnt; $p++) { - $sql .= ':p'.$p; - if ($p !== $cnt) $sql .= ','; - } - $sql .= ')'; - - $stmt = $con->prepare($sql); - self::populateStmtValues($stmt, self::buildParams($qualifiedCols, $criteria), $dbMap, $db); - $stmt->execute(); - - } catch (Exception $e) { - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e); - } - - // If the primary key column is auto-incremented, get the id now. - if ($pk !== null && $useIdGen && $db->isGetIdAfterInsert()) { - try { - $id = $db->getId($con, $keyInfo); - } catch (Exception $e) { - throw new PropelException("Unable to get autoincrement id.", $e); - } - } - - return $id; - } - - /** - * Method used to update rows in the DB. Rows are selected based - * on selectCriteria and updated using values in updateValues. - *

- * Use this method for performing an update of the kind: - *

- * WHERE some_column = some value AND could_have_another_column = - * another value AND so on. - * - * @param $selectCriteria A Criteria object containing values used in where - * clause. - * @param $updateValues A Criteria object containing values used in set - * clause. - * @param PropelPDO $con The PropelPDO connection object to use. - * @return int The number of rows affected by last update statement. For most - * uses there is only one update statement executed, so this number - * will correspond to the number of rows affected by the call to this - * method. Note that the return value does require that this information - * is returned (supported) by the Propel db driver. - * @throws PropelException - */ - public static function doUpdate(Criteria $selectCriteria, Criteria $updateValues, PropelPDO $con) { - - $db = Propel::getDB($selectCriteria->getDbName()); - $dbMap = Propel::getDatabaseMap($selectCriteria->getDbName()); - - // Get list of required tables, containing all columns - $tablesColumns = $selectCriteria->getTablesColumns(); - if (empty($tablesColumns)) { - $tablesColumns = array($selectCriteria->getPrimaryTableName() => array()); - } - - // we also need the columns for the update SQL - $updateTablesColumns = $updateValues->getTablesColumns(); - - $affectedRows = 0; // initialize this in case the next loop has no iterations. - - foreach ($tablesColumns as $tableName => $columns) { - - $whereClause = array(); - $params = array(); - $stmt = null; - try { - $sql = 'UPDATE '; - if ($queryComment = $selectCriteria->getComment()) { - $sql .= '/* ' . $queryComment . ' */ '; - } - // is it a table alias? - if ($tableName2 = $selectCriteria->getTableForAlias($tableName)) { - $udpateTable = $tableName2 . ' ' . $tableName; - $tableName = $tableName2; - } else { - $udpateTable = $tableName; - } - if ($db->useQuoteIdentifier()) { - $sql .= $db->quoteIdentifierTable($udpateTable); - } else { - $sql .= $udpateTable; - } - $sql .= " SET "; - $p = 1; - foreach ($updateTablesColumns[$tableName] as $col) { - $updateColumnName = substr($col, strrpos($col, '.') + 1); - // add identifiers for the actual database? - if ($db->useQuoteIdentifier()) { - $updateColumnName = $db->quoteIdentifier($updateColumnName); - } - if ($updateValues->getComparison($col) != Criteria::CUSTOM_EQUAL) { - $sql .= $updateColumnName . '=:p'.$p++.', '; - } else { - $param = $updateValues->get($col); - $sql .= $updateColumnName . ' = '; - if (is_array($param)) { - if (isset($param['raw'])) { - $raw = $param['raw']; - $rawcvt = ''; - // parse the $params['raw'] for ? chars - for($r=0,$len=strlen($raw); $r < $len; $r++) { - if ($raw{$r} == '?') { - $rawcvt .= ':p'.$p++; - } else { - $rawcvt .= $raw{$r}; - } - } - $sql .= $rawcvt . ', '; - } else { - $sql .= ':p'.$p++.', '; - } - if (isset($param['value'])) { - $updateValues->put($col, $param['value']); - } - } else { - $updateValues->remove($col); - $sql .= $param . ', '; - } - } - } - - $params = self::buildParams($updateTablesColumns[$tableName], $updateValues); - - $sql = substr($sql, 0, -2); - if (!empty($columns)) { - foreach ($columns as $colName) { - $sb = ""; - $selectCriteria->getCriterion($colName)->appendPsTo($sb, $params); - $whereClause[] = $sb; - } - $sql .= " WHERE " . implode(" AND ", $whereClause); - } - - $stmt = $con->prepare($sql); - - // Replace ':p?' with the actual values - self::populateStmtValues($stmt, $params, $dbMap, $db); - - $stmt->execute(); - - $affectedRows = $stmt->rowCount(); - - $stmt = null; // close - - } catch (Exception $e) { - if ($stmt) $stmt = null; // close - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute UPDATE statement [%s]', $sql), $e); - } - - } // foreach table in the criteria - - return $affectedRows; - } - - /** - * Executes query build by createSelectSql() and returns the resultset statement. - * - * @param Criteria $criteria A Criteria. - * @param PropelPDO $con A PropelPDO connection to use. - * @return PDOStatement The resultset. - * @throws PropelException - * @see createSelectSql() - */ - public static function doSelect(Criteria $criteria, PropelPDO $con = null) - { - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - $db = Propel::getDB($criteria->getDbName()); - $stmt = null; - - if ($con === null) { - $con = Propel::getConnection($criteria->getDbName(), Propel::CONNECTION_READ); - } - - if ($criteria->isUseTransaction()) { - $con->beginTransaction(); - } - - try { - - $params = array(); - $sql = self::createSelectSql($criteria, $params); - - $stmt = $con->prepare($sql); - - self::populateStmtValues($stmt, $params, $dbMap, $db); - - $stmt->execute(); - - if ($criteria->isUseTransaction()) { - $con->commit(); - } - - } catch (Exception $e) { - if ($stmt) { - $stmt = null; // close - } - if ($criteria->isUseTransaction()) { - $con->rollBack(); - } - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e); - } - - return $stmt; - } - - /** - * Executes a COUNT query using either a simple SQL rewrite or, for more complex queries, a - * sub-select of the SQL created by createSelectSql() and returns the statement. - * - * @param Criteria $criteria A Criteria. - * @param PropelPDO $con A PropelPDO connection to use. - * @return PDOStatement The resultset statement. - * @throws PropelException - * @see createSelectSql() - */ - public static function doCount(Criteria $criteria, PropelPDO $con = null) - { - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - $db = Propel::getDB($criteria->getDbName()); - - if ($con === null) { - $con = Propel::getConnection($criteria->getDbName(), Propel::CONNECTION_READ); - } - - $stmt = null; - - if ($criteria->isUseTransaction()) { - $con->beginTransaction(); - } - - $needsComplexCount = $criteria->getGroupByColumns() - || $criteria->getOffset() - || $criteria->getLimit() - || $criteria->getHaving() - || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers()); - - try { - - $params = array(); - - if ($needsComplexCount) { - if (self::needsSelectAliases($criteria)) { - if ($criteria->getHaving()) { - throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part'); - } - self::turnSelectColumnsToAliases($criteria); - } - $selectSql = self::createSelectSql($criteria, $params); - $sql = 'SELECT COUNT(*) FROM (' . $selectSql . ') propelmatch4cnt'; - } else { - // Replace SELECT columns with COUNT(*) - $criteria->clearSelectColumns()->addSelectColumn('COUNT(*)'); - $sql = self::createSelectSql($criteria, $params); - } - - $stmt = $con->prepare($sql); - self::populateStmtValues($stmt, $params, $dbMap, $db); - $stmt->execute(); - - if ($criteria->isUseTransaction()) { - $con->commit(); - } - - } catch (Exception $e) { - if ($stmt !== null) { - $stmt = null; - } - if ($criteria->isUseTransaction()) { - $con->rollBack(); - } - Propel::log($e->getMessage(), Propel::LOG_ERR); - throw new PropelException(sprintf('Unable to execute COUNT statement [%s]', $sql), $e); - } - - return $stmt; - } - - /** - * Populates values in a prepared statement. - * - * This method is designed to work with the createSelectSql() method, which creates - * both the SELECT SQL statement and populates a passed-in array of parameter - * values that should be substituted. - * - * - * $params = array(); - * $sql = BasePeer::createSelectSql($criteria, $params); - * BasePeer::populateStmtValues($stmt, $params, Propel::getDatabaseMap($critera->getDbName()), Propel::getDB($criteria->getDbName())); - * - * - * @param PDOStatement $stmt - * @param array $params array('column' => ..., 'table' => ..., 'value' => ...) - * @param DatabaseMap $dbMap - * @return int The number of params replaced. - * @see createSelectSql() - * @see doSelect() - */ - public static function populateStmtValues(PDOStatement $stmt, array $params, DatabaseMap $dbMap, DBAdapter $db) - { - $i = 1; - foreach ($params as $param) { - $tableName = $param['table']; - $columnName = $param['column']; - $value = $param['value']; - - if (null === $value) { - - $stmt->bindValue(':p'.$i++, null, PDO::PARAM_NULL); - - } elseif (null !== $tableName) { - - $cMap = $dbMap->getTable($tableName)->getColumn($columnName); - $type = $cMap->getType(); - $pdoType = $cMap->getPdoType(); - - // FIXME - This is a temporary hack to get around apparent bugs w/ PDO+MYSQL - // See http://pecl.php.net/bugs/bug.php?id=9919 - if ($pdoType == PDO::PARAM_BOOL && $db instanceof DBMySQL) { - $value = (int) $value; - $pdoType = PDO::PARAM_INT; - } elseif (is_numeric($value) && $cMap->isEpochTemporal()) { // it's a timestamp that needs to be formatted - if ($type == PropelColumnTypes::TIMESTAMP) { - $value = date($db->getTimestampFormatter(), $value); - } else if ($type == PropelColumnTypes::DATE) { - $value = date($db->getDateFormatter(), $value); - } else if ($type == PropelColumnTypes::TIME) { - $value = date($db->getTimeFormatter(), $value); - } - } elseif ($value instanceof DateTime && $cMap->isTemporal()) { // it's a timestamp that needs to be formatted - if ($type == PropelColumnTypes::TIMESTAMP || $type == PropelColumnTypes::BU_TIMESTAMP) { - $value = $value->format($db->getTimestampFormatter()); - } else if ($type == PropelColumnTypes::DATE || $type == PropelColumnTypes::BU_DATE) { - $value = $value->format($db->getDateFormatter()); - } else if ($type == PropelColumnTypes::TIME) { - $value = $value->format($db->getTimeFormatter()); - } - } elseif (is_resource($value) && $cMap->isLob()) { - // we always need to make sure that the stream is rewound, otherwise nothing will - // get written to database. - rewind($value); - } - - $stmt->bindValue(':p'.$i++, $value, $pdoType); - } else { - $stmt->bindValue(':p'.$i++, $value); - } - } // foreach - } - - /** - * Applies any validators that were defined in the schema to the specified columns. - * - * @param string $dbName The name of the database - * @param string $tableName The name of the table - * @param array $columns Array of column names as key and column values as value. - */ - public static function doValidate($dbName, $tableName, $columns) - { - $dbMap = Propel::getDatabaseMap($dbName); - $tableMap = $dbMap->getTable($tableName); - $failureMap = array(); // map of ValidationFailed objects - foreach ($columns as $colName => $colValue) { - if ($tableMap->containsColumn($colName)) { - $col = $tableMap->getColumn($colName); - foreach ($col->getValidators() as $validatorMap) { - $validator = BasePeer::getValidator($validatorMap->getClass()); - if ($validator && ($col->isNotNull() || $colValue !== null) && $validator->isValid($validatorMap, $colValue) === false) { - if (!isset($failureMap[$colName])) { // for now we do one ValidationFailed per column, not per rule - $failureMap[$colName] = new ValidationFailed($colName, $validatorMap->getMessage(), $validator); - } - } - } - } - } - return (!empty($failureMap) ? $failureMap : true); - } - - /** - * Helper method which returns the primary key contained - * in the given Criteria object. - * - * @param Criteria $criteria A Criteria. - * @return ColumnMap If the Criteria object contains a primary - * key, or null if it doesn't. - * @throws PropelException - */ - private static function getPrimaryKey(Criteria $criteria) - { - // Assume all the keys are for the same table. - $keys = $criteria->keys(); - $key = $keys[0]; - $table = $criteria->getTableName($key); - - $pk = null; - - if (!empty($table)) { - - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - - $pks = $dbMap->getTable($table)->getPrimaryKeys(); - if (!empty($pks)) { - $pk = array_shift($pks); - } - } - return $pk; - } - - /** - * Checks whether the Criteria needs to use column aliasing - * This is implemented in a service class rather than in Criteria itself - * in order to avoid doing the tests when it's not necessary (e.g. for SELECTs) - */ - public static function needsSelectAliases(Criteria $criteria) - { - $columnNames = array(); - foreach ($criteria->getSelectColumns() as $fullyQualifiedColumnName) { - if ($pos = strrpos($fullyQualifiedColumnName, '.')) { - $columnName = substr($fullyQualifiedColumnName, $pos); - if (isset($columnNames[$columnName])) { - // more than one column with the same name, so aliasing is required - return true; - } - $columnNames[$columnName] = true; - } - } - return false; - } - - /** - * Ensures uniqueness of select column names by turning them all into aliases - * This is necessary for queries on more than one table when the tables share a column name - * @see http://propel.phpdb.org/trac/ticket/795 - * - * @param Criteria $criteria - * - * @return Criteria The input, with Select columns replaced by aliases - */ - public static function turnSelectColumnsToAliases(Criteria $criteria) - { - $selectColumns = $criteria->getSelectColumns(); - // clearSelectColumns also clears the aliases, so get them too - $asColumns = $criteria->getAsColumns(); - $criteria->clearSelectColumns(); - $columnAliases = $asColumns; - // add the select columns back - foreach ($selectColumns as $clause) { - // Generate a unique alias - $baseAlias = preg_replace('/\W/', '_', $clause); - $alias = $baseAlias; - // If it already exists, add a unique suffix - $i = 0; - while (isset($columnAliases[$alias])) { - $i++; - $alias = $baseAlias . '_' . $i; - } - // Add it as an alias - $criteria->addAsColumn($alias, $clause); - $columnAliases[$alias] = $clause; - } - // Add the aliases back, don't modify them - foreach ($asColumns as $name => $clause) { - $criteria->addAsColumn($name, $clause); - } - - return $criteria; - } - - /** - * Method to create an SQL query based on values in a Criteria. - * - * This method creates only prepared statement SQL (using ? where values - * will go). The second parameter ($params) stores the values that need - * to be set before the statement is executed. The reason we do it this way - * is to let the PDO layer handle all escaping & value formatting. - * - * @param Criteria $criteria Criteria for the SELECT query. - * @param array &$params Parameters that are to be replaced in prepared statement. - * @return string - * @throws PropelException Trouble creating the query string. - */ - public static function createSelectSql(Criteria $criteria, &$params) - { - $db = Propel::getDB($criteria->getDbName()); - $dbMap = Propel::getDatabaseMap($criteria->getDbName()); - - $fromClause = array(); - $joinClause = array(); - $joinTables = array(); - $whereClause = array(); - $orderByClause = array(); - - $orderBy = $criteria->getOrderByColumns(); - $groupBy = $criteria->getGroupByColumns(); - $ignoreCase = $criteria->isIgnoreCase(); - - // get the first part of the SQL statement, the SELECT part - $selectSql = self::createSelectSqlPart($criteria, $fromClause); - - // add the criteria to WHERE clause - // this will also add the table names to the FROM clause if they are not already - // included via a LEFT JOIN - foreach ($criteria->keys() as $key) { - - $criterion = $criteria->getCriterion($key); - $table = null; - foreach ($criterion->getAttachedCriterion() as $attachedCriterion) { - $tableName = $attachedCriterion->getTable(); - - $table = $criteria->getTableForAlias($tableName); - if ($table !== null) { - $fromClause[] = $table . ' ' . $tableName; - } else { - $fromClause[] = $tableName; - $table = $tableName; - } - - if (($criteria->isIgnoreCase() || $attachedCriterion->isIgnoreCase()) - && $dbMap->getTable($table)->getColumn($attachedCriterion->getColumn())->isText()) { - $attachedCriterion->setIgnoreCase(true); - } - } - - $criterion->setDB($db); - - $sb = ''; - $criterion->appendPsTo($sb, $params); - $whereClause[] = $sb; - } - - // Handle joins - // joins with a null join type will be added to the FROM clause and the condition added to the WHERE clause. - // joins of a specified type: the LEFT side will be added to the fromClause and the RIGHT to the joinClause - foreach ($criteria->getJoins() as $join) { - // The join might have been established using an alias name - $leftTable = $join->getLeftTableName(); - if ($realTable = $criteria->getTableForAlias($leftTable)) { - $leftTableForFrom = $realTable . ' ' . $leftTable; - $leftTable = $realTable; - } else { - $leftTableForFrom = $leftTable; - } - - $rightTable = $join->getRightTableName(); - if ($realTable = $criteria->getTableForAlias($rightTable)) { - $rightTableForFrom = $realTable . ' ' . $rightTable; - $rightTable = $realTable; - } else { - $rightTableForFrom = $rightTable; - } - - // determine if casing is relevant. - if ($ignoreCase = $criteria->isIgnoreCase()) { - $leftColType = $dbMap->getTable($leftTable)->getColumn($join->getLeftColumnName())->getType(); - $rightColType = $dbMap->getTable($rightTable)->getColumn($join->getRightColumnName())->getType(); - $ignoreCase = ($leftColType == 'string' || $rightColType == 'string'); - } - - // build the condition - $condition = ''; - foreach ($join->getConditions() as $index => $conditionDesc) { - if ($ignoreCase) { - $condition .= $db->ignoreCase($conditionDesc['left']) . $conditionDesc['operator'] . $db->ignoreCase($conditionDesc['right']); - } else { - $condition .= implode($conditionDesc); - } - if ($index + 1 < $join->countConditions()) { - $condition .= ' AND '; - } - } - - // add 'em to the queues.. - if ($joinType = $join->getJoinType()) { - // real join - if (!$fromClause) { - $fromClause[] = $leftTableForFrom; - } - $joinTables[] = $rightTableForFrom; - $joinClause[] = $join->getJoinType() . ' ' . $rightTableForFrom . " ON ($condition)"; - } else { - // implicit join, translates to a where - $fromClause[] = $leftTableForFrom; - $fromClause[] = $rightTableForFrom; - $whereClause[] = $condition; - } - } - - // Unique from clause elements - $fromClause = array_unique($fromClause); - $fromClause = array_diff($fromClause, array('')); - - // tables should not exist in both the from and join clauses - if ($joinTables && $fromClause) { - foreach ($fromClause as $fi => $ftable) { - if (in_array($ftable, $joinTables)) { - unset($fromClause[$fi]); - } - } - } - - // Add the GROUP BY columns - $groupByClause = $groupBy; - - $having = $criteria->getHaving(); - $havingString = null; - if ($having !== null) { - $sb = ''; - $having->appendPsTo($sb, $params); - $havingString = $sb; - } - - if (!empty($orderBy)) { - - foreach ($orderBy as $orderByColumn) { - - // Add function expression as-is. - - if (strpos($orderByColumn, '(') !== false) { - $orderByClause[] = $orderByColumn; - continue; - } - - // Split orderByColumn (i.e. "table.column DESC") - - $dotPos = strrpos($orderByColumn, '.'); - - if ($dotPos !== false) { - $tableName = substr($orderByColumn, 0, $dotPos); - $columnName = substr($orderByColumn, $dotPos + 1); - } else { - $tableName = ''; - $columnName = $orderByColumn; - } - - $spacePos = strpos($columnName, ' '); - - if ($spacePos !== false) { - $direction = substr($columnName, $spacePos); - $columnName = substr($columnName, 0, $spacePos); - } else { - $direction = ''; - } - - $tableAlias = $tableName; - if ($aliasTableName = $criteria->getTableForAlias($tableName)) { - $tableName = $aliasTableName; - } - - $columnAlias = $columnName; - if ($asColumnName = $criteria->getColumnForAs($columnName)) { - $columnName = $asColumnName; - } - - $column = $tableName ? $dbMap->getTable($tableName)->getColumn($columnName) : null; - - if ($criteria->isIgnoreCase() && $column && $column->isText()) { - $ignoreCaseColumn = $db->ignoreCaseInOrderBy("$tableAlias.$columnAlias"); - $orderByClause[] = $ignoreCaseColumn . $direction; - $selectSql .= ', ' . $ignoreCaseColumn; - } else { - $orderByClause[] = $orderByColumn; - } - } - } - - if (empty($fromClause) && $criteria->getPrimaryTableName()) { - $fromClause[] = $criteria->getPrimaryTableName(); - } - - // from / join tables quoted if it is necessary - if ($db->useQuoteIdentifier()) { - $fromClause = array_map(array($db, 'quoteIdentifierTable'), $fromClause); - $joinClause = $joinClause ? $joinClause : array_map(array($db, 'quoteIdentifierTable'), $joinClause); - } - - // build from-clause - $from = ''; - if (!empty($joinClause) && count($fromClause) > 1) { - $from .= implode(" CROSS JOIN ", $fromClause); - } else { - $from .= implode(", ", $fromClause); - } - - $from .= $joinClause ? ' ' . implode(' ', $joinClause) : ''; - - // Build the SQL from the arrays we compiled - $sql = $selectSql - ." FROM " . $from - .($whereClause ? " WHERE ".implode(" AND ", $whereClause) : "") - .($groupByClause ? " GROUP BY ".implode(",", $groupByClause) : "") - .($havingString ? " HAVING ".$havingString : "") - .($orderByClause ? " ORDER BY ".implode(",", $orderByClause) : ""); - - // APPLY OFFSET & LIMIT to the query. - if ($criteria->getLimit() || $criteria->getOffset()) { - $db->applyLimit($sql, $criteria->getOffset(), $criteria->getLimit(), $criteria); - } - - return $sql; - } - - /** - * Builds the SELECT part of a SQL statement based on a Criteria - * taking into account select columns and 'as' columns (i.e. columns aliases) - */ - public static function createSelectSqlPart(Criteria $criteria, &$fromClause, $aliasAll = false) - { - $selectClause = array(); - - if ($aliasAll) { - self::turnSelectColumnsToAliases($criteria); - // no select columns after that, they are all aliases - } else { - foreach ($criteria->getSelectColumns() as $columnName) { - - // expect every column to be of "table.column" formation - // it could be a function: e.g. MAX(books.price) - - $tableName = null; - - $selectClause[] = $columnName; // the full column name: e.g. MAX(books.price) - - $parenPos = strrpos($columnName, '('); - $dotPos = strrpos($columnName, '.', ($parenPos !== false ? $parenPos : 0)); - - if ($dotPos !== false) { - if ($parenPos === false) { // table.column - $tableName = substr($columnName, 0, $dotPos); - } else { // FUNC(table.column) - // functions may contain qualifiers so only take the last - // word as the table name. - // COUNT(DISTINCT books.price) - $lastSpace = strpos($tableName, ' '); - if ($lastSpace !== false) { // COUNT(DISTINCT books.price) - $tableName = substr($tableName, $lastSpace + 1); - } else { - $tableName = substr($columnName, $parenPos + 1, $dotPos - ($parenPos + 1)); - } - } - // is it a table alias? - $tableName2 = $criteria->getTableForAlias($tableName); - if ($tableName2 !== null) { - $fromClause[] = $tableName2 . ' ' . $tableName; - } else { - $fromClause[] = $tableName; - } - } // if $dotPost !== false - } - } - - // set the aliases - foreach ($criteria->getAsColumns() as $alias => $col) { - $selectClause[] = $col . ' AS ' . $alias; - } - - $selectModifiers = $criteria->getSelectModifiers(); - $queryComment = $criteria->getComment(); - - // Build the SQL from the arrays we compiled - $sql = "SELECT " - . ($queryComment ? '/* ' . $queryComment . ' */ ' : '') - . ($selectModifiers ? (implode(' ', $selectModifiers) . ' ') : '') - . implode(", ", $selectClause); - - return $sql; - } - - /** - * Builds a params array, like the kind populated by Criterion::appendPsTo(). - * This is useful for building an array even when it is not using the appendPsTo() method. - * @param array $columns - * @param Criteria $values - * @return array params array('column' => ..., 'table' => ..., 'value' => ...) - */ - private static function buildParams($columns, Criteria $values) - { - $params = array(); - foreach ($columns as $key) { - if ($values->containsKey($key)) { - $crit = $values->getCriterion($key); - $params[] = array('column' => $crit->getColumn(), 'table' => $crit->getTable(), 'value' => $crit->getValue()); - } - } - return $params; - } - - /** - * This function searches for the given validator $name under propel/validator/$name.php, - * imports and caches it. - * - * @param string $classname The dot-path name of class (e.g. myapp.propel.MyValidator) - * @return Validator object or null if not able to instantiate validator class (and error will be logged in this case) - */ - public static function getValidator($classname) - { - try { - $v = isset(self::$validatorMap[$classname]) ? self::$validatorMap[$classname] : null; - if ($v === null) { - $cls = Propel::importClass($classname); - $v = new $cls(); - self::$validatorMap[$classname] = $v; - } - return $v; - } catch (Exception $e) { - Propel::log("BasePeer::getValidator(): failed trying to instantiate " . $classname . ": ".$e->getMessage(), Propel::LOG_ERR); - } - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/NodePeer.php b/airtime_mvc/library/propel/runtime/lib/util/NodePeer.php deleted file mode 100644 index d40b7642a..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/NodePeer.php +++ /dev/null @@ -1,369 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.runtime.util - */ -interface NodePeer -{ - /** - * Creates the supplied node as the root node. - * - * @param object $node Propel object for model - * @return object Inserted propel object for model - */ - public static function createRoot(NodeObject $node); - - /** - * Returns the root node for a given scope id - * - * @param int $scopeId Scope id to determine which root node to return - * @param PropelPDO $con Connection to use. - * @return object Propel object for root node - */ - public static function retrieveRoot($scopeId = 1, PropelPDO $con = null); - - /** - * Inserts $child as first child of destination node $parent - * - * @param object $child Propel object for child node - * @param object $parent Propel object for parent node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function insertAsFirstChildOf(NodeObject $child, NodeObject $parent, PropelPDO $con = null); - - /** - * Inserts $child as last child of destination node $parent - * - * @param object $child Propel object for child node - * @param object $parent Propel object for parent node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function insertAsLastChildOf(NodeObject $child, NodeObject $parent, PropelPDO $con = null); - - /** - * Inserts $sibling as previous sibling to destination node $node - * - * @param object $node Propel object for destination node - * @param object $sibling Propel object for source node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function insertAsPrevSiblingOf(NodeObject $node, NodeObject $sibling, PropelPDO $con = null); - - /** - * Inserts $sibling as next sibling to destination node $node - * - * @param object $node Propel object for destination node - * @param object $sibling Propel object for source node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function insertAsNextSiblingOf(NodeObject $node, NodeObject $sibling, PropelPDO $con = null); - - /** - * Inserts $parent as parent of given $node. - * - * @param object $parent Propel object for given parent node - * @param object $node Propel object for given destination node - * @param PropelPDO $con Connection to use. - * @return void - * @throws Exception When trying to insert node as parent of a root node - */ - public static function insertAsParentOf(NodeObject $parent, NodeObject $node, PropelPDO $con = null); - - /** - * Inserts $node as root node - * - * @param object $node Propel object as root node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function insertRoot(NodeObject $node, PropelPDO $con = null); - - /** - * Delete root node - * - * @param int $scopeId Scope id to determine which root node to delete - * @param PropelPDO $con Connection to use. - * @return boolean Deletion status - */ - public static function deleteRoot($scopeId = 1, PropelPDO $con = null); - - /** - * Delete $dest node - * - * @param object $dest Propel object node to delete - * @param PropelPDO $con Connection to use. - * @return boolean Deletion status - */ - public static function deleteNode(NodeObject $dest, PropelPDO $con = null); - - /** - * Moves $child to be first child of $parent - * - * @param object $parent Propel object for parent node - * @param object $child Propel object for child node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function moveToFirstChildOf(NodeObject $parent, NodeObject $child, PropelPDO $con = null); - - /** - * Moves $node to be last child of $dest - * - * @param object $dest Propel object for destination node - * @param object $node Propel object for source node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function moveToLastChildOf(NodeObject $dest, NodeObject $node, PropelPDO $con = null); - - /** - * Moves $node to be prev sibling to $dest - * - * @param object $dest Propel object for destination node - * @param object $node Propel object for source node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function moveToPrevSiblingOf(NodeObject $dest, NodeObject $node, PropelPDO $con = null); - - /** - * Moves $node to be next sibling to $dest - * - * @param object $dest Propel object for destination node - * @param object $node Propel object for source node - * @param PropelPDO $con Connection to use. - * @return void - */ - public static function moveToNextSiblingOf(NodeObject $dest, NodeObject $node, PropelPDO $con = null); - - /** - * Gets first child for the given node if it exists - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveFirstChild(NodeObject $node, PropelPDO $con = null); - - /** - * Gets last child for the given node if it exists - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveLastChild(NodeObject $node, PropelPDO $con = null); - - /** - * Gets prev sibling for the given node if it exists - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrievePrevSibling(NodeObject $node, PropelPDO $con = null); - - /** - * Gets next sibling for the given node if it exists - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveNextSibling(NodeObject $node, PropelPDO $con = null); - - /** - * Retrieves the entire tree from root - * - * @param int $scopeId Scope id to determine which scope tree to return - * @param PropelPDO $con Connection to use. - */ - public static function retrieveTree($scopeId = 1, PropelPDO $con = null); - - /** - * Retrieves the entire tree from parent $node - * - * @param PropelPDO $con Connection to use. - */ - public static function retrieveBranch(NodeObject $node, PropelPDO $con = null); - - /** - * Gets direct children for the node - * - * @param object $node Propel object for parent node - * @param PropelPDO $con Connection to use. - */ - public static function retrieveChildren(NodeObject $node, PropelPDO $con = null); - - /** - * Gets all descendants for the node - * - * @param object $node Propel object for parent node - * @param PropelPDO $con Connection to use. - */ - public static function retrieveDescendants(NodeObject $node, PropelPDO $con = null); - - /** - * Gets all siblings for the node - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - */ - public static function retrieveSiblings(NodeObject $node, PropelPDO $con = null); - - /** - * Gets ancestor for the given node if it exists - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return mixed Propel object if exists else false - */ - public static function retrieveParent(NodeObject $node, PropelPDO $con = null); - - /** - * Gets level for the given node - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return int Level for the given node - */ - public static function getLevel(NodeObject $node, PropelPDO $con = null); - - /** - * Gets number of direct children for given node - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return int Level for the given node - */ - public static function getNumberOfChildren(NodeObject $node, PropelPDO $con = null); - - /** - * Gets number of descendants for given node - * - * @param object $node Propel object for src node - * @param PropelPDO $con Connection to use. - * @return int Level for the given node - */ - public static function getNumberOfDescendants(NodeObject $node, PropelPDO $con = null); - - /** - * Returns path to a specific node as an array, useful to create breadcrumbs - * - * @param object $node Propel object of node to create path to - * @param PropelPDO $con Connection to use. - * @return array Array in order of heirarchy - */ - public static function getPath(NodeObject $node, PropelPDO $con = null); - - /** - * Tests if node is valid - * - * @param object $node Propel object for src node - * @return bool - */ - public static function isValid(NodeObject $node = null); - - /** - * Tests if node is a root - * - * @param object $node Propel object for src node - * @return bool - */ - public static function isRoot(NodeObject $node); - - /** - * Tests if node is a leaf - * - * @param object $node Propel object for src node - * @return bool - */ - public static function isLeaf(NodeObject $node); - - /** - * Tests if $child is a child of $parent - * - * @param object $child Propel object for node - * @param object $parent Propel object for node - * @return bool - */ - public static function isChildOf(NodeObject $child, NodeObject $parent); - - /** - * Tests if $node1 is equal to $node2 - * - * @param object $node1 Propel object for node - * @param object $node2 Propel object for node - * @return bool - */ - public static function isEqualTo(NodeObject $node1, NodeObject $node2); - - /** - * Tests if $node has an ancestor - * - * @param object $node Propel object for node - * @param PropelPDO $con Connection to use. - * @return bool - */ - public static function hasParent(NodeObject $node, PropelPDO $con = null); - - /** - * Tests if $node has prev sibling - * - * @param object $node Propel object for node - * @param PropelPDO $con Connection to use. - * @return bool - */ - public static function hasPrevSibling(NodeObject $node, PropelPDO $con = null); - - /** - * Tests if $node has next sibling - * - * @param object $node Propel object for node - * @param PropelPDO $con Connection to use. - * @return bool - */ - public static function hasNextSibling(NodeObject $node, PropelPDO $con = null); - - /** - * Tests if $node has children - * - * @param object $node Propel object for node - * @return bool - */ - public static function hasChildren(NodeObject $node); - - /** - * Deletes $node and all of its descendants - * - * @param object $node Propel object for source node - * @param PropelPDO $con Connection to use. - */ - public static function deleteDescendants(NodeObject $node, PropelPDO $con = null); - - /** - * Returns a node given its primary key or the node itself - * - * @param int/object $node Primary key/instance of required node - * @param PropelPDO $con Connection to use. - * @return object Propel object for model - */ - public static function getNode($node, PropelPDO $con = null); - -} // NodePeer diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelAutoloader.php b/airtime_mvc/library/propel/runtime/lib/util/PropelAutoloader.php deleted file mode 100644 index 1bba65cec..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelAutoloader.php +++ /dev/null @@ -1,113 +0,0 @@ - $classPath - */ - public function addClassPaths($classMap) - { - $this->classes = array_merge($this->classes, $classMap); - } - - /** - * Sets the path for a particular class. - * - * @param string $class A PHP class name - * @param string $path A path (absolute or relative to the include path) - */ - public function addClassPath($class, $path) - { - $this->classes[$class] = $path; - } - - /** - * Returns the path where a particular class can be found. - * - * @param string $class A PHP class name - * - * @return string|null A path (absolute or relative to the include path) - */ - public function getClassPath($class) - { - return isset($this->classes[$class]) ? $this->classes[$class] : null; - } - - /** - * Handles autoloading of classes that have been registered in this instance - * - * @param string $class A class name. - * - * @return boolean Returns true if the class has been loaded - */ - public function autoload($class) - { - if (isset($this->classes[$class])) { - require $this->classes[$class]; - return true; - } - return false; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelColumnTypes.php b/airtime_mvc/library/propel/runtime/lib/util/PropelColumnTypes.php deleted file mode 100644 index e23c6f350..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelColumnTypes.php +++ /dev/null @@ -1,88 +0,0 @@ - (Propel) - * @version $Revision: 1612 $ - * @package propel.runtime.util - */ -class PropelColumnTypes -{ - - const - CHAR = "CHAR", - VARCHAR = "VARCHAR", - LONGVARCHAR = "LONGVARCHAR", - CLOB = "CLOB", - CLOB_EMU = "CLOB_EMU", - NUMERIC = "NUMERIC", - DECIMAL = "DECIMAL", - TINYINT = "TINYINT", - SMALLINT = "SMALLINT", - INTEGER = "INTEGER", - BIGINT = "BIGINT", - REAL = "REAL", - FLOAT = "FLOAT", - DOUBLE = "DOUBLE", - BINARY = "BINARY", - VARBINARY = "VARBINARY", - LONGVARBINARY = "LONGVARBINARY", - BLOB = "BLOB", - DATE = "DATE", - TIME = "TIME", - TIMESTAMP = "TIMESTAMP", - BU_DATE = "BU_DATE", - BU_TIMESTAMP = "BU_TIMESTAMP", - BOOLEAN = "BOOLEAN", - BOOLEAN_EMU = "BOOLEAN_EMU"; - - private static $propelToPdoMap = array( - self::CHAR => PDO::PARAM_STR, - self::VARCHAR => PDO::PARAM_STR, - self::LONGVARCHAR => PDO::PARAM_STR, - self::CLOB => PDO::PARAM_LOB, - self::CLOB_EMU => PDO::PARAM_STR, - self::NUMERIC => PDO::PARAM_STR, - self::DECIMAL => PDO::PARAM_STR, - self::TINYINT => PDO::PARAM_INT, - self::SMALLINT => PDO::PARAM_INT, - self::INTEGER => PDO::PARAM_INT, - self::BIGINT => PDO::PARAM_STR, - self::REAL => PDO::PARAM_STR, - self::FLOAT => PDO::PARAM_STR, - self::DOUBLE => PDO::PARAM_STR, - self::BINARY => PDO::PARAM_STR, - self::VARBINARY => PDO::PARAM_STR, - self::LONGVARBINARY => PDO::PARAM_STR, - self::BLOB => PDO::PARAM_LOB, - self::DATE => PDO::PARAM_STR, - self::TIME => PDO::PARAM_STR, - self::TIMESTAMP => PDO::PARAM_STR, - self::BU_DATE => PDO::PARAM_STR, - self::BU_TIMESTAMP => PDO::PARAM_STR, - self::BOOLEAN => PDO::PARAM_BOOL, - self::BOOLEAN_EMU => PDO::PARAM_INT, - ); - - /** - * Resturns the PDO type (PDO::PARAM_* constant) value for the Propel type provided. - * @param string $propelType - * @return int - */ - public static function getPdoType($propelType) - { - return self::$propelToPdoMap[$propelType]; - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelConditionalProxy.php b/airtime_mvc/library/propel/runtime/lib/util/PropelConditionalProxy.php deleted file mode 100644 index e153760fe..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelConditionalProxy.php +++ /dev/null @@ -1,71 +0,0 @@ - - * $c->_if(true) // returns $c - * ->doStuff() // executed - * ->_else() // returns a PropelConditionalProxy instance - * ->doOtherStuff() // not executed - * ->_endif(); // returns $c - * $c->_if(false) // returns a PropelConditionalProxy instance - * ->doStuff() // not executed - * ->_else() // returns $c - * ->doOtherStuff() // executed - * ->_endif(); // returns $c - * @see Criteria - * - * @author Francois Zaninotto - * @version $Revision: 1612 $ - * @package propel.runtime.util - */ -class PropelConditionalProxy -{ - protected $mainObject; - - public function __construct($mainObject) - { - $this->mainObject = $mainObject; - } - - public function _if() - { - throw new PropelException('_if() statements cannot be nested'); - } - - public function _elseif($cond) - { - if($cond) { - return $this->mainObject; - } else { - return $this; - } - } - - public function _else() - { - return $this->mainObject; - } - - public function _endif() - { - return $this->mainObject; - } - - public function __call($name, $arguments) - { - return $this; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelDateTime.php b/airtime_mvc/library/propel/runtime/lib/util/PropelDateTime.php deleted file mode 100644 index cfa1276dd..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelDateTime.php +++ /dev/null @@ -1,76 +0,0 @@ -dateString = $this->format('Y-m-d H:i:s'); - $this->tzString = $this->getTimeZone()->getName(); - return array('dateString', 'tzString'); - } - - /** - * PHP "magic" function called when object is restored from serialized state. - * Calls DateTime constructor with previously stored string value of date. - */ - function __wakeup() - { - parent::__construct($this->dateString, new DateTimeZone($this->tzString)); - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelModelPager.php b/airtime_mvc/library/propel/runtime/lib/util/PropelModelPager.php deleted file mode 100644 index 5236ebbd5..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelModelPager.php +++ /dev/null @@ -1,349 +0,0 @@ - - * @author François Zaninotto - * @version $Revision: 1665 $ - * @package propel.runtime.query - */ -class PropelModelPager implements IteratorAggregate, Countable -{ - protected - $query = null, - $page = 1, - $maxPerPage = 10, - $lastPage = 1, - $nbResults = 0, - $objects = null, - $parameters = array(), - $currentMaxLink = 1, - $parameterHolder = null, - $maxRecordLimit = false, - $results = null, - $resultsCounter = 0; - - public function __construct(Criteria $query, $maxPerPage = 10) - { - $this->setQuery($query); - $this->setMaxPerPage($maxPerPage); - } - - public function setQuery(Criteria $query) - { - $this->query = $query; - } - - public function getQuery() - { - return $this->query; - } - - public function init() - { - $hasMaxRecordLimit = ($this->getMaxRecordLimit() !== false); - $maxRecordLimit = $this->getMaxRecordLimit(); - - $qForCount = clone $this->getQuery(); - $count = $qForCount - ->offset(0) - ->limit(0) - ->count(); - - $this->setNbResults($hasMaxRecordLimit ? min($count, $maxRecordLimit) : $count); - - $q = $this->getQuery() - ->offset(0) - ->limit(0); - - if (($this->getPage() == 0 || $this->getMaxPerPage() == 0)) { - $this->setLastPage(0); - } else { - $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage())); - - $offset = ($this->getPage() - 1) * $this->getMaxPerPage(); - $q->offset($offset); - - if ($hasMaxRecordLimit) { - $maxRecordLimit = $maxRecordLimit - $offset; - if ($maxRecordLimit > $this->getMaxPerPage()) { - $q->limit($this->getMaxPerPage()); - } else { - $q->limit($maxRecordLimit); - } - } else { - $q->limit($this->getMaxPerPage()); - } - } - } - - /** - * Get the collection of results in the page - * - * @return PropelObjectCollection A collection of results - */ - public function getResults() - { - if (null === $this->results) { - $this->results = $this->getQuery() - ->setFormatter(ModelCriteria::FORMAT_OBJECT) - ->find(); - } - return $this->results; - } - - public function getCurrentMaxLink() - { - return $this->currentMaxLink; - } - - public function getMaxRecordLimit() - { - return $this->maxRecordLimit; - } - - public function setMaxRecordLimit($limit) - { - $this->maxRecordLimit = $limit; - } - - public function getLinks($nb_links = 5) - { - $links = array(); - $tmp = $this->page - floor($nb_links / 2); - $check = $this->lastPage - $nb_links + 1; - $limit = ($check > 0) ? $check : 1; - $begin = ($tmp > 0) ? (($tmp > $limit) ? $limit : $tmp) : 1; - - $i = (int) $begin; - while (($i < $begin + $nb_links) && ($i <= $this->lastPage)) { - $links[] = $i++; - } - - $this->currentMaxLink = count($links) ? $links[count($links) - 1] : 1; - - return $links; - } - - /** - * Test whether the number of results exceeds the max number of results per page - * - * @return boolean true if the pager displays only a subset of the results - */ - public function haveToPaginate() - { - return (($this->getMaxPerPage() != 0) && ($this->getNbResults() > $this->getMaxPerPage())); - } - - /** - * Get the index of the first element in the page - * Returns 1 on the first page, $maxPerPage +1 on the second page, etc - * - * @return int - */ - public function getFirstIndex() - { - if ($this->page == 0) { - return 1; - } else { - return ($this->page - 1) * $this->maxPerPage + 1; - } - } - - /** - * Get the index of the last element in the page - * Always less than or eaqual to $maxPerPage - * - * @return int - */ - public function getLastIndex() - { - if ($this->page == 0) { - return $this->nbResults; - } else { - if (($this->page * $this->maxPerPage) >= $this->nbResults) { - return $this->nbResults; - } else { - return ($this->page * $this->maxPerPage); - } - } - } - - /** - * Get the total number of results of the query - * This can be greater than $maxPerPage - * - * @return int - */ - public function getNbResults() - { - return $this->nbResults; - } - - /** - * Set the total number of results of the query - * - * @param int $nb - */ - protected function setNbResults($nb) - { - $this->nbResults = $nb; - } - - /** - * Check whether the current page is the first page - * - * @return boolean true if the current page is the first page - */ - public function isFirstPage() - { - return $this->getPage() == $this->getFirstPage(); - } - - /** - * Get the number of the first page - * - * @return int Always 1 - */ - public function getFirstPage() - { - return 1; - } - - /** - * Check whether the current page is the last page - * - * @return boolean true if the current page is the last page - */ - public function isLastPage() - { - return $this->getPage() == $this->getLastPage(); - } - - /** - * Get the number of the last page - * - * @return int - */ - public function getLastPage() - { - return $this->lastPage; - } - - /** - * Set the number of the first page - * - * @param int $page - */ - protected function setLastPage($page) - { - $this->lastPage = $page; - if ($this->getPage() > $page) { - $this->setPage($page); - } - } - - /** - * Get the number of the current page - * - * @return int - */ - public function getPage() - { - return $this->page; - } - - /** - * Set the number of the current page - * - * @param int $page - */ - public function setPage($page) - { - $this->page = intval($page); - if ($this->page <= 0) { - // set first page, which depends on a maximum set - $this->page = $this->getMaxPerPage() ? 1 : 0; - } - } - - /** - * Get the number of the next page - * - * @return int - */ - public function getNextPage() - { - return min($this->getPage() + 1, $this->getLastPage()); - } - - /** - * Get the number of the previous page - * - * @return int - */ - public function getPreviousPage() - { - return max($this->getPage() - 1, $this->getFirstPage()); - } - - /** - * Get the maximum number results per page - * - * @return int - */ - public function getMaxPerPage() - { - return $this->maxPerPage; - } - - /** - * Set the maximum number results per page - * - * @param int $max - */ - public function setMaxPerPage($max) - { - if ($max > 0) { - $this->maxPerPage = $max; - if ($this->page == 0) { - $this->page = 1; - } - } else if ($max == 0) { - $this->maxPerPage = 0; - $this->page = 0; - } else { - $this->maxPerPage = 1; - if ($this->page == 0) { - $this->page = 1; - } - } - } - - public function getIterator() - { - return $this->getResults()->getIterator(); - } - - /** - * Returns the total number of results. - * - * @see Countable - * @return int - */ - public function count() - { - return $this->getNbResults(); - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/util/PropelPager.php b/airtime_mvc/library/propel/runtime/lib/util/PropelPager.php deleted file mode 100644 index 8fefdbc0a..000000000 --- a/airtime_mvc/library/propel/runtime/lib/util/PropelPager.php +++ /dev/null @@ -1,597 +0,0 @@ -addDescendingOrderByColumn(poemPeer::SID); - * - * // with join - * $pager = new PropelPager($c, 'poemPeer', 'doSelectJoinPoemUsers', 1, 50); - * - * // without Join - * - * $pager = new PropelPager($c, 'poemPeer', 'doSelect', 1, 50); - * - * Some template: - * - *

- * Total Pages: getTotalPages()?> Total Records: getTotalRecordCount()?> - *

- * - * - * - * - * - * - * - * - * - * - *
- * getFirstPage):?> - * | - * - * - * getPrev()):?> - * Previous| - * - * - * getPrevLinks() as $link):?> - * | - * - * getPage()?> - * getNextLinks() as $link):?> - * | - * - * - * getNext()):?> - * Last| - * - * - * getLastPage()):?> - * | - * - *
- * - * - * - * - * - * - * - * getResult() as $poem):?> - * - * - * - * - * - * - * - *
TitleAuteurDatecomments
getTitle()?>getPoemUsers()->getUname()?>getTime()?>getComments()?>
- * - * - * @author Rob Halff - * @author Niklas Närhinen - * @version $Revision: 1612 $ - * @copyright Copyright (c) 2004 Rob Halff: LGPL - See LICENCE - * @package propel.runtime.util - */ -class PropelPager implements Countable, Iterator -{ - - private $recordCount; - private $pages; - private $peerClass; - private $peerSelectMethod; - private $peerCountMethod; - private $criteria; - private $countCriteria; - private $page; - private $rs = null; - - //Iterator vars - private $currentKey = 0; - - /** @var int Start row (offset) */ - protected $start = 0; - - /** @var int Max rows to return (0 means all) */ - protected $max = 0; - - /** - * Create a new Propel Pager. - * @param Criteria $c - * @param string $peerClass The name of the static Peer class. - * @param string $peerSelectMethod The name of the static method for selecting content from the Peer class. - * @param int $page The current page (1-based). - * @param int $rowsPerPage The number of rows that should be displayed per page. - */ - public function __construct($c = null, $peerClass = null, $peerSelectMethod = null, $page = 1, $rowsPerPage = 25) - { - if (!isset($c)) { - $c = new Criteria(); - } - $this->setCriteria($c); - $this->setPeerClass($peerClass); - $this->setPeerSelectMethod($peerSelectMethod); - $this->guessPeerCountMethod(); - $this->setPage($page); - $this->setRowsPerPage($rowsPerPage); - } - - /** - * Set the criteria for this pager. - * @param Criteria $c - * @return void - */ - public function setCriteria(Criteria $c) - { - $this->criteria = $c; - } - - /** - * Return the Criteria object for this pager. - * @return Criteria - */ - public function getCriteria() - { - return $this->criteria; - } - - /** - * Set the Peer Classname - * - * @param string $class - * @return void - */ - public function setPeerClass($class) - { - $this->peerClass = $class; - } - - /** - * Return the Peer Classname. - * @return string - */ - public function getPeerClass() - { - return $this->peerClass; - } - - /** - * Set the Peer select method. - * This exists for legacy support, please use setPeerSelectMethod(). - * @param string $method The name of the static method to call on the Peer class. - * @return void - * @see setPeerSelectMethod() - * @deprecated - */ - public function setPeerMethod($method) - { - $this->setPeerSelectMethod($method); - } - - /** - * Return the Peer select method. - * This exists for legacy support, please use getPeerSelectMethod(). - * @return string - * @see getPeerSelectMethod() - * @deprecated - */ - public function getPeerMethod() - { - return $this->getPeerSelectMethod(); - } - - /** - * Set the Peer select method. - * - * @param string $method The name of the static method to call on the Peer class. - * @return void - */ - public function setPeerSelectMethod($method) - { - $this->peerSelectMethod = $method; - } - - /** - * Return the Peer select method. - * @return string - */ - public function getPeerSelectMethod() - { - return $this->peerSelectMethod; - } - - /** - * Sets the Count method. - * This is set based on the Peer method, for example if Peer method is doSelectJoin*() then the - * count method will be doCountJoin*(). - * @param string $method The name of the static method to call on the Peer class. - */ - public function setPeerCountMethod($method) - { - $this->peerCountMethod = $method; - } - - /** - * Return the Peer count method. - */ - public function getPeerCountMethod() - { - return $this->peerCountMethod; - } - - /** - * Guesses the Peer count method based on the select method. - */ - private function guessPeerCountMethod() - { - $selectMethod = $this->getPeerSelectMethod(); - if ($selectMethod == 'doSelect') { - $countMethod = 'doCount'; - } elseif ( ($pos = stripos($selectMethod, 'doSelectJoin')) === 0) { - $countMethod = 'doCount' . substr($selectMethod, strlen('doSelect')); - } else { - // we will fall back to doCount() if we don't understand the join - // method; however, it probably won't be accurate. Maybe triggering an error would - // be appropriate ... - $countMethod = 'doCount'; - } - $this->setPeerCountMethod($countMethod); - } - - /** - * Get the paged resultset - * - * @return mixed $rs - */ - public function getResult() - { - if (!isset($this->rs)) { - $this->doRs(); - } - - return $this->rs; - } - - /** - * Get the paged resultset - * - * Main method which creates a paged result set based on the criteria - * and the requested peer select method. - * - */ - private function doRs() - { - $this->criteria->setOffset($this->start); - $this->criteria->setLimit($this->max); - $this->rs = call_user_func(array($this->getPeerClass(), $this->getPeerSelectMethod()), $this->criteria); - } - - /** - * Get the first page - * - * For now I can only think of returning 1 always. - * It should probably return 0 if there are no pages - * - * @return int 1 - */ - public function getFirstPage() - { - return '1'; - } - - /** - * Convenience method to indicate whether current page is the first page. - * - * @return boolean - */ - public function atFirstPage() - { - return $this->getPage() == $this->getFirstPage(); - } - - /** - * Get last page - * - * @return int $lastPage - */ - public function getLastPage() - { - $totalPages = $this->getTotalPages(); - if ($totalPages == 0) { - return 1; - } else { - return $totalPages; - } - } - - /** - * Convenience method to indicate whether current page is the last page. - * - * @return boolean - */ - public function atLastPage() - { - return $this->getPage() == $this->getLastPage(); - } - - /** - * get total pages - * - * @return int $this->pages - */ - public function getTotalPages() { - if (!isset($this->pages)) { - $recordCount = $this->getTotalRecordCount(); - if ($this->max > 0) { - $this->pages = ceil($recordCount/$this->max); - } else { - $this->pages = 0; - } - } - return $this->pages; - } - - /** - * get an array of previous id's - * - * @param int $range - * @return array $links - */ - public function getPrevLinks($range = 5) - { - $total = $this->getTotalPages(); - $start = $this->getPage() - 1; - $end = $this->getPage() - $range; - $first = $this->getFirstPage(); - $links = array(); - for ($i=$start; $i>$end; $i--) { - if ($i < $first) { - break; - } - $links[] = $i; - } - - return array_reverse($links); - } - - /** - * get an array of next id's - * - * @param int $range - * @return array $links - */ - public function getNextLinks($range = 5) - { - $total = $this->getTotalPages(); - $start = $this->getPage() + 1; - $end = $this->getPage() + $range; - $last = $this->getLastPage(); - $links = array(); - for ($i=$start; $i<$end; $i++) { - if ($i > $last) { - break; - } - $links[] = $i; - } - - return $links; - } - - /** - * Returns whether last page is complete - * - * @return bool Last page complete or not - */ - public function isLastPageComplete() - { - return !($this->getTotalRecordCount() % $this->max); - } - - /** - * get previous id - * - * @return mixed $prev - */ - public function getPrev() { - if ($this->getPage() != $this->getFirstPage()) { - $prev = $this->getPage() - 1; - } else { - $prev = false; - } - return $prev; - } - - /** - * get next id - * - * @return mixed $next - */ - public function getNext() { - if ($this->getPage() != $this->getLastPage()) { - $next = $this->getPage() + 1; - } else { - $next = false; - } - return $next; - } - - /** - * Set the current page number (First page is 1). - * @param int $page - * @return void - */ - public function setPage($page) - { - $this->page = $page; - // (re-)calculate start rec - $this->calculateStart(); - } - - /** - * Get current page. - * @return int - */ - public function getPage() - { - return $this->page; - } - - /** - * Set the number of rows per page. - * @param int $r - */ - public function setRowsPerPage($r) - { - $this->max = $r; - // (re-)calculate start rec - $this->calculateStart(); - } - - /** - * Get number of rows per page. - * @return int - */ - public function getRowsPerPage() - { - return $this->max; - } - - /** - * Calculate startrow / max rows based on current page and rows-per-page. - * @return void - */ - private function calculateStart() - { - $this->start = ( ($this->page - 1) * $this->max ); - } - - /** - * Gets the total number of (un-LIMITed) records. - * - * This method will perform a query that executes un-LIMITed query. - * - * @return int Total number of records - disregarding page, maxrows, etc. - */ - public function getTotalRecordCount() - { - - if (!isset($this->rs)) { - $this->doRs(); - } - - if (empty($this->recordCount)) { - $this->countCriteria = clone $this->criteria; - $this->countCriteria->setLimit(0); - $this->countCriteria->setOffset(0); - - $this->recordCount = call_user_func( - array( - $this->getPeerClass(), - $this->getPeerCountMethod() - ), - $this->countCriteria - ); - - } - - return $this->recordCount; - - } - - /** - * Sets the start row or offset. - * @param int $v - */ - public function setStart($v) - { - $this->start = $v; - } - - /** - * Sets max rows (limit). - * @param int $v - * @return void - */ - public function setMax($v) - { - $this->max = $v; - } - - /** - * Returns the count of the current page's records - * @return int - */ - public function count() - { - return count($this->getResult()); - } - - /** - * Returns the current element of the iterator - * @return mixed - */ - public function current() - { - if (!isset($this->rs)) { - $this->doRs(); - } - return $this->rs[$this->currentKey]; - } - - /** - * Returns the current key of the iterator - * @return int - */ - public function key() - { - return $this->currentKey; - } - - /** - * Advances the iterator to the next element - * @return void - */ - public function next() - { - $this->currentKey++; - } - - /** - * Resets the iterator to the first element - * @return void - */ - public function rewind() - { - $this->currentKey = 0; - } - - /** - * Checks if the current key exists in the container - * @return boolean - */ - public function valid() - { - if (!isset($this->rs)) { - $this->doRs(); - } - return in_array($this->currentKey, array_keys($this->rs)); - } - -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/BasicValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/BasicValidator.php deleted file mode 100644 index 5733e0bf8..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/BasicValidator.php +++ /dev/null @@ -1,35 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -interface BasicValidator -{ - - /** - * Determine whether a value meets the criteria specified - * - * @param ValidatorMap $map A column map object for the column to be validated. - * @param string $str a String to be tested - * - * @return mixed TRUE if valid, error message otherwise - */ - public function isValid(ValidatorMap $map, $str); - -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/MatchValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/MatchValidator.php deleted file mode 100644 index a2890e9b5..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/MatchValidator.php +++ /dev/null @@ -1,68 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @author Hans Lellelid - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class MatchValidator implements BasicValidator -{ - /** - * Prepares the regular expression entered in the XML - * for use with preg_match(). - * @param string $exp - * @return string Prepared regular expession. - */ - private function prepareRegexp($exp) - { - // remove surrounding '/' marks so that they don't get escaped in next step - if ($exp{0} !== '/' || $exp{strlen($exp)-1} !== '/' ) { - $exp = '/' . $exp . '/'; - } - - // if they did not escape / chars; we do that for them - $exp = preg_replace('/([^\\\])\/([^$])/', '$1\/$2', $exp); - - return $exp; - } - - /** - * Whether the passed string matches regular expression. - */ - public function isValid (ValidatorMap $map, $str) - { - return (preg_match($this->prepareRegexp($map->getValue()), $str) != 0); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/MaxLengthValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/MaxLengthValidator.php deleted file mode 100644 index 286c82c7e..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/MaxLengthValidator.php +++ /dev/null @@ -1,39 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class MaxLengthValidator implements BasicValidator -{ - - public function isValid (ValidatorMap $map, $str) - { - return strlen($str) <= intval($map->getValue()); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/MaxValueValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/MaxValueValidator.php deleted file mode 100644 index b71294043..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/MaxValueValidator.php +++ /dev/null @@ -1,43 +0,0 @@ - - * - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class MaxValueValidator implements BasicValidator -{ - - /** - * @see BasicValidator::isValid() - */ - public function isValid (ValidatorMap $map, $value) - { - if (is_null($value) == false && is_numeric($value) == true) { - return intval($value) <= intval($map->getValue()); - } - - return false; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/MinLengthValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/MinLengthValidator.php deleted file mode 100644 index e5c034596..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/MinLengthValidator.php +++ /dev/null @@ -1,36 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class MinLengthValidator implements BasicValidator -{ - - /** - * @see BasicValidator::isValid() - */ - public function isValid (ValidatorMap $map, $str) - { - return strlen($str) >= intval($map->getValue()); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/MinValueValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/MinValueValidator.php deleted file mode 100644 index d58894663..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/MinValueValidator.php +++ /dev/null @@ -1,43 +0,0 @@ - - * - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class MinValueValidator implements BasicValidator -{ - - /** - * @see BasicValidator::isValid() - */ - public function isValid (ValidatorMap $map, $value) - { - if (is_null($value) == false && is_numeric($value)) { - return intval($value) >= intval($map->getValue()); - } - - return false; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/NotMatchValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/NotMatchValidator.php deleted file mode 100644 index f0f72998d..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/NotMatchValidator.php +++ /dev/null @@ -1,66 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @author Hans Lellelid - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class NotMatchValidator implements BasicValidator -{ - /** - * Prepares the regular expression entered in the XML - * for use with preg_match(). - * @param string $exp - * @return string Prepared regular expession. - */ - private function prepareRegexp($exp) - { - // remove surrounding '/' marks so that they don't get escaped in next step - if ($exp{0} !== '/' || $exp{strlen($exp)-1} !== '/' ) { - $exp = '/' . $exp . '/'; - } - - // if they did not escape / chars; we do that for them - $exp = preg_replace('/([^\\\])\/([^$])/', '$1\/$2', $exp); - - return $exp; - } - - /** - * Whether the passed string matches regular expression. - */ - public function isValid (ValidatorMap $map, $str) - { - return (preg_match($this->prepareRegexp($map->getValue()), $str) == 0); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/RequiredValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/RequiredValidator.php deleted file mode 100644 index 57ab63a6f..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/RequiredValidator.php +++ /dev/null @@ -1,38 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class RequiredValidator implements BasicValidator -{ - - /** - * @see BasicValidator::isValid() - */ - public function isValid (ValidatorMap $map, $str) - { - return ($str !== null && $str !== ""); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/TypeValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/TypeValidator.php deleted file mode 100644 index 141760f0a..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/TypeValidator.php +++ /dev/null @@ -1,68 +0,0 @@ - - * - * - * - * - * - * - * - * @author Hans Lellelid - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class TypeValidator implements BasicValidator -{ - public function isValid(ValidatorMap $map, $value) - { - switch ($map->getValue()) { - case 'array': - return is_array($value); - break; - case 'bool': - case 'boolean': - return is_bool($value); - break; - case 'float': - return is_float($value); - break; - case 'int': - case 'integer': - return is_int($value); - break; - case 'numeric': - return is_numeric($value); - break; - case 'object': - return is_object($value); - break; - case 'resource': - return is_resource($value); - break; - case 'scalar': - return is_scalar($value); - break; - case 'string': - return is_string($value); - break; - case 'function': - return function_exists($value); - break; - default: - throw new PropelException('Unkonwn type ' . $map->getValue()); - break; - } - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/UniqueValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/UniqueValidator.php deleted file mode 100644 index 49cc91d34..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/UniqueValidator.php +++ /dev/null @@ -1,48 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class UniqueValidator implements BasicValidator -{ - - /** - * @see BasicValidator::isValid() - */ - public function isValid (ValidatorMap $map, $str) - { - $column = $map->getColumn(); - - $c = new Criteria(); - $c->add($column->getFullyQualifiedName(), $str, Criteria::EQUAL); - - $table = $column->getTable()->getClassName(); - - $clazz = $table . 'Peer'; - $count = call_user_func(array($clazz, 'doCount'), $c); - - $isValid = ($count === 0); - - return $isValid; - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/ValidValuesValidator.php b/airtime_mvc/library/propel/runtime/lib/validator/ValidValuesValidator.php deleted file mode 100644 index d680108e9..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/ValidValuesValidator.php +++ /dev/null @@ -1,33 +0,0 @@ - - * - * - * - * - * - * - * - * @author Michael Aichler - * @version $Revision: 1612 $ - * @package propel.runtime.validator - */ -class ValidValuesValidator implements BasicValidator -{ - - public function isValid (ValidatorMap $map, $str) - { - return in_array($str, preg_split("/[|,]/", $map->getValue())); - } -} diff --git a/airtime_mvc/library/propel/runtime/lib/validator/ValidationFailed.php b/airtime_mvc/library/propel/runtime/lib/validator/ValidationFailed.php deleted file mode 100644 index ed3472074..000000000 --- a/airtime_mvc/library/propel/runtime/lib/validator/ValidationFailed.php +++ /dev/null @@ -1,115 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.runtime.validator - * @see BasePeer::doValidate() - */ -class ValidationFailed { - - /** Column name in tablename.COLUMN_NAME format */ - private $colname; - - /** Message to display to user. */ - private $message; - - /** Validator object that caused this to fail. */ - private $validator; - - /** - * Construct a new ValidationFailed object. - * @param string $colname Column name. - * @param string $message Message to display to user. - * @param object $validator The Validator that caused this column to fail. - */ - public function __construct($colname, $message, $validator = null) - { - $this->colname = $colname; - $this->message = $message; - $this->validator = $validator; - } - - /** - * Set the column name. - * @param string $v - */ - public function setColumn($v) - { - $this->colname = $v; - } - - /** - * Gets the column name. - * @return string Qualified column name (tablename.COLUMN_NAME) - */ - public function getColumn() - { - return $this->colname; - } - - /** - * Set the message for the validation failure. - * @param string $v - */ - public function setMessage($v) - { - $this->message = $v; - } - - /** - * Gets the message for the validation failure. - * @return string - */ - public function getMessage() - { - return $this->message; - } - - /** - * Set the validator object that caused this to fail. - * @param object $v - */ - public function setValidator($v) - { - $this->validator = $v; - } - - /** - * Gets the validator object that caused this to fail. - * @return object - */ - public function getValidator() - { - return $this->validator; - } - - /** - * "magic" method to get string represenation of object. - * Maybe someday PHP5 will support the invoking this method automatically - * on (string) cast. Until then it's pretty useless. - * @return string - */ - public function __toString() - { - return $this->getMessage(); - } - -} diff --git a/airtime_mvc/library/propel/runtime/pear/BuildPropelPEARPackageTask.php b/airtime_mvc/library/propel/runtime/pear/BuildPropelPEARPackageTask.php deleted file mode 100644 index 023820fc4..000000000 --- a/airtime_mvc/library/propel/runtime/pear/BuildPropelPEARPackageTask.php +++ /dev/null @@ -1,205 +0,0 @@ - - * @package phing.tasks.ext - * @version $Revision: 1681 $ - */ -class BuildPropelPEARPackageTask extends MatchingTask -{ - - /** Base directory for reading files. */ - private $dir; - - private $version; - private $state = 'stable'; - private $notes; - - private $filesets = array(); - - /** Package file */ - private $packageFile; - - public function init() - { - include_once 'PEAR/PackageFileManager2.php'; - if (!class_exists('PEAR_PackageFileManager2')) { - throw new BuildException("You must have installed PEAR_PackageFileManager2 (PEAR_PackageFileManager >= 1.6.0) in order to create a PEAR package.xml file."); - } - } - - private function setOptions($pkg) - { - $options['baseinstalldir'] = 'propel'; - $options['packagedirectory'] = $this->dir->getAbsolutePath(); - - if (empty($this->filesets)) { - throw new BuildException("You must use a tag to specify the files to include in the package.xml"); - } - - $options['filelistgenerator'] = 'Fileset'; - - // Some PHING-specific options needed by our Fileset reader - $options['phing_project'] = $this->getProject(); - $options['phing_filesets'] = $this->filesets; - - if ($this->packageFile !== null) { - // create one w/ full path - $f = new PhingFile($this->packageFile->getAbsolutePath()); - $options['packagefile'] = $f->getName(); - // must end in trailing slash - $options['outputdirectory'] = $f->getParent() . DIRECTORY_SEPARATOR; - $this->log("Creating package file: " . $f->getPath(), Project::MSG_INFO); - } else { - $this->log("Creating [default] package.xml file in base directory.", Project::MSG_INFO); - } - - $pkg->setOptions($options); - - } - - /** - * Main entry point. - * @return void - */ - public function main() - { - if ($this->dir === null) { - throw new BuildException("You must specify the \"dir\" attribute for PEAR package task."); - } - - if ($this->version === null) { - throw new BuildException("You must specify the \"version\" attribute for PEAR package task."); - } - - $package = new PEAR_PackageFileManager2(); - - $this->setOptions($package); - - // the hard-coded stuff - $package->setPackage('propel_runtime'); - $package->setSummary('Runtime component of the Propel PHP object persistence layer'); - $package->setDescription('Propel is an object persistence layer for PHP5 based on Apache Torque. This package provides the runtime engine that transparently handles object persistence and retrieval.'); - $package->setChannel('pear.propelorm.org'); - $package->setPackageType('php'); - - $package->setReleaseVersion($this->version); - $package->setAPIVersion($this->version); - - $package->setReleaseStability($this->state); - $package->setAPIStability($this->state); - - $package->setNotes($this->notes); - - $package->setLicense('MIT', 'http://www.opensource.org/licenses/mit-license.php'); - - // Add package maintainers - $package->addMaintainer('lead', 'hans', 'Hans Lellelid', 'hans@xmpl.org'); - $package->addMaintainer('lead', 'david', 'David Zuelke', 'dz@bitxtender.com'); - $package->addMaintainer('lead', 'francois', 'Francois Zaninotto', 'fzaninotto@[gmail].com'); - - // "core" dependencies - $package->setPhpDep('5.2.0'); - $package->setPearinstallerDep('1.4.0'); - - // "package" dependencies - $package->addExtensionDep('required', 'pdo'); - $package->addExtensionDep('required', 'spl'); - - // now we run this weird generateContents() method that apparently - // is necessary before we can add replacements ... ? - $package->generateContents(); - - $e = $package->writePackageFile(); - - if (PEAR::isError($e)) { - throw new BuildException("Unable to write package file.", new Exception($e->getMessage())); - } - - } - - /** - * Used by the PEAR_PackageFileManager_PhingFileSet lister. - * @return array FileSet[] - */ - public function getFileSets() - { - return $this->filesets; - } - - // ------------------------------- - // Set properties from XML - // ------------------------------- - - /** - * Nested creator, creates a FileSet for this task - * - * @return FileSet The created fileset object - */ - function createFileSet() - { - $num = array_push($this->filesets, new FileSet()); - return $this->filesets[$num-1]; - } - - /** - * Set the version we are building. - * @param string $v - * @return void - */ - public function setVersion($v) - { - $this->version = $v; - } - - /** - * Set the state we are building. - * @param string $v - * @return void - */ - public function setState($v) - { - $this->state = $v; - } - - /** - * Sets release notes field. - * @param string $v - * @return void - */ - public function setNotes($v) - { - $this->notes = $v; - } - /** - * Sets "dir" property from XML. - * @param PhingFile $f - * @return void - */ - public function setDir(PhingFile $f) - { - $this->dir = $f; - } - - /** - * Sets the file to use for generated package.xml - */ - public function setDestFile(PhingFile $f) - { - $this->packageFile = $f; - } - -} diff --git a/airtime_mvc/library/propel/runtime/pear/build-pear-package.xml b/airtime_mvc/library/propel/runtime/pear/build-pear-package.xml deleted file mode 100644 index 31a741530..000000000 --- a/airtime_mvc/library/propel/runtime/pear/build-pear-package.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Propel version for package - - - - - - - - - ----------------------------- - | Creating directory layout | - ----------------------------- - - - - - - - - - - - - - - ----------------------------- - | Creating PEAR package.xml | - ----------------------------- - - - - - - - - - - - - - - - ----------------------------- - | Creating tar.gz package | - ----------------------------- - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/README b/airtime_mvc/library/propel/test/README deleted file mode 100644 index eb0e1934b..000000000 --- a/airtime_mvc/library/propel/test/README +++ /dev/null @@ -1,139 +0,0 @@ -= Running The Propel Unit Tests = - -== Background == - -Propel uses [http://www.phpunit.de PHPUnit 3.9] to test the build and runtime frameworks. - -You can find the unit test classes and support files in the [browser:branches/1.4/test/testsuite] directory. - -== Install PHPUnit == - -In order to run the tests, you must install PHPUnit, PEAR:Log, and Phing: -{{{ -> pear channel-discover pear.phpunit.de -> pear install phpunit/PHPUnit-3.3.9 -}}} - -{{{ -> pear channel-discover pear.phing.info -> pear install phing/phing-2.3.3 -}}} - -{{{ -> pear install log -}}} - -Tip: The latest release of PHPUnit (3.4) is not totally BC with the 3.3, and doesn't have a Phing adapter yet. That's why the Propel unit tests still use PHPUnit version 3.3. - -== Configure the Database to be Used in the Tests == - -You must configure both the generator and the runtime connection settings. -{{{ -// in test/fixtures/bookstore/build.properties -propel.database = mysql -propel.database.url = mysql:dbname=test -propel.mysqlTableType = InnoDB -propel.disableIdentifierQuoting=true -# For MySQL or Oracle, you also need to specify username & password -propel.database.user = myusername -propel.database.password = p@ssw0rd -}}} - -{{{ -// in test/fixtures/bookstore/runtime-conf.xml - - - mysql - - - DebugPDO - mysql:dbname=test - myusername - p@ssw0rd - - - - - - - - - - utf8 - - - -}}} - -== Build the Propel Model and Initialize the Database == - -{{{ -> cd /path/to/propel/test -> ../generator/bin/propel-gen fixtures/bookstore main -> mysqladmin create test -> ../generator/bin/propel-gen fixtures/bookstore insert-sql -}}} - -**Tip**: To run the unit tests for the namespace support in PHP 5.3, you must also build the `fixtures/namespaced` project. - -== Run the Unit Tests == - -Run all the unit tests at once using Phing: -{{{ -> cd /path/to/propel/test -> phing -f test.xml -verbose -}}} - -'''Tip''': The `-verbose` option will force the display of PHP notices, which are hidden by default. - -To run a single test, specify the classname (minus 'Test' ending) on the commandline, using the `test` property. For example to run only GeneratedObjectTest: - -{{{ -> phing -f test.xml -verbose -Dtest=GeneratedObject -}}} - -Tip: If you want to set up custom Phing properties for your unit tests, create a `test.properties` file inside the main `test/` directory. Phing will automatically try to load it if it exists. - -== How the Tests Work == - -Every method in the test classes that begins with 'test' is run as a test case by PHPUnit. All tests are run in isolation; the `setUp()` method is called at the beginning of ''each'' test and the `tearDown()` method is called at the end. - -The [browser:branches/1.4/test/tools/helpers/bookstore/BookstoreTestBase.php BookstoreTestBase] class specifies `setUp()` and `tearDown()` methods which populate and depopulate, respectively, the database. This means that every unit test is run with a cleanly populated database. To see the sample data that is populated, take a look at the [browser:branches/1.4/test/tools/helpers/bookstore/BookstoreDataPopulator.php BookstoreDataPopulator] class. You can also add data to this class, if needed by your tests; however, proceed cautiously when changing existing data in there as there may be unit tests that depend on it. More typically, you can simply create the data you need from within your test method. It will be deleted by the `tearDown()` method, so no need to clean up after yourself. - -== Writing Tests == - -If you've made a change to a template or to Propel behavior, the right thing to do is write a unit test that ensures that it works properly -- and continues to work in the future. - -Writing a unit test often means adding a method to one of the existing test classes. For example, let's test a feature in the Propel templates that supports saving of objects when only default values have been specified. Just add a `testSaveWithDefaultValues()` method to the [browser:branches/1.4/test/testsuite/generator/engine/builder/om/php5/GeneratedObjectTest.php GeneratedObjectTest] class, as follows: - -{{{ -#!php -setName('Penguin'); - // in the past this wouldn't have marked object as modified - // since 'Penguin' is the value that's already set for that attrib - $pub->save(); - - // if getId() returns the new ID, then we know save() worked. - $this->assertTrue($pub->getId() !== null, "Expect Publisher->save() to work with only default values."); -} -?> -}}} - -Run the test again using the command line to check that it passes: - -{{{ -> phing -f test.xml -Dtest=GeneratedObject -}}} - -You can also write additional unit test classes to any of the directories in `test/testsuite/` (or add new directories if needed). The Phing task will find these files automatically and run them. \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/bookstore-packaged-test.php b/airtime_mvc/library/propel/test/bookstore-packaged-test.php deleted file mode 100644 index 7455e9011..000000000 --- a/airtime_mvc/library/propel/test/bookstore-packaged-test.php +++ /dev/null @@ -1,811 +0,0 @@ - - * @version $Revision: 1612 $ - */ - -// Setup configuration. It is expected that the bookstore-conf.php file exists in ../build/conf -// - -error_reporting(E_ALL); - -$conf_path = realpath(dirname(__FILE__) . '/../projects/bookstore-packaged/build/conf/bookstore-packaged-conf.php'); -if (!file_exists($conf_path)) { - print "Make sure that you specify properties in conf/bookstore-packaged.properties and " - ."build propel before running this script."; - exit; -} - -// Add PHP_CLASSPATH, if set -if (getenv("PHP_CLASSPATH")) { - set_include_path(getenv("PHP_CLASSPATH") . PATH_SEPARATOR . get_include_path()); -} - - // Add build/classes/ and classes/ to path -set_include_path( - realpath(dirname(__FILE__) . '/../projects/bookstore-packaged/build/classes') . PATH_SEPARATOR . - dirname(__FILE__) . '/../../runtime/classes' . PATH_SEPARATOR . - get_include_path() -); - - - // Require classes. - require_once 'propel/Propel.php'; - require_once 'author/Author.php'; - require_once 'publisher/Publisher.php'; - require_once 'book/Book.php'; - require_once 'review/Review.php'; - include_once 'media/Media.php'; - include_once 'log/BookstoreLog.php'; - include_once 'book_club_list/BookClubList.php'; - include_once 'book_club_list/BookListRel.php'; - - include_once 'Benchmark/Timer.php'; - - $timer = new Benchmark_Timer; - - $timer->start(); - - // Some utility functions - function boolTest($cond) { - if ($cond) { - return "[OK]\n"; - } else { - return "[FAILED]\n"; - } - } - - try { - // Initialize Propel - Propel::init($conf_path); - } catch (Exception $e) { - die("Error initializing propel: ". $e->__toString()); - } - -function check_tables_empty() { - try { - - print "\nChecking to see that tables are empty\n"; - print "-------------------------------------\n\n"; - - print "Ensuring that there are no records in [author] table: "; - $res = AuthorPeer::doSelect(new Criteria()); - print boolTest(empty($res)); - - print "Ensuring that there are no records in [publisher] table: "; - $res2 = PublisherPeer::doSelect(new Criteria()); - print boolTest(empty($res2)); - - print "Ensuring that there are no records in [book] table: "; - $res3 = AuthorPeer::doSelect(new Criteria()); - print boolTest(empty($res3)); - - print "Ensuring that there are no records in [review] table: "; - $res4 = ReviewPeer::doSelect(new Criteria()); - print boolTest(empty($res4)); - - print "Ensuring that there are no records in [media] table: "; - $res5 = MediaPeer::doSelect(new Criteria()); - print boolTest(empty($res5)); - - print "Ensuring that there are no records in [book_club_list] table: "; - $res6 = BookClubListPeer::doSelect(new Criteria()); - print boolTest(empty($res6)); - - print "Ensuring that there are no records in [book_x_list] table: "; - $res7 = BookListRelPeer::doSelect(new Criteria()); - print boolTest(empty($res7)); - - return (empty($res) && empty($res2) && empty($res3) && empty($res4) && empty($res5)); - - } catch (Exception $e) { - die("Error ensuring tables were empty: " . $e->__toString()); - } -} - -// Check to see if records already exist in any of the three tables. If so, display an error -// and exit. - -if (!check_tables_empty()) { - die("Tables must be empty to perform these tests."); -} - -// Add publisher records -// --------------------- - -try { - print "\nAdding some new publishers to the list\n"; - print "--------------------------------------\n\n"; - - $scholastic = new Publisher(); - $scholastic->setName("Scholastic"); - // do not save, will do later to test cascade - print "Added publisher \"Scholastic\" [not saved yet].\n"; - - $morrow = new Publisher(); - $morrow->setName("William Morrow"); - $morrow->save(); - $morrow_id = $morrow->getId(); - print "Added publisher \"William Morrow\" [id = $morrow_id].\n"; - - $penguin = new Publisher(); - $penguin->setName("Penguin"); - $penguin->save(); - $penguin_id = $penguin->getId(); - print "Added publisher \"Penguin\" [id = $penguin_id].\n"; - - $vintage = new Publisher(); - $vintage->setName("Vintage"); - $vintage->save(); - $vintage_id = $vintage->getId(); - print "Added publisher \"Vintage\" [id = $vintage_id].\n"; - -} catch (Exception $e) { - die("Error adding publisher: " . $e->__toString()); -} - -// Add author records -// ------------------ - -try { - print "\nAdding some new authors to the list\n"; - print "--------------------------------------\n\n"; - - $rowling = new Author(); - $rowling->setFirstName("J.K."); - $rowling->setLastName("Rowling"); - // no save() - print "Added author \"J.K. Rowling\" [not saved yet].\n"; - - $stephenson = new Author(); - $stephenson->setFirstName("Neal"); - $stephenson->setLastName("Stephenson"); - $stephenson->save(); - $stephenson_id = $stephenson->getId(); - print "Added author \"Neal Stephenson\" [id = $stephenson_id].\n"; - - $byron = new Author(); - $byron->setFirstName("George"); - $byron->setLastName("Byron"); - $byron->save(); - $byron_id = $byron->getId(); - print "Added author \"George Byron\" [id = $byron_id].\n"; - - - $grass = new Author(); - $grass->setFirstName("Gunter"); - $grass->setLastName("Grass"); - $grass->save(); - $grass_id = $grass->getId(); - print "Added author \"Gunter Grass\" [id = $grass_id].\n"; - -} catch (Exception $e) { - die("Error adding author: " . $e->__toString()); -} - -// Add book records -// ---------------- - -try { - - print "\nAdding some new books to the list\n"; - print "-------------------------------------\n\n"; - - $phoenix = new Book(); - $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); - $phoenix->setISBN("043935806X"); - - print "Trying cascading save (Harry Potter): "; - $phoenix->setAuthor($rowling); - $phoenix->setPublisher($scholastic); - $phoenix->save(); - $phoenix_id = $phoenix->getId(); - print boolTest(true); - print "Added book \"Harry Potter and the Order of the Phoenix\" [id = $phoenix_id].\n"; - - $qs = new Book(); - $qs->setISBN("0380977427"); - $qs->setTitle("Quicksilver"); - $qs->setAuthor($stephenson); - $qs->setPublisher($morrow); - $qs->save(); - $qs_id = $qs->getId(); - print "Added book \"Quicksilver\" [id = $qs_id].\n"; - - $dj = new Book(); - $dj->setISBN("0140422161"); - $dj->setTitle("Don Juan"); - $dj->setAuthor($byron); - $dj->setPublisher($penguin); - $dj->save(); - $dj_id = $qs->getId(); - print "Added book \"Don Juan\" [id = $dj_id].\n"; - - $td = new Book(); - $td->setISBN("067972575X"); - $td->setTitle("The Tin Drum"); - $td->setAuthor($grass); - $td->setPublisher($vintage); - $td->save(); - $td_id = $td->getId(); - print "Added book \"The Tin Drum\" [id = $dj_id].\n"; - -} catch (Exception $e) { - die("Error saving book: " . $e->__toString()); -} - -// Add review records -// ------------------ - -try { - - print "\nAdding some book reviews to the list\n"; - print "------------------------------------\n\n"; - - $r1 = new Review(); - $r1->setBook($phoenix); - $r1->setReviewedBy("Washington Post"); - $r1->setRecommended(true); - $r1->setReviewDate(time()); - $r1->save(); - $r1_id = $r1->getId(); - print "Added Washington Post book review [id = $r1_id].\n"; - - $r2 = new Review(); - $r2->setBook($phoenix); - $r2->setReviewedBy("New York Times"); - $r2->setRecommended(false); - $r2->setReviewDate(time()); - $r2->save(); - $r2_id = $r2->getId(); - print "Added New York Times book review [id = $r2_id].\n"; - -} catch (Exception $e) { - die("Error saving book review: " . $e->__toString()); -} - -// Perform a "complex" search -// -------------------------- - -try { - - print "\nDoing complex search on books\n"; - print "-----------------------------\n\n"; - - $crit = new Criteria(); - $crit->add(BookPeer::TITLE, 'Harry%', Criteria::LIKE); - - print "Looking for \"Harry%\": "; - $results = BookPeer::doSelect($crit); - print boolTest(count($results) === 1); - - - $crit2 = new Criteria(); - $crit2->add(BookPeer::ISBN, array("0380977427", "0140422161"), Criteria::IN); - $results = BookPeer::doSelect($crit2); - print "Looking for ISBN IN (\"0380977427\", \"0140422161\"): "; - print boolTest(count($results) === 2); - -} catch (Exception $e) { - die("Error while performing complex query: " . $e->__toString()); -} - - -// Perform a "limit" search -// ------------------------ - -try { - - print "\nDoing LIMITed search on books\n"; - print "-----------------------------\n\n"; - - $crit = new Criteria(); - $crit->setLimit(2); - $crit->setOffset(1); - $crit->addAscendingOrderByColumn(BookPeer::TITLE); - - print "Checking to make sure correct number returned: "; - $results = BookPeer::doSelect($crit); - print boolTest(count($results) === 2); - - print "Checking to make sure correct books returned: "; - // we ordered on book title, so we expect to get - print boolTest( $results[0]->getTitle() == "Harry Potter and the Order of the Phoenix" && $results[1]->getTitle() == "Quicksilver" ); - - -} catch (Exception $e) { - die("Error while performing LIMIT query: " . $e->__toString()); -} - - - -// Perform a lookup & update! -// -------------------------- - -try { - - print "\nUpdating just-created book title\n"; - print "--------------------------------\n\n"; - - print "First finding book by PK (=$qs_id) .... "; - - try { - $qs_lookup = BookPeer::retrieveByPk($qs_id); - } catch (Exception $e) { - print "ERROR!\n"; - die("Error retrieving by pk: " . $e->__toString()); - } - - if ($qs_lookup) { - print "FOUND!\n"; - } else { - print "NOT FOUND :(\n"; - die("Couldn't find just-created book: book_id = $qs_id"); - } - - try { - $new_title = "Quicksilver (".crc32(uniqid(rand())).")"; - print "Attempting to update found object (".$qs_lookup->getTitle()." -> ".$new_title."): "; - $qs_lookup->setTitle($new_title); - $qs_lookup->save(); - print boolTest(true); - } catch (Exception $e) { - die("Error saving (updating) book: " . $e->__toString()); - } - - print "Making sure object was correctly updated: "; - $qs_lookup2 = BookPeer::retrieveByPk($qs_id); - print boolTest($qs_lookup2->getTitle() == $new_title); - -} catch (Exception $e) { - die("Error updating book: " . $e->__toString()); -} - - -// Test some basic DATE / TIME stuff -// --------------------------------- - -try { - print "\nTesting the DATE/TIME columns\n"; - print "-----------------------------\n\n"; - - // that's the control timestamp. - $control = strtotime('2004-02-29 00:00:00'); - - // should be two in the db - $r = ReviewPeer::doSelectOne(new Criteria()); - $r_id = $r->getId(); - $r->setReviewDate($control); - $r->save(); - - $r2 = ReviewPeer::retrieveByPk($r_id); - - print "Checking ability to fetch native unix timestamp: "; - print boolTest($r2->getReviewDate(null) === $control); - - print "Checking ability to use date() formatter: "; - print boolTest($r2->getReviewDate('n-j-Y') === '2-29-2004'); - - print "[FYI] Here's the strftime() formatter for current locale: " . $r2->getReviewDate('%x') . "\n"; - -} catch (Exception $e) { - die("Error test date/time: " . $e->__toString()); -} - -// Handle BLOB/CLOB Columns -// ------------------------ - -try { - print "\nTesting the BLOB/CLOB columns\n"; - print "-------------------------------\n\n"; - - $blob_path = dirname(__FILE__) . '/etc/lob/tin_drum.gif'; - $blob2_path = dirname(__FILE__) . '/etc/lob/propel.gif'; - $clob_path = dirname(__FILE__) . '/etc/lob/tin_drum.txt'; - - $m1 = new Media(); - $m1->setBook($phoenix); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - $m1_id = $m1->getId(); - print "Added Media collection [id = $m1_id].\n"; - - print "Looking for just-created mediat by PK (=$m1_id) .... "; - - try { - $m1_lookup = MediaPeer::retrieveByPk($m1_id); - } catch (Exception $e) { - print "ERROR!\n"; - die("Error retrieving media by pk: " . $e->__toString()); - } - - if ($m1_lookup) { - print "FOUND!\n"; - } else { - print "NOT FOUND :(\n"; - die("Couldn't find just-created media item: media_id = $m1_id"); - } - - print "Making sure BLOB was correctly updated: "; - print boolTest( $m1_lookup->getCoverImage()->getContents() === file_get_contents($blob_path)); - print "Making sure CLOB was correctly updated: "; - print boolTest((string) $m1_lookup->getExcerpt()->getContents() === file_get_contents($clob_path)); - - - // now update the BLOB column and save it & check the results - - $b = $m1_lookup->getCoverImage(); - $b->setContents(file_get_contents($blob2_path)); - $m1_lookup->setCoverImage($b); - $m1_lookup->save(); - - try { - $m2_lookup = MediaPeer::retrieveByPk($m1_id); - } catch (Exception $e) { - print "ERROR!\n"; - die("Error retrieving media by pk: " . $e->__toString()); - } - - print "Making sure BLOB was correctly overwritten: "; - print boolTest($m2_lookup->getCoverImage()->getContents() === file_get_contents($blob2_path)); - -} catch (Exception $e) { - die("Error doing blob/clob updates: " . $e->__toString()); -} - -// Test Validators -// --------------- - -try { - - print "\nTesting the column validators\n"; - print "-----------------------------\n\n"; - - $bk1 = new Book(); - $bk1->setTitle("12345"); // min length is 10 - $ret = $bk1->validate(); - - print "Making sure validation failed: "; - print boolTest($ret !== true); - - print "Making sure 1 validation message was returned: "; - print boolTest(count($ret) === 1); - - print "Making sure expected validation message was returned: "; - $el = array_shift($ret); - print boolTest(stripos($el->getMessage(), "must be more than") !== false); - - print "\n(Unique validator)\n"; - - $bk2 = new Book(); - $bk2->setTitle("Don Juan"); - $ret = $bk2->validate(); - - print "Making sure validation failed: "; - print boolTest($ret !== true); - - print "Making sure 1 validation message was returned: "; - print boolTest(count($ret) === 1); - - print "Making sure expected validation message was returned: "; - $el = array_shift($ret); - print boolTest(stripos($el->getMessage(), "Book title already in database.") !== false); - - print "\n(Now trying some more complex validation.)\n"; - $auth1 = new Author(); - $auth1->setFirstName("Hans"); - // last name required; will fail - - $bk1->setAuthor($auth1); - - $rev1 = new Review(); - $rev1->setReviewDate("08/09/2001"); - // will fail: reviewed_by column required - - $bk1->addReview($rev1); - - $ret2 = $bk1->validate(); - - print "Making sure 6 validation messages were returned: "; - print boolTest(count($ret2) === 6); - - print "Making sure correct columns failed: "; - print boolTest(array_keys($ret2) === array( - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE, - BookPeer::TITLE, - ReviewPeer::REVIEWED_BY, - ReviewPeer::STATUS - )); - - - $bk2 = new Book(); - $bk2->setTitle("12345678901"); // passes - - $auth2 = new Author(); - $auth2->setLastName("Blah"); //passes - $auth2->setEmail("some@body.com"); //passes - $auth2->setAge(50); //passes - $bk2->setAuthor($auth2); - - $rev2 = new Review(); - $rev2->setReviewedBy("Me!"); // passes - $rev2->setStatus("new"); // passes - $bk2->addReview($rev2); - - $ret3 = $bk2->validate(); - - print "Making sure complex validation can pass: "; - print boolTest($ret3 === true); - -} catch (Exception $e) { - die("Error doing validation tests: " . $e->__toString()); -} - - -// Test doCount() -// -try { - - print "\nTesting doCount() functionality\n"; - print "-------------------------------\n\n"; - - $c = new Criteria(); - $records = BookPeer::doSelect($c); - $count = BookPeer::doCount($c); - - print "Making sure correct number of results: "; - print boolTest(count($records) === $count); - -} catch (Exception $e) { - die("Error deleting book: " . $e->__toString()); -} - -// Test many-to-many relationships -// --------------- - -try { - - print "\nTesting many-to-many relationships\n"; - print "-----------------------------\n\n"; - - // init book club list 1 with 2 books - - $blc1 = new BookClubList(); - $blc1->setGroupLeader("Crazyleggs"); - $blc1->setTheme("Happiness"); - - $brel1 = new BookListRel(); - $brel1->setBook($phoenix); - - $brel2 = new BookListRel(); - $brel2->setBook($dj); - - $blc1->addBookListRel($brel1); - $blc1->addBookListRel($brel2); - - $blc1->save(); - - print "Making sure BookClubList 1 was saved: "; - print boolTest(!is_null($blc1->getId())); - - // init book club list 2 with 1 book - - $blc2 = new BookClubList(); - $blc2->setGroupLeader("John Foo"); - $blc2->setTheme("Default"); - - $brel3 = new BookListRel(); - $brel3->setBook($phoenix); - - $blc2->addBookListRel($brel3); - - $blc2->save(); - - print "Making sure BookClubList 2 was saved: "; - print boolTest(!is_null($blc2->getId())); - - // re-fetch books and lists from db to be sure that nothing is cached - - $crit = new Criteria(); - $crit->add(BookPeer::ID, $phoenix->getId()); - $phoenix = BookPeer::doSelectOne($crit); - print "Making sure book 'phoenix' has been re-fetched from db: "; - print boolTest(!empty($phoenix)); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc1->getId()); - $blc1 = BookClubListPeer::doSelectOne($crit); - print "Making sure BookClubList 1 has been re-fetched from db: "; - print boolTest(!empty($blc1)); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc2->getId()); - $blc2 = BookClubListPeer::doSelectOne($crit); - print "Making sure BookClubList 2 has been re-fetched from db: "; - print boolTest(!empty($blc2)); - - $relCount = $phoenix->countBookListRels(); - print "Making sure book 'phoenix' has 2 BookListRels: "; - print boolTest($relCount == 2); - - $relCount = $blc1->countBookListRels(); - print "Making sure BookClubList 1 has 2 BookListRels: "; - print boolTest($relCount == 2); - - $relCount = $blc2->countBookListRels(); - print "Making sure BookClubList 2 has 1 BookListRel: "; - print boolTest($relCount == 1); - - -} catch (Exception $e) { - die("Error doing many-to-many relationships tests: " . $e->__toString()); -} - -// Test multiple databases -// --------------- - -try { - - print "\nTesting multiple databases\n"; - print "-----------------------------\n\n"; - - $line = new BookstoreLog(); - $line->setIdent('bookstore-packaged-test'); - $line->setTime(time()); - $line->setMessage('We are testing to write something to the log database ...'); - $line->setPriority('debug'); - $line->save(); - - $line_id = $line->getId(); - print "Making sure BookstoreLog was saved: "; - print boolTest(!empty($line_id)); - -} catch (Exception $e) { - die("Error doing multiple databases tests: " . $e->__toString()); -} - -// Cleanup (tests DELETE) -// ---------------------- - -try { - - print "\nRemoving books that were just created\n"; - print "-------------------------------------\n\n"; - - print "First finding book by PK (=$phoenix_id) .... "; - try { - $hp = BookPeer::retrieveByPk($phoenix_id); - } catch (Exception $e) { - print "ERROR!\n"; - die("Error retrieving by pk: " . $e->__toString()); - } - - if ($hp) { - print "FOUND!\n"; - } else { - print "NOT FOUND :(\n"; - die("Couldn't find just-created book: book_id = $phoenix_id"); - } - - print "Attempting to delete [multi-table] by found pk: "; - $c = new Criteria(); - $c->add(BookPeer::ID, $hp->getId()); - // The only way for cascading to work currently - // is to specify the author_id and publisher_id (i.e. the fkeys - // have to be in the criteria). - $c->add(AuthorPeer::ID, $hp->getId()); - $c->add(PublisherPeer::ID, $hp->getId()); - $c->setSingleRecord(true); - BookPeer::doDelete($c); - print boolTest(true); - - print "Checking to make sure correct records were removed.\n"; - print "\tFrom author table: "; - $res = AuthorPeer::doSelect(new Criteria()); - print boolTest(count($res) === 3); - print "\tFrom publisher table: "; - $res2 = PublisherPeer::doSelect(new Criteria()); - print boolTest(count($res2) === 3); - print "\tFrom book table: "; - $res3 = BookPeer::doSelect(new Criteria()); - print boolTest(count($res3) === 3); - - print "Attempting to delete books by complex criteria: "; - $c = new Criteria(); - $cn = $c->getNewCriterion(BookPeer::ISBN, "043935806X"); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0380977427")); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0140422161")); - $c->add($cn); - BookPeer::doDelete($c); - print boolTest(true); - - print "Attempting to delete book [id = $td_id]: "; - $td->delete(); - print boolTest(true); - - print "Attempting to delete author [id = $stephenson_id]: "; - AuthorPeer::doDelete($stephenson_id); - print boolTest(true); - - print "Attempting to delete author [id = $byron_id]: "; - AuthorPeer::doDelete($byron_id); - print boolTest(true); - - print "Attempting to delete author [id = $grass_id]: "; - $grass->delete(); - print boolTest(true); - - print "Attempting to delete publisher [id = $morrow_id]: "; - PublisherPeer::doDelete($morrow_id); - print boolTest(true); - - print "Attempting to delete publisher [id = $penguin_id]: "; - PublisherPeer::doDelete($penguin_id); - print boolTest(true); - - print "Attempting to delete publisher [id = $vintage_id]: "; - $vintage->delete(); - print boolTest(true); - - // These have to be deleted manually also since we have onDelete - // set to SETNULL in the foreign keys in book. Is this correct? - print "Attempting to delete author [lastname = 'Rowling']: "; - $rowling->delete(); - print boolTest(true); - - print "Attempting to delete publisher [lastname = 'Scholastic']: "; - $scholastic->delete(); - print boolTest(true); - - print "Attempting to delete BookClubList 1: "; - $blc1->delete(); - print boolTest(true); - - print "Attempting to delete BookClubList 2: "; - $blc2->delete(); - print boolTest(true); - -} catch (Exception $e) { - die("Error deleting book: " . $e->__toString()); -} - - -// Check again to make sure that tables are empty -// ---------------------------------------------- - -check_tables_empty(); - - - - - -$timer->stop(); -print $timer->display(); diff --git a/airtime_mvc/library/propel/test/etc/lob/propel.gif b/airtime_mvc/library/propel/test/etc/lob/propel.gif deleted file mode 100644 index 48e881ef5f537ca18162b0dd36467d88549ed225..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2671 zcmd7Pi9geg1Hkd`PTPoyoMD^Ck)uT9e4be-jH!pTFS!dVP*N95c7@?F1ZvMKbWmAAf9YY}D1|fL$6Z zBEZef&B@8BzrQ~$EKDpGJ32bX#Ka^dBoq}DEiElgPEMAVmh$=h4<9~^kB^6jhWh#W z`TP5Kc6Q#laU&xmgTY|b)YRnX=eM`F3x&ee)Ko5)yVi*Vx97p-%GK57moIC6tc$@O z!{z0LotU=Zgqj zNNs8=dH;S2Tq+zH=>oqrf@1-#tz7Wy(B|eE_+t$mbeNp%`!*g9&eFj?tF39;z(B{> z0m^!}QCF7$1VP~cFZ?zf0sv&d;6K`bPXGy!MvjeR#NSO|vJ#Wn$tkI6>3?TrW@YE( z-pk7`D7;_9DSq&<!0~Po%rM(c&SlazCK(ZsIWnGb%ed|4?=mv+$9F7~S=0C0}h6fUJJYL5)h)Ya2M2 zuC(S6|7kUlGa+H!1%y60b{E#Z8{6vr06-gGC@|`@WgvH%6HbV6advQdLlQ<@41uwf zNXOci*3Kib$UXb=7o`-W6flaIle3++aaT67n~prq7!km~XFoE@q}d8e0Hv~X0}$9y z2%+Kn&qU5>F|c7Nd~i_nu9)uxsvtTyv+l)L#fr&}$8$#dY$>0N^=UbJr(5TCA2nxh zQD7m6b2IL%^$}7^Y|C?dga&cNulkMIg{8)#OFd)z?<-W|F5)FlojM?Cb!ok}y&{NG z{ln}o`q;^Uclzg5iNP0sz)w;Q#)6B{9TqqCXW}d`O2zklHgtM(lrl-WbpS)P-8%Fv z?y01La%*GMk&ka9HRY$QX{2s2Z%uk~E$ryLRy+iyOs5v!UhsWHvwLlOTn4E&f5_Iy zIv~dxq8yb*baU^`k%uiQf6cm#mXE^R`HAje$R0APRRNR)*=|vHvbOLcWOMUmM2{@g zBR&qxkPeOeVg44ke#svKhRE$rC}4B7-c4NnY1m3iN>*x+LNO@rXDYjI<|*3D z4ZO>fgB-$oon`XQE|ooRLX>e5m_{UNYu(sS#-X#1cjbr_bb|1w_D5W-Ae--7z&B(5 zE|QCAv$&j|MsITs(C4lA)LCN>ike`$eN}!-?r@Svg8lbL1SpKEP~7e8*xAspt!E$G zC7(77AGc`T3)UBijN&NxZVK!Ii;aUdZ@s~m-&fr8O))ZEZS9F!lKH-%vcyZ}G@GhY z#e<=i3OLytKQ9z8JXd>?Ia_aLHNHO*AIBK72KP zE8wFd5cwdni*?mR0Mrr)!tl1f-*(b!&6!R(Qvkzw6y4$Pw!AR7OzyAs&z1grpm7lK z+3p4AOl(|lcnk4cpXR`LHO!bS4w|C%noQs|W(Qj*0e0wei4BtHKAYHo21vQz4{O9t zRrtM-$?>yh&nn3-hj@fh5t>~5j!U))n>`3+8pReN^P>%EIm_NPBf4K8(pBa1H z3VeM}f0k?W??Dr7JRuhi)D?QhAT@^atC==P+OnUYxOp7jsG@R@+zn7YUHT>R~Bk-2D?20i zFa_RL_BH8NO&#{%o9}f!srH4Hy^5Yf9sFAPpO7UY`n?b(x=FXEThcjSf=RNBX(pOB z|3GU1VQ17>9Zk&4wWPF4r+lC!+>XlB(j}1`^(c5Jxe|ibK1a2Wr~RPC68eSZ#53YJ zUknGKC!jk;d-M^c)=Mo6%i-#xJ~f~iP14fC|Gomren6~90NnvN@-G_3C|X`oSL9YR zib7FD@>b?EB6}}XvRQmuX*)Dphm-OyZ!3&-zIq|s{*CJqM!JLEF%{6P#xZ`HMf2S zUAQwt#~4gQC5%K87#U04meu5J}!3?=%Ohjsg%097s|~7E~R_ zkibwqU#W=rBZGj%rU(6BBnK)lGK}D_O+cN$LKeILo)i&+61j27;)t%zv&v5US7I<&0~Ys|p5z#YPVup$isf);^*RK(kMbaON}yy41kO^_eonY1qhuUaG#6i;iFz4J$o>Ai(Af zj@;(Y2u_Rm0MdXimBWA>>H^v z7Hvk1VtJw3kSY@gkbJnd0i7R_KOS_lHoeBc2W2f7gp@@ds9bir{;i?K)22F1MigXw zDW=;qoruVltXy-Ya#f6gv=@nrtjjlRkt+wh9)BK_8IFS?FLATc_;a|Nadptt4btX0 z!A|AR_*Ma4GAUCB`O6E-^Ta$Ix{rP3-rdUDT-_2+)?8>EHt%+OMppAi$LU#UR5Bc1 N`HOj7RTB$X{ST6!mO}sl diff --git a/airtime_mvc/library/propel/test/etc/lob/tin_drum.gif b/airtime_mvc/library/propel/test/etc/lob/tin_drum.gif deleted file mode 100644 index a0de847bb781a3a8d119daa27ac4e650d5245d4e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8202 zcmW-j2Urv58^ABQ%jL3aCy%2qC64>2HG#A?G3LDU9BMR6n{EM69;My;T=<{$cd?|t9j`#sZt7n{otm37r~!jaOwIqLpPg9PH8nLgH}P`*{lcZk@aU8Nq0#>5kA{YZMh&U&>Kz*D?;jfad8nsA&04e@lPqyPlrAkK1qe^xV2($c4D2Z))keb@kSQ8ZgL3eM4>A zf*Im!d)vjU3*Ep)ecAD=SDG(gy?9Y=m@eu|3NJ3u-1PnT%@>>RoUFds+^m=7wKN&J zfja$x?E2>Vx>L=~wblCFyXy_qRaDg1SJqeRccu;;I#g*e1ILSsDvR{u5_ z7w70V#wm)56h#VsOtiw#6pCW$5ruqzwnCAu$kqp~c^e*?ZLsWYy-=8aVE69q?A_VB zt5Xv7ULF|+TOciM_wMbx(-Qwv{R-EeX@;e=9Xk>d)6x>t5_Tmf>KF42LtFq9437>A!GvL9Zva3T_Fovv0$yH1p%wtVgoZG%P@KJlJ|2AM1#xZx z0B1v6z|qm!%hAvb@?X00>>M4r3IO0bI&%%?$mRZ*UlRy6Tqcw2$TTb%l4)R}I5HS0 zlZ!H$C=+F&Oba?0MVX!efTAdZGHED+{AY%SEC2uq3K#~!Acpv_0l=~aS$GyO!^P=I zRv~ItM-F1*^i{7qzB6m)Ez5M#C60F?%r(#SSjqO08|fSUhg)^GO6Q%(H|@*54U@gy zLXIdbBODKD5xp8*{HnOj)hBB4cDL|F=fAw0*(WT=38jWpFad4KS>7UE?VC^j31@$C z-L%)DkPHYNHWwZYncbeW({7RX7pVo5^`$GsW94t_*FXC1djcggGyTlb3u9eL-^9Gj zkNmY|b(~z|Y1G*9^Zf$Xw9y@&SiZxF@u=q`A2JlYs(0&ccMjKf9r^s})qQ(Ly>rwK z`N6DvwQqiAi0G_}xzeg+!nMzR{~WjPgTh`|e`vBNbYn{V>}6h;d7DVsI*Q0Q*n z#(g7A4=X^&3PG|Z>Uz|wZJEx&^Ns_cp}jLrVtCy6YLI9p8PUs-rKL$_xmNcsd|KNdIp4181-%v5#`vXf7nCeVJ)bJPREpqN0PRwcGPH zaxc3FzsC$UBE9n066TGO7t$0L-5%|1x z;_?@q0BXYF)8n?nkM%DioD`}u1;d%sNH7akh%_-PBJNn6s#$dhqi?Sqr2Po5DTy_^ zFk-Zkwrq#S4n%l#cJg=roQFmp1-5?~k&~2noI;@6HSY$z0Dr5S7rK^*lP;RvUt~Q@ zl+F*c)OcWV{Usb7P+}gW)qqIGh#XVNaI2XBjs#qgd?shQYW{IUkLM^L-hCx}`?Jib zW~7TfClN!7QW&MYaUNaKi#HQ8GS^JoC^(R5xkh1!jv-+jyiukq$D~#ZpPdi(pvUK} ztZbx)ddf)~dxd6f8OdFZL-i#Ze{=j8(ND}Z{zd}w@MDGUN&&g3Kw)V+2D@uJXeHA* zmTE02k`FqRmzAt;lNP$PB(Q>1_~oDQ_SfhAV~W%!0@Ygk7EQ;-oARUV9h@vtO=qM~ zfC+XGh(4hZ>3xc+k@60ZHgnASOI3vjA}b9Nk8i#Q;7&?A_`J#c>kzffNh`Mk{wT(u zp0Pckw6kbO33l&QuyYcZ9IPyA1cGn9fiS>fQf_};P-?D(jrA=sx7#C(`JmBqkpKAf zDZHYB1zGEu(Jl;}VnX@yge4+m=h-Q@roc6Nb-wdQoz+laFkmn3Tx?FrO-+6Y@0!jH zdnC{oe_bgz+K2d?9#!V_)vG|uNexMiLGCTjt;Y+1ZCjKLM?}RY@lrw6DdDZJU38Go zB%T{1Xgs0@H=jr=^P3eg_Kd$^*J~d6krSD0YPZenNlV6S|EjU&QrybePU{#M+x!D) z)q1VV$bC<>)v|7SzBA4YNxzp@Wb4{6f7dIlG1o-NfCWg7{rRW?g%uTucL;HES3i1C zFvfYN!JF#DBrIYb&gGW(`eHE4*0K*V!^*xL24{Eowo?sn$^b())rB-xDW00>#uOywGZ%z z)AKFS4$qphJg@!n%7Yhjte%O25A29%T5F2-!hQH{*QXg_)nc>PPaaqWHIi#oT-R=t zU{cV*W`ulcHhk?4rcK8`cjuYpdrd)!D#{F$R7WACC&LOWC`6m-e!M_>Ha;`m`U*Qu~TlDQs z7)Z)U{nqUP-n*=U^RN{&2Uu@_##xGZP)2PAUx!4|w2kvdjqJFTwvkB)MdSpXcxUr)Ckz%ym6l$mm$H9zsG5~ZVgAXRT&FaBP2iSKF2{@|F%>=o5HsQ}{*pp|ME)r7 zc$3SC=38q_zOejtqcIMkPx4I5l!4Ywa`5DvamY*6&E3wv+oD+P5czE``rhG~C?o+I z!)Yuo47SzWO((29vnhtHHWy%;H!ZPA4_C87+kqx}TBw2>HRg9INep_416(!g+*Sa< zt*I6QhjifeRGrz|kYHDA4DQ<@#o?qBCxj&RQ{c@G=%nn=SUwTZ(TYP9?Ajo6BPD=8 z|KfwiB;TA?FO#lKl^V01>0a+(Uuo&Sz1b!Ob@!Sq+L?E_IuW7orVg?k*5DCM9JbaK zuy5(~Z5^=m>3!isk#^{_a!HiC#miQWER|>-KlJ_-V=z~Nrr~hqp^Lbqvity8-DV$Zh()$mn+!!CCdt; z4tigq818Dma5Z<{5(o_E?@@M#PUX zo~lXEwJ6_7R=9?gQbBy$!wS}t#xYvHl7In+i~wer9RQ&?dki`xrhWwI=T5WU=B_)h zgk7ZjhdkJP6`?^wr-WDt_(T;($piRaTH<{je`PrXeN5};Q(HOY(rKq89U)2$iS%kH zN&{E&sULM|b@A&0V`=qTZrHFl4g-on!hQ|;bI10ic)UQm%Zg~()<}P*p*_-3`!RYy z9~U))f2f2C1dzwyv?dI;AlP;m*w~nDC{j~KG%4Rr+O~E?e*o<2CCt~0(ds}XREsMx zX5&Rg2>_{G6aQ>4<1vRkm$wZ}XJl4KCrkNHIp}LOITZjCVJ5E}jGIQfRCKx#qg5lF zYb3YQcb#H+h)e!h3>UKTugk095*tu2lJmiCbE35y+WiOylptA6CUwx8rx`l6BZ;37 zWNh{}5S}b z1;D%k;HK(09F~LbG^y|e)pI!b){Mht z-s{KAG+1NCe%j4xBvq5RA@%Gmu%v)b9pKkPIG45NTRlwZZ^drZ0mfUDuGO5`nHZe! zOt>p{`;5_VV8})hm@pI$&d^63;Yy5jUPqnMHk~<2mTOk$IqyAtp7P^Frt1)t--@sB zrp%a_9ae6;CoZ;=%4&_W^UENK1ZkV5MfPD1VdlwEt{DoZ_O)59=0E`s%mb8gtJNV5 zWH-$n=F5oO^ zTpb}q0`qxtYA*vhYzFsG^6Jtz73A8?Ey{&8I4cZ)Vd>SM-ml@`024IG zc|P^Nh*o>`a9#*$-G@tOE&r#vQPk;kvwPFc?(b*{DXodKPKUzXd}<|z?$g3EI^;PA z{aZ_tN{IEkuk{k*A-#%x0z*@ENF93X!(*aOL+T!+i8Pc{aUEDDg>dw2F=cWos^pU^ zwaxf+%03ZoBPs*A#N!x+ypN$k8Hd)PIlvjnhwJQ#ydbMEoxl3&qJwYDI`)x+RBkid@0IITXN`l{S&CXjOq1dZuRKWp z@)97*NLPe3jXcQi@QcEQJ{uu#nSoDso9wZNuqf9?H9oEE?g7*<<}AgMj}MiQ`_v}I ze6#k5%oRFvP%FNczqLgN<;ejAOA`pNvUkLGD>9&0?hcCTg+*pt?2$F17Eh7sH;IcH zB`}QP4{%6oHSH1~2T#M_h|{8QxFf24ev1!3<-@;nPtEEKZ){kk1hrq{UNzxv8eRRK za?>go@ZuADq_mg+V-;S(1&GLhlvz*aty6H@qBtz#@wiTZ-xO>OrJ!zgjb$w_>0Q^k;rmN)^>e;pwH@w#;u zqcv#qswcuNHQ+u8<>NfVBaNBNa;U@z@9m4I66hT6RB$=$(2Ty;kY}zvQ(LZ8a(MWe z%>|A4>$8k!8WI!&?0;q1AoH0MCv+#{WvS?(RKZdK-dea#O>a;``58783``P}bN^u! z96I{BnND^GEzLaJ$4A;V^a1PPf->j<3a|h0tJUA(EDk7Kk(_|A=TAaxEqloyV`;yyF;B2X|Bz79m7tO2h@BAJ ztrzhJ#>ZEp#5>}sC=!yWgnTu>o(L`#JAfO-q!&+*)Ry5!MT(~)GV5_+_`LT%owLw$ zjR#7+4Q#%0i>{cbTo98Kd}6$kP<;}tqk%3cv{6a?QN?J*EL_w}%gpsM_)jQ0iBZQcqaQhpNsRuBigQ6nsz8yg_u*84DCLv;b&PFSSvO-9_eQzT zU%$~o;Cc+{P&x_NW=n6T%UkGAQQCbq=YooSQ$ib;;7>O~tPEO{=yhkx6h(`35v!Y3 zR2Puoq$T8`)Y0&pm${7BeEKttJ^_eVs=m>2%A;glP(VMgSHZEu)q}3=#g`!oAk(#U zUA`6VMoL<01m)rIqc`a7Qlfy9d^_s*_5j=3QR3;AtE)@V%K{&r);_6~=&_zwCn9Vi zSU-3dE@na!lxMT$ZxFv3Y^cHu=;t`_{0`|n?(dBf%td~8}W->o`9?0%zY<~c3?P%K$#2gxI z!DyBQ>;0SCzP$LTo@>u+dFPN<=9-P^W%qThlr^PRJMZwa)oZV0K}$b;42FB#v(CrJ zZV-dFeU&?Y*m^J{F$Xxl)B}J0YUG8swz5@0A-V}0=gjyB9w3Scw{L}-bB(UNwpm;( zS#j?>cXDL8iKRJj165j~zj6?34%``5VEuz#c`oSLxiq--*uWOIhttms%YAx!s#Xn4 ztA$6#_gWj9KtcI5BPV{WH1@GaYmvJ!Iwb8{u*njjJBnEx66bJIi#L2YEpu~X)`hTB zBXGQ8CzVuqj6W=Gx)J}#XsKPX(ypL$&hwssn8Iv()eN7pb<~J*v?StMM>iD=us_r2Z3`DKKI{M$mz2!kz4Qk%8_do)pMJ(- z&nJOBRNN^EVyoVg`kO3Y;xar5J8(rRXP;@kqs>+XOUnO}tL|#FCHN(k2n6>6(kNMp ziua4`%veZXmT!8Hjf($nlCbwJ%O$Yykt&~)qPGqZ| z`1V#DS@I!J_(RKIE#wVri&zw-8DWIyxm!6|eYVW?ykq#SvX5Rti#C4_$s}!Sd6isW zoj7~UE?WI>a72me`~VaQ+b#wi-V{d^A0(3VcU^y#b?K;?KI(46`UldS$H$($Y+-Z| z4*XzuUGwToi{Litn8K0(GspKRN8Zx7DyB6T_?h*^$x+0NBTg_alzq$Q^v!3j1vKoEi&YAGz%%NIcX+|MPgsp3BIlIk)RC z&h`=#a@%uGp?aGv-S^p0b};Ubo-Hrl8m&JfH~<{$;`Pf)~Q~9Q<1!S-y28!CG&T@Gz8O>Njx+3 zH`w=`j2d3h2wT6gxhl*-fMp!Y;aCE>%c%S9!vq4r*Vs7hqcZ6{pI&C5&1Gc{jU!zO zi0*pN8om-Ec~)<4AinVYot=tAn`ZE+&-You_d?}`fT#bU?o8>f5jh%%2#NRB)#Xfv z+MKEbm*zPKbMUhz8c*15mRTbC6ka(t+~Z#2+&$80Yb0&^DwsUOD5EBpxwZfagSO}q zY2u-Hox(oPneJ^2v0F~paU>FS(F0*cWnJ!)s&kYzzB&#X>%SsnZdI|Khs&K*1zJh9 zxJ^NMoKQe&ZY4k>N1j{6|F6L255ANUno#qNXRoQ7V?mo6&g_Z=2W(NB%QO8=U55$HvvzvUgzi~YAN7w{J~@IPN@ZtORMAut<{embMxG3 z=R6F%T^50TTG_5Id*$36xX$VeUCeqhXyh%{27G9;7#}GBm?GS8ZoKh*@!5#aW9r&^ zfN^ly$&h-%vA{=-bUQ#wS-n`XoaaQ34-wKu8UW%f(F6Ecj40>8VFCUL?cXVIg(vphPA9Er(|6vLopr;^~n>+rGD{AqD)L(zv%yO_bESo)G_HZCOjGF2=y zXXC1>mvz}4Y6)^ej5aTUxQLq+M-EcU=-38eX=Fqk2aw*#l$-v1jkvO)1Bqn*jxeQC zp^x!cZ^U~j5>u$8ry5G?HH@g4>JE|<`s;{=XUMmmV5z&5o*6L40hO?cOTeQaws1(t zuLYgmRb_5^df;?n`2)%+^)F$$DzrrR{KR5Asfnh8=~ozB=8Fg8s(W#1$yX$(7`VgK z+(JZ5NmJ(P1pT1dEsA; z=CH>_u>EyDUbqdx2RSUe - - - - - - - - -
- - - - -
- - -
- diff --git a/airtime_mvc/library/propel/test/etc/xsl/coverage-frames.xsl b/airtime_mvc/library/propel/test/etc/xsl/coverage-frames.xsl deleted file mode 100644 index edfcf2983..000000000 --- a/airtime_mvc/library/propel/test/etc/xsl/coverage-frames.xsl +++ /dev/null @@ -1,636 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Coverage Results. - - - - - - - - - <h2>Frame Alert</h2> - <p> - This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. - </p> - - - - - - - - .bannercell { - border: 0px; - padding: 0px; - } - body { - margin-left: 10; - margin-right: 10; - background-color:#FFFFFF; - font-family: verdana,arial,sanserif; - color:#000000; - } - a { - color: #003399; - } - a:hover { - color: #888888; - } - .a td { - background: #efefef; - } - .b td { - background: #fff; - } - th, td { - text-align: left; - vertical-align: top; - } - th { - font-weight:bold; - background: #ccc; - color: black; - } - table, th, td { - font-size: 12px; - border: none - } - table.log tr td, tr th { - } - h2 { - font-weight:bold; - font-size: 12px; - margin-bottom: 5; - } - h3 { - font-size:100%; - font-weight: 12px; - background: #DFDFDF - color: white; - text-decoration: none; - padding: 5px; - margin-right: 2px; - margin-left: 2px; - margin-bottom: 0; - } - .small { - font-size: 9px; - } -TD.empty { - FONT-SIZE: 2px; BACKGROUND: #c0c0c0; BORDER:#9c9c9c 1px solid; - color: #c0c0c0; -} -TD.fullcover { - FONT-SIZE: 2px; BACKGROUND: #00df00; BORDER:#9c9c9c 1px solid; - color: #00df00; -} -TD.covered { - FONT-SIZE: 2px; BACKGROUND: #00df00; BORDER-LEFT:#9c9c9c 1px solid;BORDER-TOP:#9c9c9c 1px solid;BORDER-BOTTOM:#9c9c9c 1px solid; - color: #00df00; -} -TD.uncovered { - FONT-SIZE: 2px; BACKGROUND: #df0000; BORDER:#9c9c9c 1px solid; - color: #df0000; -} -PRE.srcLine { - BACKGROUND: #ffffff; MARGIN-TOP: 0px; MARGIN-BOTTOM: 0px; -} -td.lineCount, td.coverageCount { - BACKGROUND: #F0F0F0; PADDING-RIGHT: 3px; - text-align: right; -} -td.lineCountHighlight { - background: #C8C8F0; PADDING-RIGHT: 3px; - text-align: right; -} -td.coverageCountHighlight { - background: #F0C8C8; PADDING-RIGHT: 3px; - text-align: right; -} -span.srcLineHighlight { - background: #F0C8C8; -} -span.srcLine { - background: #C8C8F0; -} -TD.srcLineClassStart { - WIDTH: 100%; BORDER-TOP:#dcdcdc 1px solid; FONT-WEIGHT: bold; -} -.srcLine , .srcLine ol, .srcLine ol li {margin: 0;} -.srcLine .de1, .srcLine .de2 {font-family: 'Courier New', Courier, monospace; font-weight: normal;} -.srcLine .imp {font-weight: bold; color: red;} -.srcLine .kw1 {color: #b1b100;} -.srcLine .kw2 {color: #000000; font-weight: bold;} -.srcLine .kw3 {color: #000066;} -.srcLine .co1 {color: #808080; font-style: italic;} -.srcLine .co2 {color: #808080; font-style: italic;} -.srcLine .coMULTI {color: #808080; font-style: italic;} -.srcLine .es0 {color: #000099; font-weight: bold;} -.srcLine .br0 {color: #66cc66;} -.srcLine .st0 {color: #ff0000;} -.srcLine .nu0 {color: #cc66cc;} -.srcLine .me1 {color: #006600;} -.srcLine .me2 {color: #006600;} -.srcLine .re0 {color: #0000ff;} - - - - - - - - - -

All Classes

- - - - - - - / - .html - - - - - -
- - - - (-) - - - () - - -
- - -
- - - - - - - - -

Overview

-

All Packages

- - - - - - - -
- - - -
- - - - - - - - - - - - - - - - - - - -
Packages: Classes: Methods: LOC:
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Methods covered
Total coverage

PackagesMethods covered
- - - -
- - - - - - . - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

-
- -

Classes

- - - - - - - -
- - - - (-) - - - () - - -
- - -
- - - - - - - - - - - - - - - - - - -
Classes: Methods: LOC:
-
- - - - - - - - - - - - - - - - - - - - -
PackageMethods covered

ClassesMethods covered
- - - -
- - - - - - - - - - - - - - - - - -
Methods: LOC:
-
- - - - - - - - - - - - -
Source fileMethods covered
- - -
-
- - - - -
- - - - - - - - - - - - -
- - http://phing.info/ - -

Source Code Coverage

Designed for use with PHPUnit2, Xdebug and Phing.
-
-
- - - - - - -

Report generated at
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
 
- -
- - - - - - - - - - - - - - - - - - - - - - - -
   
- -
-
-
- - - - - - - - - - 0 - - - - - - - - srcLineClassStart - - - -
-
-
- - -
-
-
- -
-
- - -
- - - - - - ../ - - - - - - ../ - - - - - - - - stylesheet.css - - - - - - a - b - - - - - - diff --git a/airtime_mvc/library/propel/test/etc/xsl/log.xsl b/airtime_mvc/library/propel/test/etc/xsl/log.xsl deleted file mode 100644 index a460b667c..000000000 --- a/airtime_mvc/library/propel/test/etc/xsl/log.xsl +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - - Phing Build Log - - - - - - - - - -
- - http://phing.info/ - - - Phing -
- - - -

- - - - - - - -

-
- Phing -
-
- - -
- - - - - - failed - complete - - - - - - - - - - - - - -
Build FailedBuild CompleteTotal Time:
- -
- See the stacktrace. -
-
- - - -
phing.file
phing.version
- -

Build events

- - - - - - - -
targettaskmessage
-

- - - -

Error details

- - -
-
-
- -

-
- - - - - - - a - b - - - [ ] - - - - - - -
diff --git a/airtime_mvc/library/propel/test/etc/xsl/phpunit2-noframes.xsl b/airtime_mvc/library/propel/test/etc/xsl/phpunit2-noframes.xsl deleted file mode 100644 index 20b96a707..000000000 --- a/airtime_mvc/library/propel/test/etc/xsl/phpunit2-noframes.xsl +++ /dev/null @@ -1,445 +0,0 @@ - - - - - - - - - - - Unit Test Results - - - - - - - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Failure - Error - - - - - - - - - - -
- - - -
-
- - - - - - - - -

Packages

- - - - -

Package

- - - - - - -
-

- - - - -

Test Cases

- - - - -

TestCase

- - - - - - - - - - -
-

- - - - -

Summary

- - - - - - - - - - - - - - - - - - - Failure - Error - - - - - - - - - - -
AssertionsTestsFailuresErrorsSuccess rateTime
- - - - - - - -
- - - - -
- Note: failures are anticipated and checked for with assertions while errors are unanticipated. -
-
- - - -

Unit Test Results

- - - - - -
Designed for use with PHPUnit2 and Phing.
-
-
- - - - - - -

Report generated at
-
- - - - Name - Assertions - Tests - Errors - Failures - Time(s) - - - - - - - Name - Assertions - Tests - Errors - Failures - Time(s) - - - - - - - Name - Status - Type - Assertions - Time (s) - - - - - - - - - - - Failure - Error - - - - - - - - - - - - - - - - - - - - - - Error - - - - - - Failure - - - - Error - - - - Success - - - - - - - - - - - - - - - - - - - - - - - - - N/A - - - - - - -

- - - - -
- - -
- - - - - - - - - - - - -
- -
- - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/test/etc/xsl/str.replace.function.xsl b/airtime_mvc/library/propel/test/etc/xsl/str.replace.function.xsl deleted file mode 100644 index 626e5498c..000000000 --- a/airtime_mvc/library/propel/test/etc/xsl/str.replace.function.xsl +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ERROR: function implementation of str:replace() relies on exsl:node-set(). - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book.schema.xml deleted file mode 100644 index 27810c5ec..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book.schema.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book_club_list.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book_club_list.schema.xml deleted file mode 100644 index 6b6cb5fcd..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/book_club_list.schema.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - -
- - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/build.properties b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/build.properties deleted file mode 100644 index 3113ded43..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# $Id: build.properties 1756 2010-05-10 08:54:06Z francois $ -# -# This is a project-specific build.properties file. The properties -# in this file override anything set in Propel's top-level build.properties -# file when *this* project is being built. -# -# See top-level build.properties-sample for explanation of configuration -# options. -# -# Because this file is included before the top-level build.properties file, -# you cannot refer to any properties set therein. - -propel.project = bookstore-packaged -propel.database = sqlite -propel.database.url = sqlite://localhost/./test/@DB@.db -# propel.database.createUrl = (doesn't aply for SQLite, since db is auto-created) - -propel.targetPackage = bookstore-packaged -propel.packageObjectModel = true \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/external/author.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/external/author.schema.xml deleted file mode 100644 index 14ce34fba..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/external/author.schema.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/log.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/log.schema.xml deleted file mode 100644 index 96590489c..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/log.schema.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/media.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/media.schema.xml deleted file mode 100644 index 0aa3a2f9b..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/media.schema.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/publisher.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/publisher.schema.xml deleted file mode 100644 index 9f6408210..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/publisher.schema.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/review.schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/review.schema.xml deleted file mode 100644 index f486c8014..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/review.schema.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/runtime-conf.xml b/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/runtime-conf.xml deleted file mode 100644 index be7a2bd42..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore-packaged/runtime-conf.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - propel-bookstore-packaged - 7 - - - - - - - sqlite - - - sqlite - localhost - ./bookstore.db - - - - - - - sqlite - - - sqlite - localhost - ./bookstore-log.db - - - - - - - \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-aggregate-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-aggregate-schema.xml deleted file mode 100644 index 8ad697d03..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-aggregate-schema.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - -
- - - - - - - -
- - - - - - - - -
- - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-auto-add-pk-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-auto-add-pk-schema.xml deleted file mode 100644 index 881b4d536..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-auto-add-pk-schema.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - -
- - - - - -
- - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-concrete-inheritance-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-concrete-inheritance-schema.xml deleted file mode 100644 index e54760333..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-concrete-inheritance-schema.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - -
- - - - -
- - - - - - -
- - - - - - - -
- - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-nested-set-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-nested-set-schema.xml deleted file mode 100644 index c89acd437..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-nested-set-schema.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - -
- - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-schema.xml deleted file mode 100644 index 191b54bd1..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-schema.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sluggable-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sluggable-schema.xml deleted file mode 100644 index 29f962670..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sluggable-schema.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - -
- - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-soft-delete-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-soft-delete-schema.xml deleted file mode 100644 index 3b9f464bf..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-soft-delete-schema.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - -
- - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sortable-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sortable-schema.xml deleted file mode 100644 index 1f08c7172..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-sortable-schema.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - -
- - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-timestampable-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-timestampable-schema.xml deleted file mode 100644 index 850466305..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/behavior-timestampable-schema.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - -
- - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/build.properties b/airtime_mvc/library/propel/test/fixtures/bookstore/build.properties deleted file mode 100644 index 1981cc4b6..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/build.properties +++ /dev/null @@ -1,35 +0,0 @@ -# $Id: build.properties 1688 2010-04-19 20:23:27Z francois $ -# -# This is a project-specific build.properties file. The properties -# in this file override anything set in Propel's top-level build.properties -# file when *this* project is being built. -# -# See top-level build.properties-sample for explanation of configuration -# options. -# -# Because this file is included before the top-level build.properties file, -# you cannot refer to any properties set therein. - -propel.project = bookstore -propel.database = mysql -propel.database.url = mysql:dbname=test -propel.mysqlTableType = InnoDB -propel.disableIdentifierQuoting=true - -# For MySQL or Oracle, you also need to specify username & password -#propel.database.user = [db username] -#propel.database.password = [db password] - -# Note that if you do not wish to specify the database (e.g. if you -# are using multiple databses) you can use the @DB@ token which -# will be replaced with a database at runtime. -# E.g.: propel.database.url = sqlite://localhost/./test/@DB@.db -# This will work for the datadump and the insert-sql tasks. - -# propel.database.createUrl = (doesn't apply for SQLite, since db is auto-created) - -propel.targetPackage = bookstore - -# We need to test behavior hooks -propel.behavior.test_all_hooks.class = ../test.tools.helpers.bookstore.behavior.Testallhooksbehavior -propel.behavior.do_nothing.class = ../test.tools.helpers.bookstore.behavior.DonothingBehavior \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/cms-schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/cms-schema.xml deleted file mode 100644 index bf85a0df0..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/cms-schema.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - -
- - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/runtime-conf.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/runtime-conf.xml deleted file mode 100644 index e38b7bf9f..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/runtime-conf.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - propel-bookstore - propel.log - 7 - - - - - - - - mysql - - - DebugPDO - mysql:dbname=test - - - - - - - - - - - - - utf8 - - - - - - - mysql - - DebugPDO - mysql:dbname=test - - - - - - - - - utf8 - - - - - - mysql - - DebugPDO - mysql:dbname=test - - - - - - - - - utf8 - - - - - - - diff --git a/airtime_mvc/library/propel/test/fixtures/bookstore/schema.xml b/airtime_mvc/library/propel/test/fixtures/bookstore/schema.xml deleted file mode 100644 index c55066ceb..000000000 --- a/airtime_mvc/library/propel/test/fixtures/bookstore/schema.xml +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - -
- - - - - - -
- - - - - - - - - - -
- - - - - - -
- - - - - - - - - - -
- - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - -
- - - - - - - - -
- - - - -
- - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - -
- - - - -
- - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/namespaced/build.properties b/airtime_mvc/library/propel/test/fixtures/namespaced/build.properties deleted file mode 100644 index 9dc98b564..000000000 --- a/airtime_mvc/library/propel/test/fixtures/namespaced/build.properties +++ /dev/null @@ -1,31 +0,0 @@ -# $Id: build.properties 1688 2010-04-19 20:23:27Z francois $ -# -# This is a project-specific build.properties file. The properties -# in this file override anything set in Propel's top-level build.properties -# file when *this* project is being built. -# -# See top-level build.properties-sample for explanation of configuration -# options. -# -# Because this file is included before the top-level build.properties file, -# you cannot refer to any properties set therein. - -propel.project = bookstore_namespaced -propel.database = mysql -propel.database.url = mysql:dbname=test -propel.mysqlTableType = InnoDB -propel.disableIdentifierQuoting=true - -# For MySQL or Oracle, you also need to specify username & password -#propel.database.user = [db username] -#propel.database.password = [db password] - -# Note that if you do not wish to specify the database (e.g. if you -# are using multiple databses) you can use the @DB@ token which -# will be replaced with a database at runtime. -# E.g.: propel.database.url = sqlite://localhost/./test/@DB@.db -# This will work for the datadump and the insert-sql tasks. - -# propel.database.createUrl = (doesn't apply for SQLite, since db is auto-created) - -propel.targetPackage = bookstore \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/fixtures/namespaced/runtime-conf.xml b/airtime_mvc/library/propel/test/fixtures/namespaced/runtime-conf.xml deleted file mode 100644 index ccc5a5c87..000000000 --- a/airtime_mvc/library/propel/test/fixtures/namespaced/runtime-conf.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - propel-bookstore - propel.log - 7 - - - - - - - - mysql - - - DebugPDO - mysql:dbname=test - - - - - - - - - - - - - utf8 - - - - - - - - diff --git a/airtime_mvc/library/propel/test/fixtures/namespaced/schema.xml b/airtime_mvc/library/propel/test/fixtures/namespaced/schema.xml deleted file mode 100644 index 0951482aa..000000000 --- a/airtime_mvc/library/propel/test/fixtures/namespaced/schema.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - -
- - - - - - - - - - -
- - - - - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/nestedset/build.properties b/airtime_mvc/library/propel/test/fixtures/nestedset/build.properties deleted file mode 100644 index 7105e18ab..000000000 --- a/airtime_mvc/library/propel/test/fixtures/nestedset/build.properties +++ /dev/null @@ -1,35 +0,0 @@ -# $Id: build.properties 1260 2009-10-26 20:43:51Z francois $ -# -# This is a project-specific build.properties file. The properties -# in this file override anything set in Propel's top-level build.properties -# file when *this* project is being built. -# -# See top-level build.properties-sample for explanation of configuration -# options. -# -# Because this file is included before the top-level build.properties file, -# you cannot refer to any properties set therein. - -propel.project = nestedset -propel.database = sqlite -propel.database.url = sqlite:/var/tmp/nestedset.db -# For MySQL or Oracle, you also need to specify username & password -# propel.database.user = [db username] -# propel.database.password = [db password] - -# Note that if you do not wish to specify the database (e.g. if you -# are using multiple databses) you can use the @DB@ token which -# will be replaced with a database at runtime. -# E.g.: propel.database.url = sqlite://localhost/./test/@DB@.db -# This will work for the datadump and the insert-sql tasks. - -# propel.database.createUrl = (doesn't aply for SQLite, since db is auto-created) - -propel.targetPackage = nestedset - -# The unit tests need to test this stuff -propel.addGenericAccessors = true -propel.addGenericMutators = true - -# Use the new PHP 5.2 DateTime class -propel.useDateTimeClass = true diff --git a/airtime_mvc/library/propel/test/fixtures/nestedset/nestedset-schema.xml b/airtime_mvc/library/propel/test/fixtures/nestedset/nestedset-schema.xml deleted file mode 100644 index 9a49d5103..000000000 --- a/airtime_mvc/library/propel/test/fixtures/nestedset/nestedset-schema.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - -
-
diff --git a/airtime_mvc/library/propel/test/fixtures/nestedset/runtime-conf.xml b/airtime_mvc/library/propel/test/fixtures/nestedset/runtime-conf.xml deleted file mode 100644 index 8cc8fca13..000000000 --- a/airtime_mvc/library/propel/test/fixtures/nestedset/runtime-conf.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - propel-nestedset - 7 - - - - - - - sqlite - - - sqlite - sqlite:/var/tmp/nestedset.db - - - - - - - diff --git a/airtime_mvc/library/propel/test/fixtures/treetest/build.properties b/airtime_mvc/library/propel/test/fixtures/treetest/build.properties deleted file mode 100644 index eca0fdfcf..000000000 --- a/airtime_mvc/library/propel/test/fixtures/treetest/build.properties +++ /dev/null @@ -1,26 +0,0 @@ -# $Id: build.properties 1260 2009-10-26 20:43:51Z francois $ -# -# This is a project-specific build.properties file. The properties -# in this file override anything set in Propel's top-level build.properties -# file when *this* project is being built. -# -# See top-level build.properties-sample for explanation of configuration -# options. -# -# Because this file is included before the top-level build.properties file, -# you cannot refer to any properties set therein. - -propel.targetPackage = treetest -propel.project = treetest - -propel.database = sqlite -propel.database.url = sqlite:/var/tmp/treetest.db - -#propel.database = mysql -#propel.database.url = mysql://localhost/test - -#propel.database = codebase -#propel.database.url = odbc://localhost/Driver=CodeBaseOdbcStand;DBQ=test;?adapter=CodeBase - - - diff --git a/airtime_mvc/library/propel/test/fixtures/treetest/runtime-conf.xml b/airtime_mvc/library/propel/test/fixtures/treetest/runtime-conf.xml deleted file mode 100644 index c20f28ae4..000000000 --- a/airtime_mvc/library/propel/test/fixtures/treetest/runtime-conf.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - propel-treetest - 7 - - - - - - - sqlite - - - sqlite - sqlite:/var/tmp/treetest.db - - - - - - - diff --git a/airtime_mvc/library/propel/test/fixtures/treetest/treetest-schema.xml b/airtime_mvc/library/propel/test/fixtures/treetest/treetest-schema.xml deleted file mode 100644 index a2f11e889..000000000 --- a/airtime_mvc/library/propel/test/fixtures/treetest/treetest-schema.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - -
- -
diff --git a/airtime_mvc/library/propel/test/fixtures/unique-column/column-schema.xml b/airtime_mvc/library/propel/test/fixtures/unique-column/column-schema.xml deleted file mode 100644 index 6c0dcf725..000000000 --- a/airtime_mvc/library/propel/test/fixtures/unique-column/column-schema.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - -
-
diff --git a/airtime_mvc/library/propel/test/fixtures/unique-column/table-schema.xml b/airtime_mvc/library/propel/test/fixtures/unique-column/table-schema.xml deleted file mode 100644 index 0fb6b26f2..000000000 --- a/airtime_mvc/library/propel/test/fixtures/unique-column/table-schema.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - -
- - - - -
-
diff --git a/airtime_mvc/library/propel/test/speed.php b/airtime_mvc/library/propel/test/speed.php deleted file mode 100644 index c013f18f5..000000000 --- a/airtime_mvc/library/propel/test/speed.php +++ /dev/null @@ -1,401 +0,0 @@ -iterations = $iterations; - } - - public function run() - { - $timers = array(); - fwrite(STDOUT, "Running scenario"); - // perform tests - for ($i=0; $i < $this->iterations; $i++) { - fwrite(STDOUT, '.'); - $this->setUp(); - $t = microtime(true); - $this->testSpeed(); - $timers[]= microtime(true) - $t; - $this->tearDown(); - } - fwrite(STDOUT, " done\n"); - // sort tests - sort($timers); - - // eliminate first and last - array_shift($timers); - array_pop($timers); - - return array_sum($timers) / count($timers); - } - - protected function emptyTables() - { - $res1 = AuthorPeer::doDeleteAll(); - $res2 = PublisherPeer::doDeleteAll(); - $res3 = AuthorPeer::doDeleteAll(); - $res4 = ReviewPeer::doDeleteAll(); - $res5 = MediaPeer::doDeleteAll(); - $res6 = BookClubListPeer::doDeleteAll(); - $res7 = BookListRelPeer::doDeleteAll(); - } - - public function setUp() - { - $this->con = Propel::getConnection(BookPeer::DATABASE_NAME); - $this->con->beginTransaction(); - $this->emptyTables(); - } - - public function tearDown() - { - $this->emptyTables(); - $this->con->commit(); - } - - public function testSpeed() - { - // Add publisher records - // --------------------- - - $scholastic = new Publisher(); - $scholastic->setName("Scholastic"); - // do not save, will do later to test cascade - - $morrow = new Publisher(); - $morrow->setName("William Morrow"); - $morrow->save(); - $morrow_id = $morrow->getId(); - - $penguin = new Publisher(); - $penguin->setName("Penguin"); - $penguin->save(); - $penguin_id = $penguin->getId(); - - $vintage = new Publisher(); - $vintage->setName("Vintage"); - $vintage->save(); - $vintage_id = $vintage->getId(); - - // Add author records - // ------------------ - - $rowling = new Author(); - $rowling->setFirstName("J.K."); - $rowling->setLastName("Rowling"); - // no save() - - $stephenson = new Author(); - $stephenson->setFirstName("Neal"); - $stephenson->setLastName("Stephenson"); - $stephenson->save(); - $stephenson_id = $stephenson->getId(); - - $byron = new Author(); - $byron->setFirstName("George"); - $byron->setLastName("Byron"); - $byron->save(); - $byron_id = $byron->getId(); - - $grass = new Author(); - $grass->setFirstName("Gunter"); - $grass->setLastName("Grass"); - $grass->save(); - $grass_id = $grass->getId(); - - // Add book records - // ---------------- - - $phoenix = new Book(); - $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); - $phoenix->setISBN("043935806X"); - - // cascading save (Harry Potter) - $phoenix->setAuthor($rowling); - $phoenix->setPublisher($scholastic); - $phoenix->save(); - $phoenix_id = $phoenix->getId(); - - $qs = new Book(); - $qs->setISBN("0380977427"); - $qs->setTitle("Quicksilver"); - $qs->setAuthor($stephenson); - $qs->setPublisher($morrow); - $qs->save(); - $qs_id = $qs->getId(); - - $dj = new Book(); - $dj->setISBN("0140422161"); - $dj->setTitle("Don Juan"); - $dj->setAuthor($byron); - $dj->setPublisher($penguin); - $dj->save(); - $dj_id = $qs->getId(); - - $td = new Book(); - $td->setISBN("067972575X"); - $td->setTitle("The Tin Drum"); - $td->setAuthor($grass); - $td->setPublisher($vintage); - $td->save(); - $td_id = $td->getId(); - - // Add review records - // ------------------ - - $r1 = new Review(); - $r1->setBook($phoenix); - $r1->setReviewedBy("Washington Post"); - $r1->setRecommended(true); - $r1->setReviewDate(time()); - $r1->save(); - $r1_id = $r1->getId(); - - $r2 = new Review(); - $r2->setBook($phoenix); - $r2->setReviewedBy("New York Times"); - $r2->setRecommended(false); - $r2->setReviewDate(time()); - $r2->save(); - $r2_id = $r2->getId(); - - // Perform a "complex" search - // -------------------------- - - $results = BookQuery::create() - ->filterByTitle('Harry%') - ->find(); - - $results = BookQuery::create() - ->where('Book.ISBN IN ?', array("0380977427", "0140422161")) - ->find(); - - // Perform a "limit" search - // ------------------------ - - $results = BookQuery::create() - ->limit(2) - ->offset(1) - ->orderByTitle() - ->find(); - - // Perform a lookup & update! - // -------------------------- - - $qs_lookup = BookQuery::create()->findPk($qs_id); - $new_title = "Quicksilver (".crc32(uniqid(rand())).")"; - $qs_lookup->setTitle($new_title); - $qs_lookup->save(); - - $qs_lookup2 = BookQuery::create()->findPk($qs_id); - - // Test some basic DATE / TIME stuff - // --------------------------------- - - // that's the control timestamp. - $control = strtotime('2004-02-29 00:00:00'); - - // should be two in the db - $r = ReviewQuery::create()->findOne(); - $r_id = $r->getId(); - $r->setReviewDate($control); - $r->save(); - - $r2 = ReviewQuery::create()->findPk($r_id); - - // Testing the DATE/TIME columns - // ----------------------------- - - // that's the control timestamp. - $control = strtotime('2004-02-29 00:00:00'); - - // should be two in the db - $r = ReviewQuery::create()->findOne(); - $r_id = $r->getId(); - $r->setReviewDate($control); - $r->save(); - - $r2 = ReviewQuery::create()->findPk($r_id); - - // Testing the column validators - // ----------------------------- - - $bk1 = new Book(); - $bk1->setTitle("12345"); // min length is 10 - $ret = $bk1->validate(); - - // Unique validator - $bk2 = new Book(); - $bk2->setTitle("Don Juan"); - $ret = $bk2->validate(); - - // Now trying some more complex validation. - $auth1 = new Author(); - $auth1->setFirstName("Hans"); - // last name required; will fail - - $bk1->setAuthor($auth1); - - $rev1 = new Review(); - $rev1->setReviewDate("08/09/2001"); - // will fail: reviewed_by column required - - $bk1->addReview($rev1); - - $ret2 = $bk1->validate(); - - $bk2 = new Book(); - $bk2->setTitle("12345678901"); // passes - - $auth2 = new Author(); - $auth2->setLastName("Blah"); //passes - $auth2->setEmail("some@body.com"); //passes - $auth2->setAge(50); //passes - $bk2->setAuthor($auth2); - - $rev2 = new Review(); - $rev2->setReviewedBy("Me!"); // passes - $rev2->setStatus("new"); // passes - $bk2->addReview($rev2); - - $ret3 = $bk2->validate(); - - // Testing doCount() functionality - // ------------------------------- - - $count = BookQuery::create()->count(); - - // Testing many-to-many relationships - // ---------------------------------- - - // init book club list 1 with 2 books - - $blc1 = new BookClubList(); - $blc1->setGroupLeader("Crazyleggs"); - $blc1->setTheme("Happiness"); - - $brel1 = new BookListRel(); - $brel1->setBook($phoenix); - - $brel2 = new BookListRel(); - $brel2->setBook($dj); - - $blc1->addBookListRel($brel1); - $blc1->addBookListRel($brel2); - - $blc1->save(); - - // init book club list 2 with 1 book - - $blc2 = new BookClubList(); - $blc2->setGroupLeader("John Foo"); - $blc2->setTheme("Default"); - - $brel3 = new BookListRel(); - $brel3->setBook($phoenix); - - $blc2->addBookListRel($brel3); - - $blc2->save(); - - // re-fetch books and lists from db to be sure that nothing is cached - - $phoenix = BookQuery::create() - ->filterById($phoenix->getId()) - ->findOne(); - - $blc1 = BookClubListQuery::create() - ->filterById($blc1->getId()) - ->findOne(); - - $blc2 = BookClubListQuery::create() - ->filterbyId($blc2->getId()) - ->findOne(); - - $relCount = $phoenix->countBookListRels(); - - $relCount = $blc1->countBookListRels(); - - $relCount = $blc2->countBookListRels(); - - // Removing books that were just created - // ------------------------------------- - - $hp = BookQuery::create()->findPk($phoenix_id); - $c = new Criteria(); - $c->add(BookPeer::ID, $hp->getId()); - // The only way for cascading to work currently - // is to specify the author_id and publisher_id (i.e. the fkeys - // have to be in the criteria). - $c->add(AuthorPeer::ID, $hp->getId()); - $c->add(PublisherPeer::ID, $hp->getId()); - $c->setSingleRecord(true); - BookPeer::doDelete($c); - - // Attempting to delete books by complex criteria - BookQuery::create() - ->filterByISBN("043935806X") - ->orWhere('Book.ISBN = ?', "0380977427") - ->orWhere('Book.ISBN = ?', "0140422161") - ->delete(); - - $td->delete(); - - AuthorQuery::create()->filterById($stephenson_id)->delete(); - - AuthorQuery::create()->filterById($byron_id)->delete(); - - $grass->delete(); - - PublisherQuery::create()->filterById($morrow_id)->delete(); - - PublisherQuery::create()->filterById($penguin_id)->delete(); - - $vintage->delete(); - - // These have to be deleted manually also since we have onDelete - // set to SETNULL in the foreign keys in book. Is this correct? - $rowling->delete(); - - $scholastic->delete(); - - $blc1->delete(); - - $blc2->delete(); - } -} - -$test = new PropelSpeedTest(100); -echo "Test speed: {$test->run()} ({$test->iterations} iterations)\n"; diff --git a/airtime_mvc/library/propel/test/test.xml b/airtime_mvc/library/propel/test/test.xml deleted file mode 100644 index e97215e7f..000000000 --- a/airtime_mvc/library/propel/test/test.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ------------------------------------------------- - +++++ Running Propel unit tests - ------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/AutoAddPkBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/AutoAddPkBehaviorTest.php deleted file mode 100644 index a59f84575..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/AutoAddPkBehaviorTest.php +++ /dev/null @@ -1,70 +0,0 @@ -assertEquals(count($table6->getColumns()), 2, 'auto_add_pk adds one column by default'); - $pks = $table6->getPrimaryKeys(); - $this->assertEquals(count($pks), 1, 'auto_add_pk adds a simple primary key by default'); - $pk = array_pop($pks); - $this->assertEquals($pk->getName(), 'ID', 'auto_add_pk adds an id column by default'); - $this->assertEquals($pk->getType(), 'INTEGER', 'auto_add_pk adds an integer column by default'); - $this->assertTrue($pk->isPrimaryKey(), 'auto_add_pk adds a primary key column by default'); - $this->assertTrue($table6->isUseIdGenerator(), 'auto_add_pk adds an autoIncrement column by default'); - } - - public function testNoTrigger() - { - $table7 = Table7Peer::getTableMap(); - $this->assertEquals(count($table7->getColumns()), 2, 'auto_add_pk does not add a column when the table already has a primary key'); - $this->assertFalse(method_exists('Table7', 'getId'), 'auto_add_pk does not add an id column when the table already has a primary key'); - $pks = $table7->getPrimaryKeys(); - $pk = array_pop($pks); - $this->assertEquals($pk->getName(), 'FOO', 'auto_add_pk does not change an existing primary key'); - } - - public function testParameters() - { - $table8 = Table8Peer::getTableMap(); - $this->assertEquals(count($table8->getColumns()), 3, 'auto_add_pk adds one column with custom parameters'); - $pks = $table8->getPrimaryKeys(); - $pk = array_pop($pks); - $this->assertEquals($pk->getName(), 'IDENTIFIER', 'auto_add_pk accepts customization of pk column name'); - $this->assertEquals($pk->getType(), 'BIGINT', 'auto_add_pk accepts customization of pk column type'); - $this->assertTrue($pk->isPrimaryKey(), 'auto_add_pk adds a primary key column with custom parameters'); - $this->assertFalse($table8->isUseIdGenerator(), 'auto_add_pk accepts customization of pk column autoIncrement'); - } - - public function testForeignKey() - { - $t6 = new Table6(); - $t6->setTitle('foo'); - $t6->save(); - $t8 = new Table8(); - $t8->setIdentifier(1); - $t8->setTable6($t6); - $t8->save(); - $this->assertEquals($t8->getFooId(), $t6->getId(), 'Auto added pkeys can be used in relations'); - $t8->delete(); - $t6->delete(); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/ObjectBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/ObjectBehaviorTest.php deleted file mode 100644 index f42c8e9c2..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/ObjectBehaviorTest.php +++ /dev/null @@ -1,152 +0,0 @@ -assertEquals($t->customAttribute, 1, 'objectAttributes hook is called when adding attributes'); - } - - public function testPreSave() - { - $t = new Table3(); - $t->preSave = 0; - $t->save(); - $this->assertEquals($t->preSave, 1, 'preSave hook is called on object insertion'); - $this->assertEquals($t->preSaveBuilder, 'PHP5ObjectBuilder', 'preSave hook is called with the object builder as parameter'); - $this->assertFalse($t->preSaveIsAfterSave, 'preSave hook is called before save'); - $t->preSave = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->preSave, 1, 'preSave hook is called on object modification'); - } - - public function testPostSave() - { - $t = new Table3(); - $t->postSave = 0; - $t->save(); - $this->assertEquals($t->postSave, 1, 'postSave hook is called on object insertion'); - $this->assertEquals($t->postSaveBuilder, 'PHP5ObjectBuilder', 'postSave hook is called with the object builder as parameter'); - $this->assertTrue($t->postSaveIsAfterSave, 'postSave hook is called after save'); - $t->postSave = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->postSave, 1, 'postSave hook is called on object modification'); - } - - public function testPreInsert() - { - $t = new Table3(); - $t->preInsert = 0; - $t->save(); - $this->assertEquals($t->preInsert, 1, 'preInsert hook is called on object insertion'); - $this->assertEquals($t->preInsertBuilder, 'PHP5ObjectBuilder', 'preInsert hook is called with the object builder as parameter'); - $this->assertFalse($t->preInsertIsAfterSave, 'preInsert hook is called before save'); - $t->preInsert = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->preInsert, 0, 'preInsert hook is not called on object modification'); - } - - public function testPostInsert() - { - $t = new Table3(); - $t->postInsert = 0; - $t->save(); - $this->assertEquals($t->postInsert, 1, 'postInsert hook is called on object insertion'); - $this->assertEquals($t->postInsertBuilder, 'PHP5ObjectBuilder', 'postInsert hook is called with the object builder as parameter'); - $this->assertTrue($t->postInsertIsAfterSave, 'postInsert hook is called after save'); - $t->postInsert = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->postInsert, 0, 'postInsert hook is not called on object modification'); - } - - public function testPreUpdate() - { - $t = new Table3(); - $t->preUpdate = 0; - $t->save(); - $this->assertEquals($t->preUpdate, 0, 'preUpdate hook is not called on object insertion'); - $t->preUpdate = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->preUpdate, 1, 'preUpdate hook is called on object modification'); - $this->assertEquals($t->preUpdateBuilder, 'PHP5ObjectBuilder', 'preUpdate hook is called with the object builder as parameter'); - $this->assertFalse($t->preUpdateIsAfterSave, 'preUpdate hook is called before save'); - } - - public function testPostUpdate() - { - $t = new Table3(); - $t->postUpdate = 0; - $t->save(); - $this->assertEquals($t->postUpdate, 0, 'postUpdate hook is not called on object insertion'); - $t->postUpdate = 0; - $t->setTitle('foo'); - $t->save(); - $this->assertEquals($t->postUpdate, 1, 'postUpdate hook is called on object modification'); - $this->assertEquals($t->postUpdateBuilder, 'PHP5ObjectBuilder', 'postUpdate hook is called with the object builder as parameter'); - $this->assertTrue($t->postUpdateIsAfterSave, 'postUpdate hook is called after save'); - } - - public function testPreDelete() - { - $t = new Table3(); - $t->save(); - $this->preDelete = 0; - $t->delete(); - $this->assertEquals($t->preDelete, 1, 'preDelete hook is called on object deletion'); - $this->assertEquals($t->preDeleteBuilder, 'PHP5ObjectBuilder', 'preDelete hook is called with the object builder as parameter'); - $this->assertTrue($t->preDeleteIsBeforeDelete, 'preDelete hook is called before deletion'); - } - - public function testPostDelete() - { - $t = new Table3(); - $t->save(); - $this->postDelete = 0; - $t->delete(); - $this->assertEquals($t->postDelete, 1, 'postDelete hook is called on object deletion'); - $this->assertEquals($t->postDeleteBuilder, 'PHP5ObjectBuilder', 'postDelete hook is called with the object builder as parameter'); - $this->assertFalse($t->postDeleteIsBeforeDelete, 'postDelete hook is called before deletion'); - } - - public function testObjectMethods() - { - $t = new Table3(); - $this->assertTrue(method_exists($t, 'hello'), 'objectMethods hook is called when adding methods'); - $this->assertEquals($t->hello(), 'PHP5ObjectBuilder', 'objectMethods hook is called with the object builder as parameter'); - } - - public function testObjectCall() - { - $t = new Table3(); - $this->assertEquals('bar', $t->foo(), 'objectCall hook is called when building the magic __call()'); - } - - public function testObjectFilter() - { - $t = new Table3(); - $this->assertTrue(class_exists('testObjectFilter'), 'objectFilter hook allows complete manipulation of the generated script'); - $this->assertEquals(testObjectFilter::FOO, 'PHP5ObjectBuilder', 'objectFilter hook is called with the object builder as parameter'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/PeerBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/PeerBehaviorTest.php deleted file mode 100644 index 5e968f2c4..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/PeerBehaviorTest.php +++ /dev/null @@ -1,61 +0,0 @@ -assertEquals(Table3Peer::$customStaticAttribute, 1, 'staticAttributes hook is called when adding attributes'); - $this->assertEquals(Table3Peer::$staticAttributeBuilder, 'PHP5PeerBuilder', 'staticAttributes hook is called with the peer builder as parameter'); - } - - public function testStaticMethods() - { - $this->assertTrue(method_exists('Table3Peer', 'hello'), 'staticMethods hook is called when adding methods'); - $this->assertEquals(Table3Peer::hello(), 'PHP5PeerBuilder', 'staticMethods hook is called with the peer builder as parameter'); - } - - public function testPreSelect() - { - $con = Propel::getConnection(Table3Peer::DATABASE_NAME, Propel::CONNECTION_READ); - $con->preSelect = 0; - Table3Peer::doSelect(new Criteria, $con); - $this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelect()'); - $con->preSelect = 0; - Table3Peer::doSelectOne(new Criteria, $con); - $this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelectOne()'); - $con->preSelect = 0; - Table3Peer::doCount(new Criteria, $con); - $this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doCount()'); - $con->preSelect = 0; - Table3Peer::doSelectStmt(new Criteria, $con); - $this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelectStmt()'); - // and for the doSelectJoin and doCountJoin methods, well just believe my word - - $con->preSelect = 0; - Table3Peer::doSelect(new Criteria, $con); - $this->assertEquals($con->preSelect, 'PHP5PeerBuilder', 'preSelect hook is called with the peer builder as parameter'); - } - - public function testPeerFilter() - { - Table3Peer::TABLE_NAME; - $this->assertTrue(class_exists('testPeerFilter'), 'peerFilter hook allows complete manipulation of the generated script'); - $this->assertEquals(testPeerFilter::FOO, 'PHP5PeerBuilder', 'peerFilter hook is called with the peer builder as parameter'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/SoftDeleteBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/SoftDeleteBehaviorTest.php deleted file mode 100644 index 2f3fecb97..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/SoftDeleteBehaviorTest.php +++ /dev/null @@ -1,360 +0,0 @@ -assertEquals(count($table2->getColumns()), 3, 'SoftDelete adds one columns by default'); - $this->assertTrue(method_exists('Table4', 'getDeletedAt'), 'SoftDelete adds an updated_at column by default'); - $table1 = Table5Peer::getTableMap(); - $this->assertEquals(count($table1->getColumns()), 3, 'SoftDelete does not add a column when it already exists'); - $this->assertTrue(method_exists('Table5', 'getDeletedOn'), 'SoftDelete allows customization of deleted_column name'); - } - - public function testStaticSoftDeleteStatus() - { - $this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'The static soft delete is enabled by default'); - Table4Peer::disableSoftDelete(); - $this->assertFalse(Table4Peer::isSoftDeleteEnabled(), 'disableSoftDelete() disables the static soft delete'); - Table4Peer::enableSoftDelete(); - $this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'enableSoftDelete() enables the static soft delete'); - } - - public function testInstancePoolingAndSoftDelete() - { - Table4Peer::doForceDeleteAll($this->con); - $t = new Table4(); - $t->save($this->con); - Table4Peer::enableSoftDelete(); - $t->delete($this->con); - $t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con); - $this->assertNull($t2, 'An object is removed from the instance pool on soft deletion'); - Table4Peer::disableSoftDelete(); - $t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con); - $this->assertNotNull($t2); - Table4Peer::enableSoftDelete(); - $t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con); - $this->assertNull($t2, 'A soft deleted object is removed from the instance pool when the soft delete behavior is enabled'); - } - - public function testStaticDoForceDelete() - { - $t1 = new Table4(); - $t1->save(); - Table4Peer::doForceDelete($t1); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doForceDelete() actually deletes records'); - } - - public function testStaticDoSoftDelete() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - $t3 = new Table4(); - $t3->save(); - // softDelete with a criteria - $c = new Criteria(); - $c->add(Table4Peer::ID, $t1->getId()); - Table4Peer::doSoftDelete($c); - Table4Peer::disableSoftDelete(); - $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); - // softDelete with a value - Table4Peer::doSoftDelete(array($t2->getId())); - Table4Peer::disableSoftDelete(); - $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); - // softDelete with an object - Table4Peer::doSoftDelete($t3); - Table4Peer::disableSoftDelete(); - $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); - } - - public function testStaticDoDelete() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::disableSoftDelete(); - Table4Peer::doDelete($t1); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doDelete() calls doForceDelete() when soft delete is disabled'); - Table4Peer::enableSoftDelete(); - Table4Peer::doDelete($t2); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doDelete() calls doSoftDelete() when soft delete is enabled'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDelete() calls doSoftDelete() when soft delete is enabled'); - } - - public function testStaticDoForceDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - Table4Peer::doForceDeleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doForceDeleteAll() actually deletes records'); - } - - public function testStaticDoSoftDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::enableSoftDelete(); - Table4Peer::doSoftDeleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doSoftDeleteAll() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doSoftDeleteAll() marks deleted record as deleted'); - } - - public function testStaticDoDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::disableSoftDelete(); - Table4Peer::doDeleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doForceDeleteAll() when soft delete is disabled'); - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::enableSoftDelete(); - Table4Peer::doDeleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doSoftDeleteAll() when soft delete is disabled'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doSoftDeleteAll() when soft delete is disabled'); - } - - public function testSelect() - { - $t = new Table4(); - $t->setDeletedAt(123); - $t->save(); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria), 'rows with a deleted_at date are hidden for select queries'); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Peer::doCount(new Criteria), 'rows with a deleted_at date are visible for select queries once the static soft_delete is enabled'); - $this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'Executing a select query enables the static soft delete again'); - } - - public function testDelete() - { - $t = new Table4(); - $t->save(); - $this->assertNull($t->getDeletedAt(), 'deleted_column is null by default'); - $t->delete(); - $this->assertNotNull($t->getDeletedAt(), 'deleted_column is not null after a soft delete'); - $this->assertEquals(0, Table4Peer::doCount(new Criteria), 'soft deleted rows are hidden for select queries'); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Peer::doCount(new Criteria), 'soft deleted rows are still present in the database'); - } - - public function testDeleteUndeletable() - { - $t = new UndeletableTable4(); - $t->save(); - $t->delete(); - $this->assertNull($t->getDeletedAt(), 'soft_delete is not triggered for objects wit ha preDelete hook returning false'); - $this->assertEquals(1, Table4Peer::doCount(new Criteria), 'soft_delete is not triggered for objects wit ha preDelete hook returning false'); - } - - public function testUnDelete() - { - $t = new Table4(); - $t->save(); - $t->delete(); - $t->undelete(); - $this->assertNull($t->getDeletedAt(), 'deleted_column is null again after an undelete'); - $this->assertEquals(1, Table4Peer::doCount(new Criteria), 'undeleted rows are visible for select queries'); - } - - public function testForceDelete() - { - $t = new Table4(); - $t->save(); - $t->forceDelete(); - $this->assertTrue($t->isDeleted(), 'forceDelete() actually deletes a row'); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Peer::doCount(new Criteria), 'forced deleted rows are not present in the database'); - } - - public function testQueryIncludeDeleted() - { - $t = new Table4(); - $t->setDeletedAt(123); - $t->save(); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'rows with a deleted_at date are hidden for select queries'); - $this->assertEquals(1, Table4Query::create()->includeDeleted()->count(), 'rows with a deleted_at date are visible for select queries using includeDeleted()'); - } - - public function testQueryForceDelete() - { - $t1 = new Table4(); - $t1->save(); - Table4Query::create()->filterById($t1->getId())->forceDelete(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'forceDelete() actually deletes records'); - } - - public function testQuerySoftDelete() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - $t3 = new Table4(); - $t3->save(); - - Table4Query::create() - ->filterById($t1->getId()) - ->softDelete(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(3, Table4Query::create()->count(), 'softDelete() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(2, Table4Query::create()->count(), 'softDelete() marks deleted record as deleted'); - } - - public function testQueryDelete() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - - Table4Peer::disableSoftDelete(); - Table4Query::create()->filterById($t1->getId())->delete(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Query::create()->count(), 'delete() calls forceDelete() when soft delete is disabled'); - Table4Peer::enableSoftDelete(); - Table4Query::create()->filterById($t2->getId())->delete(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Query::create()->count(), 'delete() calls softDelete() when soft delete is enabled'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'delete() calls softDelete() when soft delete is enabled'); - } - - public function testQueryForceDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - Table4Query::create()->forceDeleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'forceDeleteAll() actually deletes records'); - } - - public function testQuerySoftDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::enableSoftDelete(); - Table4Query::create()->softDelete(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(2, Table4Query::create()->count(), 'softDelete() keeps deleted record in the database'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'softDelete() marks deleted record as deleted'); - } - - public function testQueryDeleteAll() - { - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::disableSoftDelete(); - Table4Query::create()->deleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'deleteAll() calls forceDeleteAll() when soft delete is disabled'); - - $t1 = new Table4(); - $t1->save(); - $t2 = new Table4(); - $t2->save(); - Table4Peer::enableSoftDelete(); - Table4Query::create()->deleteAll(); - Table4Peer::disableSoftDelete(); - $this->assertEquals(2, Table4Query::create()->count(), 'deleteAll() calls softDeleteAll() when soft delete is disabled'); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'deleteAll() calls softDeleteAll() when soft delete is disabled'); - } - - public function testQuerySelect() - { - $t = new Table4(); - $t->setDeletedAt(123); - $t->save(); - Table4Peer::enableSoftDelete(); - $this->assertEquals(0, Table4Query::create()->count(), 'rows with a deleted_at date are hidden for select queries'); - Table4Peer::disableSoftDelete(); - $this->assertEquals(1, Table4Query::create()->count(), 'rows with a deleted_at date are visible for select queries once the static soft_delete is enabled'); - $this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'Executing a select query enables the static soft delete again'); - } - - public function testCustomization() - { - Table5Peer::disableSoftDelete(); - Table5Peer::doDeleteAll(); - Table5Peer::enableSoftDelete(); - $t = new Table5(); - $t->save(); - $this->assertNull($t->getDeletedOn(), 'deleted_column is null by default'); - $t->delete(); - $this->assertNotNull($t->getDeletedOn(), 'deleted_column is not null after a soft delete'); - $this->assertEquals(0, Table5Peer::doCount(new Criteria), 'soft deleted rows are hidden for select queries'); - Table5Peer::disableSoftDelete(); - $this->assertEquals(1, Table5Peer::doCount(new Criteria), 'soft deleted rows are still present in the database'); - } -} - -class UndeletableTable4 extends Table4 -{ - public function preDelete(PropelPDO $con = null) - { - parent::preDelete($con); - $this->setTitle('foo'); - return false; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/TableBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/TableBehaviorTest.php deleted file mode 100644 index 25e534f7e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/TableBehaviorTest.php +++ /dev/null @@ -1,34 +0,0 @@ -assertTrue($t->hasColumn('test'), 'modifyTable hook is called when building the model structure'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/TimestampableBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/TimestampableBehaviorTest.php deleted file mode 100644 index ba80d64f8..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/TimestampableBehaviorTest.php +++ /dev/null @@ -1,215 +0,0 @@ -assertEquals(count($table2->getColumns()), 4, 'Timestampable adds two columns by default'); - $this->assertTrue(method_exists('Table2', 'getCreatedAt'), 'Timestamplable adds a created_at column by default'); - $this->assertTrue(method_exists('Table2', 'getUpdatedAt'), 'Timestamplable adds an updated_at column by default'); - $table1 = Table1Peer::getTableMap(); - $this->assertEquals(count($table1->getColumns()), 4, 'Timestampable does not add two columns when they already exist'); - $this->assertTrue(method_exists('Table1', 'getCreatedOn'), 'Timestamplable allows customization of create_column name'); - $this->assertTrue(method_exists('Table1', 'getUpdatedOn'), 'Timestamplable allows customization of update_column name'); - } - - public function testPreSave() - { - $t1 = new Table2(); - $this->assertNull($t1->getUpdatedAt()); - $tsave = time(); - $t1->save(); - $this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable sets updated_column to time() on creation'); - sleep(1); - $t1->setTitle('foo'); - $tupdate = time(); - $t1->save(); - $this->assertEquals($t1->getUpdatedAt('U'), $tupdate, 'Timestampable changes updated_column to time() on update'); - } - - public function testPreSaveNoChange() - { - $t1 = new Table2(); - $this->assertNull($t1->getUpdatedAt()); - $tsave = time(); - $t1->save(); - $this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable sets updated_column to time() on creation'); - sleep(1); - $tupdate = time(); - $t1->save(); - $this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable only changes updated_column if the object was modified'); - } - - public function testPreSaveManuallyUpdated() - { - $t1 = new Table2(); - $t1->setUpdatedAt(time() - 10); - $tsave = time(); - $t1->save(); - $this->assertNotEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable does not set updated_column to time() on creation when it is set by the user'); - // tip: if I set it to time()-10 a second time, the object sees that I want to change it to the same value - // and skips the update, therefore the updated_at is not in the list of modified columns, - // and the behavior changes it to the current date... let's say it's an edge case - $t1->setUpdatedAt(time() - 15); - $tupdate = time(); - $t1->save(); - $this->assertNotEquals($t1->getUpdatedAt('U'), $tupdate, 'Timestampable does not change updated_column to time() on update when it is set by the user'); - } - - public function testPreInsert() - { - $t1 = new Table2(); - $this->assertNull($t1->getCreatedAt()); - $tsave = time(); - $t1->save(); - $this->assertEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable sets created_column to time() on creation'); - sleep(1); - $t1->setTitle('foo'); - $tupdate = time(); - $t1->save(); - $this->assertEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable does not update created_column on update'); - } - - public function testPreInsertManuallyUpdated() - { - $t1 = new Table2(); - $t1->setCreatedAt(time() - 10); - $tsave = time(); - $t1->save(); - $this->assertNotEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable does not set created_column to time() on creation when it is set by the user'); - } - - public function testObjectKeepUpdateDateUnchanged() - { - $t1 = new Table2(); - $t1->setUpdatedAt(time() - 10); - $tsave = time(); - $t1->save(); - $this->assertNotEquals($t1->getUpdatedAt('U'), $tsave); - // let's save it a second time; the updated_at should be changed - $t1->setTitle('foo'); - $tsave = time(); - $t1->save(); - $this->assertEquals($t1->getUpdatedAt('U'), $tsave); - - // now let's do this a second time - $t1 = new Table2(); - $t1->setUpdatedAt(time() - 10); - $tsave = time(); - $t1->save(); - $this->assertNotEquals($t1->getUpdatedAt('U'), $tsave); - // let's save it a second time; the updated_at should be changed - $t1->keepUpdateDateUnchanged(); - $t1->setTitle('foo'); - $tsave = time(); - $t1->save(); - $this->assertNotEquals($t1->getUpdatedAt('U'), $tsave, 'keepUpdateDateUnchanged() prevents the behavior from updating the update date'); - - } - - protected function populateUpdatedAt() - { - Table2Query::create()->deleteAll(); - $ts = new PropelObjectCollection(); - $ts->setModel('Table2'); - for ($i=0; $i < 10; $i++) { - $t = new Table2(); - $t->setTitle('UpdatedAt' . $i); - $t->setUpdatedAt(time() - $i * 24 * 60 * 60); - $ts[]= $t; - } - $ts->save(); - } - - protected function populateCreatedAt() - { - Table2Query::create()->deleteAll(); - $ts = new PropelObjectCollection(); - $ts->setModel('Table2'); - for ($i=0; $i < 10; $i++) { - $t = new Table2(); - $t->setTitle('CreatedAt' . $i); - $t->setCreatedAt(time() - $i * 24 * 60 * 60); - $ts[]= $t; - } - $ts->save(); - } - - public function testQueryRecentlyUpdated() - { - $q = Table2Query::create()->recentlyUpdated(); - $this->assertTrue($q instanceof Table2Query, 'recentlyUpdated() returns the current Query object'); - $this->populateUpdatedAt(); - $ts = Table2Query::create()->recentlyUpdated()->count(); - $this->assertEquals(8, $ts, 'recentlyUpdated() returns the elements updated in the last 7 days by default'); - $ts = Table2Query::create()->recentlyUpdated(5)->count(); - $this->assertEquals(6, $ts, 'recentlyUpdated() accepts a number of days as parameter'); - } - - public function testQueryRecentlyCreated() - { - $q = Table2Query::create()->recentlyCreated(); - $this->assertTrue($q instanceof Table2Query, 'recentlyCreated() returns the current Query object'); - $this->populateCreatedAt(); - $ts = Table2Query::create()->recentlyCreated()->count(); - $this->assertEquals(8, $ts, 'recentlyCreated() returns the elements created in the last 7 days by default'); - $ts = Table2Query::create()->recentlyCreated(5)->count(); - $this->assertEquals(6, $ts, 'recentlyCreated() accepts a number of days as parameter'); - } - - public function testQueryLastUpdatedFirst() - { - $q = Table2Query::create()->lastUpdatedFirst(); - $this->assertTrue($q instanceof Table2Query, 'lastUpdatedFirst() returns the current Query object'); - $this->populateUpdatedAt(); - $t = Table2Query::create()->lastUpdatedFirst()->findOne(); - $this->assertEquals('UpdatedAt0', $t->getTitle(), 'lastUpdatedFirst() returns element with most recent update date first'); - } - - public function testQueryFirstUpdatedFirst() - { - $q = Table2Query::create()->firstUpdatedFirst(); - $this->assertTrue($q instanceof Table2Query, 'firstUpdatedFirst() returns the current Query object'); - $this->populateUpdatedAt(); - $t = Table2Query::create()->firstUpdatedFirst()->findOne(); - $this->assertEquals('UpdatedAt9', $t->getTitle(), 'firstUpdatedFirst() returns the element with oldest updated date first'); - } - - public function testQueryLastCreatedFirst() - { - $q = Table2Query::create()->lastCreatedFirst(); - $this->assertTrue($q instanceof Table2Query, 'lastCreatedFirst() returns the current Query object'); - $this->populateCreatedAt(); - $t = Table2Query::create()->lastCreatedFirst()->findOne(); - $this->assertEquals('CreatedAt0', $t->getTitle(), 'lastCreatedFirst() returns element with most recent create date first'); - } - - public function testQueryFirstCreatedFirst() - { - $q = Table2Query::create()->firstCreatedFirst(); - $this->assertTrue($q instanceof Table2Query, 'firstCreatedFirst() returns the current Query object'); - $this->populateCreatedAt(); - $t = Table2Query::create()->firstCreatedFirst()->findOne(); - $this->assertEquals('CreatedAt9', $t->getTitle(), 'firstCreatedFirst() returns the element with oldest create date first'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/aggregate_column/AggregateColumnBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/aggregate_column/AggregateColumnBehaviorTest.php deleted file mode 100644 index 3019727c5..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/aggregate_column/AggregateColumnBehaviorTest.php +++ /dev/null @@ -1,254 +0,0 @@ -assertEquals(count($postTable->getColumns()), 2, 'AggregateColumn adds one column by default'); - $this->assertTrue(method_exists('AggregatePost', 'getNbComments')); - } - - public function testCompute() - { - AggregateCommentQuery::create()->deleteAll($this->con); - AggregatePostQuery::create()->deleteAll($this->con); - $post = new AggregatePost(); - $post->save($this->con); - $this->assertEquals(0, $post->computeNbComments($this->con), 'The compute method returns 0 for objects with no related objects'); - $comment1 = new AggregateComment(); - $comment1->setAggregatePost($post); - $comment1->save($this->con); - $this->assertEquals(1, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects'); - $comment2 = new AggregateComment(); - $comment2->setAggregatePost($post); - $comment2->save($this->con); - $this->assertEquals(2, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects'); - $comment1->delete($this->con); - $this->assertEquals(1, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects'); - } - - public function testUpdate() - { - AggregateCommentQuery::create()->deleteAll($this->con); - AggregatePostQuery::create()->deleteAll($this->con); - $post = new AggregatePost(); - $post->save($this->con); - $comment = new TestableComment(); - $comment->setAggregatePost($post); - $comment->save($this->con); - $this->assertNull($post->getNbComments()); - $post->updateNbComments($this->con); - $this->assertEquals(1, $post->getNbComments(), 'The update method updates the aggregate column'); - $comment->delete($this->con); - $this->assertEquals(1, $post->getNbComments()); - $post->updateNbComments($this->con); - $this->assertEquals(0, $post->getNbComments(), 'The update method updates the aggregate column'); - } - - public function testCreateRelated() - { - AggregateCommentQuery::create()->deleteAll($this->con); - AggregatePostQuery::create()->deleteAll($this->con); - $post = new AggregatePost(); - $post->save($this->con); - $comment1 = new AggregateComment(); - $comment1->save($this->con); - $this->assertNull($post->getNbComments(), 'Adding a new foreign object does not update the aggregate column'); - $comment2 = new AggregateComment(); - $comment2->setAggregatePost($post); - $comment2->save($this->con); - $this->assertEquals(1, $post->getNbComments(), 'Adding a new related object updates the aggregate column'); - $comment3 = new AggregateComment(); - $comment3->setAggregatePost($post); - $comment3->save($this->con); - $this->assertEquals(2, $post->getNbComments(), 'Adding a new related object updates the aggregate column'); - } - - public function testUpdateRelated() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - $item1->setScore(10); - $item1->save($this->con); - $this->assertEquals(17, $poll->getTotalScore(), 'Updating a related object updates the aggregate column'); - } - - public function testDeleteRelated() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - $item1->delete($this->con); - $this->assertEquals(7, $poll->getTotalScore(), 'Deleting a related object updates the aggregate column'); - $item2->delete($this->con); - $this->assertNull($poll->getTotalScore(), 'Deleting a related object updates the aggregate column'); - } - - public function testUpdateRelatedWithQuery() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - AggregateItemQuery::create() - ->update(array('Score' => 4), $this->con); - $this->assertEquals(8, $poll->getTotalScore(), 'Updating related objects with a query updates the aggregate column'); - } - - public function testUpdateRelatedWithQueryUsingAlias() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - AggregateItemQuery::create() - ->setModelAlias('foo', true) - ->update(array('Score' => 4), $this->con); - $this->assertEquals(8, $poll->getTotalScore(), 'Updating related objects with a query using alias updates the aggregate column'); - } - - public function testDeleteRelatedWithQuery() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - AggregateItemQuery::create() - ->deleteAll($this->con); - $this->assertNull($poll->getTotalScore(), 'Deleting related objects with a query updates the aggregate column'); - } - - public function testDeleteRelatedWithQueryUsingAlias() - { - list($poll, $item1, $item2) = $this->populatePoll(); - $this->assertEquals(19, $poll->getTotalScore()); - AggregateItemQuery::create() - ->setModelAlias('foo', true) - ->filterById($item1->getId()) - ->delete($this->con); - $this->assertEquals(7, $poll->getTotalScore(), 'Deleting related objects with a query using alias updates the aggregate column'); - } - - public function testRemoveRelation() - { - AggregateCommentQuery::create()->deleteAll($this->con); - AggregatePostQuery::create()->deleteAll($this->con); - $post = new AggregatePost(); - $post->save($this->con); - $comment1 = new AggregateComment(); - $comment1->setAggregatePost($post); - $comment1->save($this->con); - $comment2 = new AggregateComment(); - $comment2->setAggregatePost($post); - $comment2->save($this->con); - $this->assertEquals(2, $post->getNbComments()); - $comment2->setAggregatePost(null); - $comment2->save($this->con); - $this->assertEquals(1, $post->getNbComments(), 'Removing a relation changes the related object aggregate column'); - } - - public function testReplaceRelation() - { - AggregateCommentQuery::create()->deleteAll($this->con); - AggregatePostQuery::create()->deleteAll($this->con); - $post1 = new AggregatePost(); - $post1->save($this->con); - $post2 = new AggregatePost(); - $post2->save($this->con); - $comment = new AggregateComment(); - $comment->setAggregatePost($post1); - $comment->save($this->con); - $this->assertEquals(1, $post1->getNbComments()); - $this->assertNull($post2->getNbComments()); - $comment->setAggregatePost($post2); - $comment->save($this->con); - $this->assertEquals(0, $post1->getNbComments(), 'Replacing a relation changes the related object aggregate column'); - $this->assertEquals(1, $post2->getNbComments(), 'Replacing a relation changes the related object aggregate column'); - } - - protected function populatePoll() - { - AggregateItemQuery::create()->deleteAll($this->con); - AggregatePollQuery::create()->deleteAll($this->con); - $poll = new AggregatePoll(); - $poll->save($this->con); - $item1 = new AggregateItem(); - $item1->setScore(12); - $item1->setAggregatePoll($poll); - $item1->save($this->con); - $item2 = new AggregateItem(); - $item2->setScore(7); - $item2->setAggregatePoll($poll); - $item2->save($this->con); - return array($poll, $item1, $item2); - } - -} - -class TestableComment extends AggregateComment -{ - // overrides the parent save() to bypass behavior hooks - public function save(PropelPDO $con = null) - { - $con->beginTransaction(); - try { - $affectedRows = $this->doSave($con); - AggregateCommentPeer::addInstanceToPool($this); - $con->commit(); - return $affectedRows; - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - - // overrides the parent delete() to bypass behavior hooks - public function delete(PropelPDO $con = null) - { - $con->beginTransaction(); - try { - TestableAggregateCommentQuery::create() - ->filterByPrimaryKey($this->getPrimaryKey()) - ->delete($con); - $con->commit(); - $this->setDeleted(true); - } catch (PropelException $e) { - $con->rollBack(); - throw $e; - } - } - -} - -class TestableAggregateCommentQuery extends AggregateCommentQuery -{ - public static function create($modelAlias = null, $criteria = null) - { - return new TestableAggregateCommentQuery(); - } - - // overrides the parent basePreDelete() to bypass behavior hooks - protected function basePreDelete(PropelPDO $con) - { - return $this->preDelete($con); - } - - // overrides the parent basePostDelete() to bypass behavior hooks - protected function basePostDelete($affectedRows, PropelPDO $con) - { - return $this->postDelete($affectedRows, $con); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceBehaviorTest.php deleted file mode 100644 index 8c86fa122..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceBehaviorTest.php +++ /dev/null @@ -1,202 +0,0 @@ -getBehaviors(); - $this->assertTrue(array_key_exists('concrete_inheritance_parent', $behaviors), 'modifyTable() gives the parent table the concrete_inheritance_parent behavior'); - $this->assertEquals('descendant_class', $behaviors['concrete_inheritance_parent']['descendant_column'], 'modifyTable() passed the descendent_column parameter to the parent behavior'); - } - - public function testModifyTableAddsParentColumn() - { - $contentColumns = array('id', 'title', 'category_id'); - $article = ConcreteArticlePeer::getTableMap(); - foreach ($contentColumns as $column) { - $this->assertTrue($article->containsColumn($column), 'modifyTable() adds the columns of the parent table'); - } - $quizz = ConcreteQuizzPeer::getTableMap(); - $this->assertEquals(3, count($quizz->getColumns()), 'modifyTable() does not add a column of the parent table if a similar column exists'); - } - - public function testModifyTableCopyDataAddsOneToOneRelationships() - { - $article = ConcreteArticlePeer::getTableMap(); - $this->assertTrue($article->hasRelation('ConcreteContent'), 'modifyTable() adds a relationship to the parent'); - $relation = $article->getRelation('ConcreteContent'); - $this->assertEquals(RelationMap::MANY_TO_ONE, $relation->getType(), 'modifyTable adds a one-to-one relationship'); - $content = ConcreteContentPeer::getTableMap(); - $relation = $content->getRelation('ConcreteArticle'); - $this->assertEquals(RelationMap::ONE_TO_ONE, $relation->getType(), 'modifyTable adds a one-to-one relationship'); - } - - public function testModifyTableNoCopyDataNoParentRelationship() - { - $quizz = ConcreteQuizzPeer::getTableMap(); - $this->assertFalse($quizz->hasRelation('ConcreteContent'), 'modifyTable() does not add a relationship to the parent when copy_data is false'); - } - - public function testModifyTableCopyDataRemovesAutoIncrement() - { - $content = new ConcreteContent(); - $content->save(); - $c = new Criteria; - $c->add(ConcreteArticlePeer::ID, $content->getId()); - try { - ConcreteArticlePeer::doInsert($c); - $this->assertTrue(true, 'modifyTable() removed autoIncrement from copied Primary keys'); - } catch (PropelException $e) { - $this->fail('modifyTable() removed autoIncrement from copied Primary keys'); - } - } - - /** - * @expectedException PropelException - */ - public function testModifyTableNoCopyDataKeepsAutoIncrement() - { - $content = new ConcreteContent(); - $content->save(); - $c = new Criteria; - $c->add(ConcreteQuizzPeer::ID, $content->getId()); - ConcreteQuizzPeer::doInsert($c); - } - - public function testModifyTableAddsForeignKeys() - { - $article = ConcreteArticlePeer::getTableMap(); - $this->assertTrue($article->hasRelation('ConcreteCategory'), 'modifyTable() copies relationships from parent table'); - } - - public function testModifyTableAddsForeignKeysWithoutDuplicates() - { - $article = ConcreteAuthorPeer::getTableMap(); - $this->assertTrue($article->hasRelation('ConcreteNews'), 'modifyTable() copies relationships from parent table and removes hardcoded refPhpName'); - } - - public function testModifyTableAddsValidators() - { - $article = ConcreteArticlePeer::getTableMap(); - $this->assertTrue($article->getColumn('title')->hasValidators(), 'modifyTable() copies validators from parent table'); - } - - // no way to test copying of indices and uniques, except by reverse engineering the db... - - public function testParentObjectClass() - { - $article = new ConcreteArticle(); // to autoload the BaseConcreteArticle class - $r = new ReflectionClass('BaseConcreteArticle'); - $this->assertEquals('ConcreteContent', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Model Object to the parent object class'); - $quizz = new ConcreteQuizz(); // to autoload the BaseConcreteQuizz class - $r = new ReflectionClass('BaseConcreteQuizz'); - $this->assertEquals('ConcreteContent', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Model Object to the parent object class'); - } - - public function testParentQueryClass() - { - $q = new ConcreteArticleQuery(); // to autoload the BaseConcreteArticleQuery class - $r = new ReflectionClass('BaseConcreteArticleQuery'); - $this->assertEquals('ConcreteContentQuery', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Query Object to the parent object class'); - $q = new ConcreteQuizzQuery(); // to autoload the BaseConcreteQuizzQuery class - $r = new ReflectionClass('BaseConcreteQuizzQuery'); - $this->assertEquals('ConcreteContentQuery', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Query Object to the parent object class'); - } - - public function testPreSaveCopyData() - { - ConcreteArticleQuery::create()->deleteAll(); - ConcreteQuizzQuery::create()->deleteAll(); - ConcreteContentQuery::create()->deleteAll(); - ConcreteCategoryQuery::create()->deleteAll(); - $category = new ConcreteCategory(); - $category->setName('main'); - $article = new ConcreteArticle(); - $article->setConcreteCategory($category); - $article->save(); - $this->assertNotNull($article->getId()); - $this->assertNotNull($category->getId()); - $content = ConcreteContentQuery::create()->findPk($article->getId()); - $this->assertNotNull($content); - $this->assertEquals($category->getId(), $content->getCategoryId()); - } - - public function testPreSaveNoCopyData() - { - ConcreteArticleQuery::create()->deleteAll(); - ConcreteQuizzQuery::create()->deleteAll(); - ConcreteContentQuery::create()->deleteAll(); - $quizz = new ConcreteQuizz(); - $quizz->save(); - $this->assertNotNull($quizz->getId()); - $content = ConcreteContentQuery::create()->findPk($quizz->getId()); - $this->assertNull($content); - } - - public function testGetParentOrCreateNew() - { - $article = new ConcreteArticle(); - $content = $article->getParentOrCreate(); - $this->assertTrue($content instanceof ConcreteContent, 'getParentOrCreate() returns an instance of the parent class'); - $this->assertTrue($content->isNew(), 'getParentOrCreate() returns a new instance of the parent class if the object is new'); - $this->assertEquals('ConcreteArticle', $content->getDescendantClass(), 'getParentOrCreate() correctly sets the descendant_class of the parent object'); - } - - public function testGetParentOrCreateExisting() - { - $article = new ConcreteArticle(); - $article->save(); - ConcreteContentPeer::clearInstancePool(); - $content = $article->getParentOrCreate(); - $this->assertTrue($content instanceof ConcreteContent, 'getParentOrCreate() returns an instance of the parent class'); - $this->assertFalse($content->isNew(), 'getParentOrCreate() returns an existing instance of the parent class if the object is persisted'); - $this->assertEquals($article->getId(), $content->getId(), 'getParentOrCreate() returns the parent object related to the current object'); - } - - public function testGetSyncParent() - { - $category = new ConcreteCategory(); - $category->setName('main'); - $article = new ConcreteArticle(); - $article->setTitle('FooBar'); - $article->setConcreteCategory($category); - $content = $article->getSyncParent(); - $this->assertEquals('FooBar', $content->getTitle(), 'getSyncParent() returns a synchronized parent object'); - $this->assertEquals($category, $content->getConcreteCategory(), 'getSyncParent() returns a synchronized parent object'); - } - - public function testPostDeleteCopyData() - { - ConcreteArticleQuery::create()->deleteAll(); - ConcreteQuizzQuery::create()->deleteAll(); - ConcreteContentQuery::create()->deleteAll(); - ConcreteCategoryQuery::create()->deleteAll(); - $category = new ConcreteCategory(); - $category->setName('main'); - $article = new ConcreteArticle(); - $article->setConcreteCategory($category); - $article->save(); - $id = $article->getId(); - $article->delete(); - $this->assertNull(ConcreteContentQuery::create()->findPk($id), 'delete() removes the parent record as well'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceParentBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceParentBehaviorTest.php deleted file mode 100644 index b62cd3d00..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/concrete_inheritance/ConcreteInheritanceParentBehaviorTest.php +++ /dev/null @@ -1,53 +0,0 @@ -deleteAll(); - ConcreteQuizzQuery::create()->deleteAll(); - ConcreteContentQuery::create()->deleteAll(); - $content = new ConcreteContent(); - $content->save(); - $this->assertFalse($content->hasChildObject()); - - $article = new ConcreteArticle(); - $article->save(); - $content = $article->getConcreteContent(); - $this->assertTrue($content->hasChildObject()); - } - - public function testGetChildObject() - { - ConcreteArticleQuery::create()->deleteAll(); - ConcreteQuizzQuery::create()->deleteAll(); - ConcreteContentQuery::create()->deleteAll(); - $content = new ConcreteContent(); - $content->save(); - $this->assertNull($content->getChildObject()); - - $article = new ConcreteArticle(); - $article->save(); - $content = $article->getConcreteContent(); - $this->assertEquals($article, $content->getChildObject()); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierTest.php deleted file mode 100644 index 2abb542d1..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierTest.php +++ /dev/null @@ -1,1351 +0,0 @@ -setTreeLeft('123'); - $this->assertEquals($t->getLeftValue(), '123', 'nested_set adds a getLeftValue() method'); - $t->setTreeRight('456'); - $this->assertEquals($t->getRightValue(), '456', 'nested_set adds a getRightValue() method'); - $t->setLevel('789'); - $this->assertEquals($t->getLevel(), '789', 'nested_set adds a getLevel() method'); - } - - public function testParameters() - { - $t = new Table10(); - $t->setMyLeftColumn('123'); - $this->assertEquals($t->getLeftValue(), '123', 'nested_set adds a getLeftValue() method'); - $t->setMyRightColumn('456'); - $this->assertEquals($t->getRightValue(), '456', 'nested_set adds a getRightValue() method'); - $t->setMyLevelColumn('789'); - $this->assertEquals($t->getLevel(), '789', 'nested_set adds a getLevel() method'); - $t->setMyScopeColumn('012'); - $this->assertEquals($t->getScopeValue(), '012', 'nested_set adds a getScopeValue() method'); - } - - public function testObjectAttributes() - { - $expectedAttributes = array('nestedSetQueries'); - foreach ($expectedAttributes as $attribute) { - $this->assertClassHasAttribute($attribute, 'Table9'); - } - } - - public function testSaveOutOfTree() - { - Table9Peer::doDeleteAll(); - $t1 = new Table9(); - $t1->setTitle('t1'); - try { - $t1->save(); - $this->assertTrue(true, 'A node can be saved without valid tree information'); - } catch (Exception $e) { - $this->fail('A node can be saved without valid tree information'); - } - try { - $t1->makeRoot(); - $this->assertTrue(true, 'A saved node can be turned into root'); - } catch (Exception $e) { - $this->fail('A saved node can be turned into root'); - } - $t1->save(); - $t2 = new Table9(); - $t2->setTitle('t1'); - $t2->save(); - try { - $t2->insertAsFirstChildOf($t1); - $this->assertTrue(true, 'A saved node can be inserted into the tree'); - } catch (Exception $e) { - $this->fail('A saved node can be inserted into the tree'); - } - try { - $t2->save(); - $this->assertTrue(true, 'A saved node can be inserted into the tree'); - } catch (Exception $e) { - $this->fail('A saved node can be inserted into the tree'); - } - } - - public function testPreUpdate() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t3->setLeftValue(null); - try { - $t3->save(); - $this->fail('Trying to save a node incorrectly updated throws an exception'); - } catch (Exception $e) { - $this->assertTrue(true, 'Trying to save a node incorrectly updated throws an exception'); - } - } - - public function testDelete() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t5->delete(); - $this->assertEquals(13, $t3->getRightValue(), 'delete() does not update existing nodes (because delete() clears the instance cache)'); - $expected = array( - 't1' => array(1, 8, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'delete() deletes all descendants and shifts the entire subtree correctly'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - try { - $t1->delete(); - $this->fail('delete() throws an exception when called on a root node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'delete() throws an exception when called on a root node'); - } - $this->assertNotEquals(array(), Table9Peer::doSelect(new Criteria()), 'delete() called on the root node does not delete the whole tree'); - } - - public function testMakeRoot() - { - $t = new Table9(); - $t->makeRoot(); - $this->assertEquals($t->getLeftValue(), 1, 'makeRoot() initializes left_column to 1'); - $this->assertEquals($t->getRightValue(), 2, 'makeRoot() initializes right_column to 2'); - $this->assertEquals($t->getLevel(), 0, 'makeRoot() initializes right_column to 0'); - $t = new Table9(); - $t->setLeftValue(12); - try { - $t->makeRoot(); - $this->fail('makeRoot() throws an exception when called on an object with a left_column value'); - } catch (PropelException $e) { - $this->assertTrue(true, 'makeRoot() throws an exception when called on an object with a left_column value'); - } - } - - public function testIsInTree() - { - $t1 = new Table9(); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for nodes with no left and right value'); - $t1->save(); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for saved nodes with no left and right value'); - $t1->setLeftValue(1)->setRightValue(0); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for nodes with zero left value'); - $t1->setLeftValue(0)->setRightValue(1); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for nodes with zero right value'); - $t1->setLeftValue(1)->setRightValue(1); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for nodes with equal left and right value'); - $t1->setLeftValue(1)->setRightValue(2); - $this->assertTrue($t1->isInTree(), 'inInTree() returns true for nodes with left < right value'); - $t1->setLeftValue(2)->setRightValue(1); - $this->assertFalse($t1->isInTree(), 'inInTree() returns false for nodes with left > right value'); - } - - public function testIsRoot() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertTrue($t1->isRoot(), 'root is seen as root'); - $this->assertFalse($t2->isRoot(), 'leaf is not seen as root'); - $this->assertFalse($t3->isRoot(), 'node is not seen as root'); - } - - public function testIsLeaf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertFalse($t1->isLeaf(), 'root is not seen as leaf'); - $this->assertTrue($t2->isLeaf(), 'leaf is seen as leaf'); - $this->assertFalse($t3->isLeaf(), 'node is not seen as leaf'); - } - - public function testIsDescendantOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertFalse($t1->isDescendantOf($t1), 'root is not seen as a descendant of root'); - $this->assertTrue($t2->isDescendantOf($t1), 'direct child is seen as a descendant of root'); - $this->assertFalse($t1->isDescendantOf($t2), 'root is not seen as a descendant of leaf'); - $this->assertTrue($t5->isDescendantOf($t1), 'grandchild is seen as a descendant of root'); - $this->assertTrue($t5->isDescendantOf($t3), 'direct child is seen as a descendant of node'); - $this->assertFalse($t3->isDescendantOf($t5), 'node is not seen as a descendant of its parent'); - } - - public function testIsAncestorOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertFalse($t1->isAncestorOf($t1), 'root is not seen as an ancestor of root'); - $this->assertTrue($t1->isAncestorOf($t2), 'root is seen as an ancestor of direct child'); - $this->assertFalse($t2->isAncestorOf($t1), 'direct child is not seen as an ancestor of root'); - $this->assertTrue($t1->isAncestorOf($t5), 'root is seen as an ancestor of grandchild'); - $this->assertTrue($t3->isAncestorOf($t5), 'parent is seen as an ancestor of node'); - $this->assertFalse($t5->isAncestorOf($t3), 'child is not seen as an ancestor of its parent'); - } - - public function testHasParent() - { - Table9Peer::doDeleteAll(); - $t0 = new Table9(); - $t1 = new Table9(); - $t1->setTitle('t1')->setLeftValue(1)->setRightValue(6)->setLevel(0)->save(); - $t2 = new Table9(); - $t2->setTitle('t2')->setLeftValue(2)->setRightValue(5)->setLevel(1)->save(); - $t3 = new Table9(); - $t3->setTitle('t3')->setLeftValue(3)->setRightValue(4)->setLevel(2)->save(); - $this->assertFalse($t0->hasParent(), 'empty node has no parent'); - $this->assertFalse($t1->hasParent(), 'root node has no parent'); - $this->assertTrue($t2->hasParent(), 'not root node has a parent'); - $this->assertTrue($t3->hasParent(), 'leaf node has a parent'); - } - - public function testGetParent() - { - Table9Peer::doDeleteAll(); - $t0 = new Table9(); - $this->assertFalse($t0->hasParent(), 'empty node has no parent'); - $t1 = new Table9(); - $t1->setTitle('t1')->setLeftValue(1)->setRightValue(8)->setLevel(0)->save(); - $t2 = new Table9(); - $t2->setTitle('t2')->setLeftValue(2)->setRightValue(7)->setLevel(1)->save(); - $t3 = new Table9(); - $t3->setTitle('t3')->setLeftValue(3)->setRightValue(4)->setLevel(2)->save(); - $t4 = new Table9(); - $t4->setTitle('t4')->setLeftValue(5)->setRightValue(6)->setLevel(2)->save(); - $this->assertNull($t1->getParent($this->con), 'getParent() return null for root nodes'); - $this->assertEquals($t2->getParent($this->con), $t1, 'getParent() correctly retrieves parent for nodes'); - $this->assertEquals($t3->getParent($this->con), $t2, 'getParent() correctly retrieves parent for leafs'); - $this->assertEquals($t4->getParent($this->con), $t2, 'getParent() retrieves the same parent for two siblings'); - } - - public function testGetParentCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $con = Propel::getConnection(); - $count = $con->getQueryCount(); - $parent = $t5->getParent($con); - $parent = $t5->getParent($con); - $this->assertEquals($count + 1, $con->getQueryCount(), 'getParent() only issues a query once'); - $this->assertEquals('t3', $parent->getTitle(), 'getParent() returns the parent Node'); - } - - public function testHasPrevSibling() - { - Table9Peer::doDeleteAll(); - $t0 = new Table9(); - $t1 = new Table9(); - $t1->setTitle('t1')->setLeftValue(1)->setRightValue(6)->save(); - $t2 = new Table9(); - $t2->setTitle('t2')->setLeftValue(2)->setRightValue(3)->save(); - $t3 = new Table9(); - $t3->setTitle('t3')->setLeftValue(4)->setRightValue(5)->save(); - $this->assertFalse($t0->hasPrevSibling(), 'empty node has no previous sibling'); - $this->assertFalse($t1->hasPrevSibling(), 'root node has no previous sibling'); - $this->assertFalse($t2->hasPrevSibling(), 'first sibling has no previous sibling'); - $this->assertTrue($t3->hasPrevSibling(), 'not first sibling has a previous siblingt'); - } - - public function testGetPrevSibling() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertNull($t1->getPrevSibling($this->con), 'getPrevSibling() returns null for root nodes'); - $this->assertNull($t2->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings'); - $this->assertEquals($t3->getPrevSibling($this->con), $t2, 'getPrevSibling() correctly retrieves prev sibling'); - $this->assertNull($t6->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings'); - $this->assertEquals($t7->getPrevSibling($this->con), $t6, 'getPrevSibling() correctly retrieves prev sibling'); - } - - public function testHasNextSibling() - { - Table9Peer::doDeleteAll(); - $t0 = new Table9(); - $t1 = new Table9(); - $t1->setTitle('t1')->setLeftValue(1)->setRightValue(6)->save(); - $t2 = new Table9(); - $t2->setTitle('t2')->setLeftValue(2)->setRightValue(3)->save(); - $t3 = new Table9(); - $t3->setTitle('t3')->setLeftValue(4)->setRightValue(5)->save(); - $this->assertFalse($t0->hasNextSibling(), 'empty node has no next sibling'); - $this->assertFalse($t1->hasNextSibling(), 'root node has no next sibling'); - $this->assertTrue($t2->hasNextSibling(), 'not last sibling has a next sibling'); - $this->assertFalse($t3->hasNextSibling(), 'last sibling has no next sibling'); - } - - public function testGetNextSibling() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertNull($t1->getNextSibling($this->con), 'getNextSibling() returns null for root nodes'); - $this->assertEquals($t2->getNextSibling($this->con), $t3, 'getNextSibling() correctly retrieves next sibling'); - $this->assertNull($t3->getNextSibling($this->con), 'getNextSibling() returns null for last siblings'); - $this->assertEquals($t6->getNextSibling($this->con), $t7, 'getNextSibling() correctly retrieves next sibling'); - $this->assertNull($t7->getNextSibling($this->con), 'getNextSibling() returns null for last siblings'); - } - - public function testAddNestedSetChildren() - { - $t0 = new Table9(); - $t1 = new Table9(); - $t2 = new Table9(); - $t0->addNestedSetChild($t1); - $t0->addNestedSetChild($t2); - $this->assertEquals(2, $t0->countChildren(), 'addNestedSetChild() adds the object to the internal children collection'); - $this->assertEquals($t0, $t1->getParent(), 'addNestedSetChild() sets the object as th parent of the parameter'); - $this->assertEquals($t0, $t2->getParent(), 'addNestedSetChild() sets the object as th parent of the parameter'); - } - - public function testHasChildren() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertTrue($t1->hasChildren(), 'root has children'); - $this->assertFalse($t2->hasChildren(), 'leaf has no children'); - $this->assertTrue($t3->hasChildren(), 'node has children'); - } - - public function testGetChildren() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertTrue($t2->getChildren() instanceof PropelObjectCollection, 'getChildren() returns a collection'); - $this->assertEquals(0, count($t2->getChildren()), 'getChildren() returns an empty collection for leafs'); - $children = $t3->getChildren(); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'getChildren() returns a collection of children'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't5'); - $children = $t3->getChildren($c); - $expected = array( - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'getChildren() accepts a criteria as parameter'); - } - - public function testGetChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $con = Propel::getConnection(); - $count = $con->getQueryCount(); - $children = $t3->getChildren(null, $con); - $children = $t3->getChildren(null, $con); - $this->assertEquals($count + 1, $con->getQueryCount(), 'getChildren() only issues a query once'); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'getChildren() returns a collection of children'); - // when using criteria, cache is not used - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't5'); - $children = $t3->getChildren($c, $con); - $this->assertEquals($count + 2, $con->getQueryCount(), 'getChildren() issues a new query when âssed a non-null Criteria'); - $expected = array( - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'getChildren() accepts a criteria as parameter'); - // but not erased either - $children = $t3->getChildren(null, $con); - $this->assertEquals($count + 2, $con->getQueryCount(), 'getChildren() keeps its internal cache after being called with a Criteria'); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'getChildren() returns a collection of children'); - } - - public function testCountChildren() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(0, $t2->countChildren(), 'countChildren() returns 0 for leafs'); - $this->assertEquals(2, $t3->countChildren(), 'countChildren() returns the number of children'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't5'); - $this->assertEquals(1, $t3->countChildren($c), 'countChildren() accepts a criteria as parameter'); - } - - public function testCountChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $con = Propel::getConnection(); - $count = $con->getQueryCount(); - $children = $t3->getChildren(null, $con); - $nbChildren = $t3->countChildren(null, $con); - $this->assertEquals($count + 1, $con->getQueryCount(), 'countChildren() uses the internal collection when passed no Criteria'); - $nbChildren = $t3->countChildren(new Criteria(), $con); - $this->assertEquals($count + 2, $con->getQueryCount(), 'countChildren() issues a new query when passed a Criteria'); - } - - public function testGetFirstChild() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToNextSiblingOf($t3); - /* Results in - t1 - | \ \ - t2 t3 t5 - | | \ - t4 t6 t7 - */ - $this->assertEquals($t2, $t1->getFirstChild(), 'getFirstChild() returns the first child'); - } - - public function testGetLastChild() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToNextSiblingOf($t3); - /* Results in - t1 - | \ \ - t2 t3 t5 - | | \ - t4 t6 t7 - */ - $this->assertEquals($t5, $t1->getLastChild(), 'getLastChild() returns the last child'); - } - - public function testGetSiblings() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(array(), $t1->getSiblings(), 'getSiblings() returns an empty array for root'); - $descendants = $t5->getSiblings(); - $expected = array( - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getSiblings() returns an array of siblings'); - $descendants = $t5->getSiblings(true); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getSiblings(true) includes the current node'); - $t5->moveToNextSiblingOf($t3); - /* Results in - t1 - | \ \ - t2 t3 t5 - | | \ - t4 t6 t7 - */ - $this->assertEquals(0, count($t4->getSiblings()), 'getSiblings() returns an empty colleciton for lone children'); - $descendants = $t3->getSiblings(); - $expected = array( - 't2' => array(2, 3, 1), - 't5' => array(8, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getSiblings() returns all siblings'); - } - - public function testGetDescendants() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(array(), $t2->getDescendants(), 'getDescendants() returns an empty array for leafs'); - $descendants = $t3->getDescendants(); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getDescendants() returns an array of descendants'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't5'); - $descendants = $t3->getDescendants($c); - $expected = array( - 't5' => array(7, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getDescendants() accepts a criteria as parameter'); - } - - public function testCountDescendants() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(0, $t2->countDescendants(), 'countDescendants() returns 0 for leafs'); - $this->assertEquals(4, $t3->countDescendants(), 'countDescendants() returns the number of descendants'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't5'); - $this->assertEquals(1, $t3->countDescendants($c), 'countDescendants() accepts a criteria as parameter'); - } - - public function testGetBranch() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(array($t2), $t2->getBranch()->getArrayCopy(), 'getBranch() returns the current node for leafs'); - $descendants = $t3->getBranch(); - $expected = array( - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getBranch() returns an array of descendants, uncluding the current node'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't3', Criteria::NOT_EQUAL); - $descendants = $t3->getBranch($c); - unset($expected['t3']); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getBranch() accepts a criteria as first parameter'); - } - - public function testGetAncestors() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(array(), $t1->getAncestors(), 'getAncestors() returns an empty array for roots'); - $ancestors = $t5->getAncestors(); - $expected = array( - 't1' => array(1, 14, 0), - 't3' => array(4, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() returns an array of ancestors'); - $c = new Criteria(); - $c->add(Table9Peer::TITLE, 't3'); - $ancestors = $t5->getAncestors($c); - $expected = array( - 't3' => array(4, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() accepts a criteria as parameter'); - } - - public function testAddChild() - { - Table9Peer::doDeleteAll(); - $t1 = new Table9(); - $t1->setTitle('t1'); - $t1->makeRoot(); - $t1->save(); - $t2 = new Table9(); - $t2->setTitle('t2'); - $t1->addChild($t2); - $t2->save(); - $t3 = new Table9(); - $t3->setTitle('t3'); - $t1->addChild($t3); - $t3->save(); - $t4 = new Table9(); - $t4->setTitle('t4'); - $t2->addChild($t4); - $t4->save(); - $expected = array( - 't1' => array(1, 8, 0), - 't2' => array(4, 7, 1), - 't3' => array(2, 3, 1), - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'addChild() adds the child and saves it'); - } - - public function testInsertAsFirstChildOf() - { - $this->assertTrue(method_exists('Table9', 'insertAsFirstChildOf'), 'nested_set adds a insertAsFirstChildOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t8 = new PublicTable9(); - $t8->setTitle('t8'); - $t = $t8->insertAsFirstChildOf($t3); - $this->assertEquals($t8, $t, 'insertAsFirstChildOf() returns the object it was called on'); - $this->assertEquals(5, $t4->getLeftValue(), 'insertAsFirstChildOf() does not modify the tree until the object is saved'); - $t8->save(); - $this->assertEquals(5, $t8->getLeftValue(), 'insertAsFirstChildOf() sets the left value correctly'); - $this->assertEquals(6, $t8->getRightValue(), 'insertAsFirstChildOf() sets the right value correctly'); - $this->assertEquals(2, $t8->getLevel(), 'insertAsFirstChildOf() sets the level correctly'); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - 't8' => array(5, 6, 2) - ); - $this->assertEquals($expected, $this->dumpTree(), 'insertAsFirstChildOf() shifts the other nodes correctly'); - try { - $t8->insertAsFirstChildOf($t4); - $this->fail('insertAsFirstChildOf() throws an exception when called on a saved object'); - } catch (PropelException $e) { - $this->assertTrue(true, 'insertAsFirstChildOf() throws an exception when called on a saved object'); - } - } - - public function testInsertAsLastChildOf() - { - $this->assertTrue(method_exists('Table9', 'insertAsLastChildOf'), 'nested_set adds a insertAsLastChildOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t8 = new PublicTable9(); - $t8->setTitle('t8'); - $t = $t8->insertAsLastChildOf($t3); - $this->assertEquals($t8, $t, 'insertAsLastChildOf() returns the object it was called on'); - $this->assertEquals(13, $t3->getRightValue(), 'insertAsLastChildOf() does not modify the tree until the object is saved'); - $t8->save(); - $this->assertEquals(13, $t8->getLeftValue(), 'insertAsLastChildOf() sets the left value correctly'); - $this->assertEquals(14, $t8->getRightValue(), 'insertAsLastChildOf() sets the right value correctly'); - $this->assertEquals(2, $t8->getLevel(), 'insertAsLastChildOf() sets the level correctly'); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - 't8' => array(13, 14, 2) - ); - $this->assertEquals($expected, $this->dumpTree(), 'insertAsLastChildOf() shifts the other nodes correctly'); - try { - $t8->insertAsLastChildOf($t4); - $this->fail('insertAsLastChildOf() throws an exception when called on a saved object'); - } catch (PropelException $e) { - $this->assertTrue(true, 'insertAsLastChildOf() throws an exception when called on a saved object'); - } - } - - public function testInsertAsPrevSiblingOf() - { - $this->assertTrue(method_exists('Table9', 'insertAsPrevSiblingOf'), 'nested_set adds a insertAsPrevSiblingOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t8 = new PublicTable9(); - $t8->setTitle('t8'); - $t = $t8->insertAsPrevSiblingOf($t3); - $this->assertEquals($t8, $t, 'insertAsPrevSiblingOf() returns the object it was called on'); - $this->assertEquals(4, $t3->getLeftValue(), 'insertAsPrevSiblingOf() does not modify the tree until the object is saved'); - $t8->save(); - $this->assertEquals(4, $t8->getLeftValue(), 'insertAsPrevSiblingOf() sets the left value correctly'); - $this->assertEquals(5, $t8->getRightValue(), 'insertAsPrevSiblingOf() sets the right value correctly'); - $this->assertEquals(1, $t8->getLevel(), 'insertAsPrevSiblingOf() sets the level correctly'); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(6, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - 't8' => array(4, 5, 1) - ); - $this->assertEquals($expected, $this->dumpTree(), 'insertAsPrevSiblingOf() shifts the other nodes correctly'); - try { - $t8->insertAsPrevSiblingOf($t4); - $this->fail('insertAsPrevSiblingOf() throws an exception when called on a saved object'); - } catch (PropelException $e) { - $this->assertTrue(true, 'insertAsPrevSiblingOf() throws an exception when called on a saved object'); - } - } - - public function testInsertAsNextSiblingOf() - { - $this->assertTrue(method_exists('Table9', 'insertAsNextSiblingOf'), 'nested_set adds a insertAsNextSiblingOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t8 = new PublicTable9(); - $t8->setTitle('t8'); - $t = $t8->insertAsNextSiblingOf($t3); - $this->assertEquals($t8, $t, 'insertAsNextSiblingOf() returns the object it was called on'); - $this->assertEquals(14, $t1->getRightValue(), 'insertAsNextSiblingOf() does not modify the tree until the object is saved'); - $t8->save(); - $this->assertEquals(14, $t8->getLeftValue(), 'insertAsNextSiblingOf() sets the left value correctly'); - $this->assertEquals(15, $t8->getRightValue(), 'insertAsNextSiblingOf() sets the right value correctly'); - $this->assertEquals(1, $t8->getLevel(), 'insertAsNextSiblingOf() sets the level correctly'); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - 't8' => array(14, 15, 1) - ); - $this->assertEquals($expected, $this->dumpTree(), 'insertAsNextSiblingOf() shifts the other nodes correctly'); - try { - $t8->insertAsNextSiblingOf($t4); - $this->fail('insertAsNextSiblingOf() throws an exception when called on a saved object'); - } catch (PropelException $e) { - $this->assertTrue(true, 'insertAsNextSiblingOf() throws an exception when called on a saved object'); - } - } - - public function testMoveToFirstChildOf() - { - $this->assertTrue(method_exists('Table9', 'moveToFirstChildOf'), 'nested_set adds a moveToFirstChildOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - try { - $t3->moveToFirstChildOf($t5); - $this->fail('moveToFirstChildOf() throws an exception when the target is a child node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToFirstChildOf() throws an exception when the target is a child node'); - } - // moving down - $t = $t3->moveToFirstChildOf($t2); - $this->assertEquals($t3, $t, 'moveToFirstChildOf() returns the object it was called on'); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 13, 1), - 't3' => array(3, 12, 2), - 't4' => array(4, 5, 3), - 't5' => array(6, 11, 3), - 't6' => array(7, 8, 4), - 't7' => array(9, 10, 4), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToFirstChildOf() moves the entire subtree down correctly'); - // moving up - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToFirstChildOf($t1); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(8, 9, 1), - 't3' => array(10, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(2, 7, 1), - 't6' => array(3, 4, 2), - 't7' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToFirstChildOf() moves the entire subtree up correctly'); - // moving to the same level - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToFirstChildOf($t3); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(5, 10, 2), - 't6' => array(6, 7, 3), - 't7' => array(8, 9, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToFirstChildOf() moves the entire subtree to the same level correctly'); - } - - public function testMoveToFirstChildOfAndChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - // fill children cache - $t3->getChildren(); - $t1->getChildren(); - // move - $t5->moveToFirstChildOf($t1); - $children = $t3->getChildren(); - $expected = array( - 't4' => array(11, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToFirstChildOf() reinitializes the child collection of all concerned nodes'); - $children = $t1->getChildren(); - $expected = array( - 't5' => array(2, 7, 1), - 't2' => array(8, 9, 1), - 't3' => array(10, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToFirstChildOf() reinitializes the child collection of all concerned nodes'); - } - - public function testMoveToLastChildOf() - { - $this->assertTrue(method_exists('Table9', 'moveToLastChildOf'), 'nested_set adds a moveToLastChildOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - try { - $t3->moveToLastChildOf($t5); - $this->fail('moveToLastChildOf() throws an exception when the target is a child node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToLastChildOf() throws an exception when the target is a child node'); - } - // moving up - $t = $t5->moveToLastChildOf($t1); - $this->assertEquals($t5, $t, 'moveToLastChildOf() returns the object it was called on'); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't4' => array(5, 6, 2), - 't5' => array(8, 13, 1), - 't6' => array(9, 10, 2), - 't7' => array(11, 12, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToLastChildOf() moves the entire subtree up correctly'); - // moving down - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t3->moveToLastChildOf($t2); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 13, 1), - 't3' => array(3, 12, 2), - 't4' => array(4, 5, 3), - 't5' => array(6, 11, 3), - 't6' => array(7, 8, 4), - 't7' => array(9, 10, 4), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToLastChildOf() moves the entire subtree down correctly'); - // moving to the same level - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t4->moveToLastChildOf($t3); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(5, 10, 2), - 't6' => array(6, 7, 3), - 't7' => array(8, 9, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToLastChildOf() moves the entire subtree to the same level correctly'); - } - - public function testMoveToLastChildOfAndChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - // fill children cache - $t3->getChildren(); - $t1->getChildren(); - // move - $t5->moveToLastChildOf($t1); - $children = $t3->getChildren(); - $expected = array( - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToLastChildOf() reinitializes the child collection of all concerned nodes'); - $children = $t1->getChildren(); - $expected = array( - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't5' => array(8, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToLastChildOf() reinitializes the child collection of all concerned nodes'); - } - - public function testMoveToPrevSiblingOf() - { - $this->assertTrue(method_exists('Table9', 'moveToPrevSiblingOf'), 'nested_set adds a moveToPrevSiblingOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - try { - $t5->moveToPrevSiblingOf($t1); - $this->fail('moveToPrevSiblingOf() throws an exception when the target is a root node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToPrevSiblingOf() throws an exception when the target is a root node'); - } - try { - $t5->moveToPrevSiblingOf($t6); - $this->fail('moveToPrevSiblingOf() throws an exception when the target is a child node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToPrevSiblingOf() throws an exception when the target is a child node'); - } - // moving up - $t = $t5->moveToPrevSiblingOf($t3); - /* Results in - t1 - | \ \ - t2 t5 t3 - | \ | - t6 t7 t4 - */ - $this->assertEquals($t5, $t, 'moveToPrevSiblingOf() returns the object it was called on'); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(10, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(4, 9, 1), - 't6' => array(5, 6, 2), - 't7' => array(7, 8, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToPrevSiblingOf() moves the entire subtree up correctly'); - // moving down - $t5->moveToPrevSiblingOf($t4); - /* Results in - t1 - | \ - t2 t3 - | \ - t5 t4 - | \ - t6 t7 - */ - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(5, 10, 2), - 't6' => array(6, 7, 3), - 't7' => array(8, 9, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToPrevSiblingOf() moves the entire subtree down correctly'); - // moving at the same level - $t4->moveToPrevSiblingOf($t5); - /* Results in - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToPrevSiblingOf() moves the entire subtree at the same level correctly'); - } - - public function testMoveToPrevSiblingOfAndChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - // fill children cache - $t3->getChildren(); - $t1->getChildren(); - // move - $t5->moveToPrevSiblingOf($t2); - $children = $t3->getChildren(); - $expected = array( - 't4' => array(11, 12, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToPrevSiblingOf() reinitializes the child collection of all concerned nodes'); - $children = $t1->getChildren(); - $expected = array( - 't5' => array(2, 7, 1), - 't2' => array(8, 9, 1), - 't3' => array(10, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToPrevSiblingOf() reinitializes the child collection of all concerned nodes'); - } - - public function testMoveToNextSiblingOfAndChildrenCache() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - // fill children cache - $t3->getChildren(); - $t1->getChildren(); - // move - $t5->moveToNextSiblingOf($t3); - $children = $t3->getChildren(); - $expected = array( - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToNextSiblingOf() reinitializes the child collection of all concerned nodes'); - $children = $t1->getChildren(); - $expected = array( - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't5' => array(8, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($children, true), 'moveToNextSiblingOf() reinitializes the child collection of all concerned nodes'); - } - - public function testMoveToNextSiblingOf() - { - $this->assertTrue(method_exists('Table9', 'moveToNextSiblingOf'), 'nested_set adds a moveToNextSiblingOf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - try { - $t5->moveToNextSiblingOf($t1); - $this->fail('moveToNextSiblingOf() throws an exception when the target is a root node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToNextSiblingOf() throws an exception when the target is a root node'); - } - try { - $t5->moveToNextSiblingOf($t6); - $this->fail('moveToNextSiblingOf() throws an exception when the target is a child node'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToNextSiblingOf() throws an exception when the target is a child node'); - } - // moving up - $t = $t5->moveToNextSiblingOf($t3); - /* Results in - t1 - | \ \ - t2 t3 t5 - | | \ - t4 t6 t7 - */ - $this->assertEquals($t5, $t, 'moveToPrevSiblingOf() returns the object it was called on'); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't4' => array(5, 6, 2), - 't5' => array(8, 13, 1), - 't6' => array(9, 10, 2), - 't7' => array(11, 12, 2), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToNextSiblingOf() moves the entire subtree up correctly'); - // moving down - $t = $t5->moveToNextSiblingOf($t4); - /* Results in - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToNextSiblingOf() moves the entire subtree down correctly'); - // moving at the same level - $t = $t4->moveToNextSiblingOf($t5); - /* Results in - t1 - | \ - t2 t3 - | \ - t5 t4 - | \ - t6 t7 - */ - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(11, 12, 2), - 't5' => array(5, 10, 2), - 't6' => array(6, 7, 3), - 't7' => array(8, 9, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'moveToNextSiblingOf() moves the entire subtree at the same level correctly'); - } - - public function testDeleteDescendants() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertNull($t2->deleteDescendants(), 'deleteDescendants() returns null leafs'); - $this->assertEquals(4, $t3->deleteDescendants(), 'deleteDescendants() returns the number of deleted nodes'); - $this->assertEquals(5, $t3->getRightValue(), 'deleteDescendants() updates the current node'); - $this->assertEquals(5, $t4->getLeftValue(), 'deleteDescendants() does not update existing nodes (because delete() clears the instance cache)'); - $expected = array( - 't1' => array(1, 6, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTree(), 'deleteDescendants() shifts the entire subtree correctly'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->assertEquals(6, $t1->deleteDescendants(), 'deleteDescendants() can be called on the root node'); - $expected = array( - 't1' => array(1, 2, 0), - ); - $this->assertEquals($expected, $this->dumpTree(), 'deleteDescendants() can delete all descendants of the root node'); - } - - public function testGetIterator() - { - $fixtures = $this->initTree(); - $this->assertTrue(method_exists('Table9', 'getIterator'), 'nested_set adds a getIterator() method'); - $root = Table9Peer::retrieveRoot(); - $iterator = $root->getIterator(); - $this->assertTrue($iterator instanceof NestedSetRecursiveIterator, 'getIterator() returns a NestedSetRecursiveIterator'); - foreach ($iterator as $node) { - $expected = array_shift($fixtures); - $this->assertEquals($expected, $node, 'getIterator returns an iterator parsing the tree order by left column'); - } - } - - public function testCompatibilityProxies() - { - $proxies = array('createRoot', 'retrieveParent', 'setParentNode', 'getNumberOfDescendants', 'getNumberOfChildren', 'retrievePrevSibling', 'retrieveNextSibling', 'retrieveFirstChild', 'retrieveLastChild', 'getPath'); - foreach ($proxies as $method) { - $this->assertFalse(method_exists('Table9', $method), 'proxies are not enabled by default'); - $this->assertTrue(method_exists('Table10', $method), 'setting method_proxies to true adds compatibility proxies'); - } - $t = new Table10(); - $t->createRoot(); - $this->assertEquals($t->getLeftValue(), 1, 'createRoot() is an alias for makeRoot()'); - $this->assertEquals($t->getRightValue(), 2, 'createRoot() is an alias for makeRoot()'); - $this->assertEquals($t->getLevel(), 0, 'createRoot() is an alias for makeRoot()'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierWithScopeTest.php deleted file mode 100644 index 439ff588f..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorObjectBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,551 +0,0 @@ -add(Table10Peer::TITLE, $title); - return Table10Peer::doSelectOne($c); - } - - public function testDelete() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t5->delete(); - $expected = array( - 't1' => array(1, 8, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 7, 1), - 't4' => array(5, 6, 2), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'delete() deletes all descendants and shifts the entire subtree correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'delete() does not delete anything out of the scope'); - } - - public function testIsDescendantOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertFalse($t8->isDescendantOf($t9), 'root is not seen as a child of root'); - $this->assertTrue($t9->isDescendantOf($t8), 'direct child is seen as a child of root'); - try { - $t2->isDescendantOf($t8); - $this->fail('isDescendantOf() throws an exception when comparing two nodes of different trees'); - } catch (PropelException $e) { - $this->assertTrue(true, 'isDescendantOf() throws an exception when comparing two nodes of different trees'); - } - } - - public function testGetParent() - { - $this->initTreeWithScope(); - $t1 = $this->getByTitle('t1'); - $this->assertNull($t1->getParent($this->con), 'getParent() return null for root nodes'); - $t2 = $this->getByTitle('t2'); - $this->assertEquals($t2->getParent($this->con), $t1, 'getParent() correctly retrieves parent for leafs'); - $t3 = $this->getByTitle('t3'); - $this->assertEquals($t3->getParent($this->con), $t1, 'getParent() correctly retrieves parent for nodes'); - $t4 = $this->getByTitle('t4'); - $this->assertEquals($t4->getParent($this->con), $t3, 'getParent() retrieves the same parent for nodes'); - } - - public function testGetPrevSibling() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertNull($t1->getPrevSibling($this->con), 'getPrevSibling() returns null for root nodes'); - $this->assertNull($t2->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings'); - $this->assertEquals($t3->getPrevSibling($this->con), $t2, 'getPrevSibling() correctly retrieves prev sibling'); - $this->assertNull($t6->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings'); - $this->assertEquals($t7->getPrevSibling($this->con), $t6, 'getPrevSibling() correctly retrieves prev sibling'); - } - - public function testGetNextSibling() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertNull($t1->getNextSibling($this->con), 'getNextSibling() returns null for root nodes'); - $this->assertEquals($t2->getNextSibling($this->con), $t3, 'getNextSibling() correctly retrieves next sibling'); - $this->assertNull($t3->getNextSibling($this->con), 'getNextSibling() returns null for last siblings'); - $this->assertEquals($t6->getNextSibling($this->con), $t7, 'getNextSibling() correctly retrieves next sibling'); - $this->assertNull($t7->getNextSibling($this->con), 'getNextSibling() returns null for last siblings'); - } - - public function testGetDescendants() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $descendants = $t3->getDescendants(); - $expected = array( - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpNodes($descendants), 'getDescendants() returns descendants from the current scope only'); - } - - public function testGetAncestors() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertEquals(array(), $t1->getAncestors(), 'getAncestors() returns an empty array for roots'); - $ancestors = $t5->getAncestors(); - $expected = array( - 't1' => array(1, 14, 0), - 't3' => array(4, 13, 1), - ); - $this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() returns ancestors from the current scope only'); - } - - public function testInsertAsFirstChildOf() - { - $this->assertTrue(method_exists('Table10', 'insertAsFirstChildOf'), 'nested_set adds a insertAsFirstChildOf() method'); - $fixtures = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t11 = new PublicTable10(); - $t11->setTitle('t11'); - $t11->insertAsFirstChildOf($fixtures[2]); // first child of t3 - $this->assertEquals(1, $t11->getScopeValue(), 'insertAsFirstChildOf() sets the scope value correctly'); - $t11->save(); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - 't11' => array(5, 6, 2) - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsFirstChildOf() shifts the other nodes correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsFirstChildOf() does not shift anything out of the scope'); - } - - public function testInsertAsLastChildOf() - { - $this->assertTrue(method_exists('Table10', 'insertAsLastChildOf'), 'nested_set adds a insertAsLastChildOf() method'); - $fixtures = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t11 = new PublicTable10(); - $t11->setTitle('t11'); - $t11->insertAsLastChildOf($fixtures[2]); // last child of t3 - $this->assertEquals(1, $t11->getScopeValue(), 'insertAsLastChildOf() sets the scope value correctly'); - $t11->save(); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - 't11' => array(13, 14, 2) - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsLastChildOf() shifts the other nodes correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsLastChildOf() does not shift anything out of the scope'); - } - - public function testInsertAsPrevSiblingOf() - { - $this->assertTrue(method_exists('Table10', 'insertAsPrevSiblingOf'), 'nested_set adds a insertAsPrevSiblingOf() method'); - $fixtures = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t11 = new PublicTable10(); - $t11->setTitle('t11'); - $t11->insertAsPrevSiblingOf($fixtures[2]); // prev sibling of t3 - $this->assertEquals(1, $t11->getScopeValue(), 'insertAsPrevSiblingOf() sets the scope value correctly'); - $t11->save(); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(6, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - 't11' => array(4, 5, 1) - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsPrevSiblingOf() shifts the other nodes correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsPrevSiblingOf() does not shift anything out of the scope'); - } - - public function testInsertAsNextSiblingOf() - { - $this->assertTrue(method_exists('Table10', 'insertAsNextSiblingOf'), 'nested_set adds a insertAsNextSiblingOf() method'); - $fixtures = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t11 = new PublicTable10(); - $t11->setTitle('t11'); - $t11->insertAsNextSiblingOf($fixtures[2]); // next sibling of t3 - $this->assertEquals(1, $t11->getScopeValue(), 'insertAsNextSiblingOf() sets the scope value correctly'); - $t11->save(); - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - 't11' => array(14, 15, 1) - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsNextSiblingOf() shifts the other nodes correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsNextSiblingOf() does not shift anything out of the scope'); - } - - public function testMoveToFirstChildOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - try { - $t8->moveToFirstChildOf($t3); - $this->fail('moveToFirstChildOf() throws an exception when the target is in a different tree'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToFirstChildOf() throws an exception when the target is in a different tree'); - } - try { - $t5->moveToLastChildOf($t2); - $this->assertTrue(true, 'moveToFirstChildOf() does not throw an exception when the target is in the same tree'); - } catch (PropelException $e) { - $this->fail('moveToFirstChildOf() does not throw an exception when the target is in the same tree'); - } - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToFirstChildOf() does not shift anything out of the scope'); - } - - public function testMoveToLastChildOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - try { - $t8->moveToLastChildOf($t3); - $this->fail('moveToLastChildOf() throws an exception when the target is in a different tree'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToLastChildOf() throws an exception when the target is in a different tree'); - } - try { - $t5->moveToLastChildOf($t2); - $this->assertTrue(true, 'moveToLastChildOf() does not throw an exception when the target is in the same tree'); - } catch (PropelException $e) { - $this->fail('moveToLastChildOf() does not throw an exception when the target is in the same tree'); - } - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToLastChildOf() does not shift anything out of the scope'); - } - - public function testMoveToPrevSiblingOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - try { - $t8->moveToPrevSiblingOf($t3); - $this->fail('moveToPrevSiblingOf() throws an exception when the target is in a different tree'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToPrevSiblingOf() throws an exception when the target is in a different tree'); - } - try { - $t5->moveToPrevSiblingOf($t2); - $this->assertTrue(true, 'moveToPrevSiblingOf() does not throw an exception when the target is in the same tree'); - } catch (PropelException $e) { - $this->fail('moveToPrevSiblingOf() does not throw an exception when the target is in the same tree'); - } - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToPrevSiblingOf() does not shift anything out of the scope'); - } - - public function testMoveToNextSiblingOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - try { - $t8->moveToNextSiblingOf($t3); - $this->fail('moveToNextSiblingOf() throws an exception when the target is in a different tree'); - } catch (PropelException $e) { - $this->assertTrue(true, 'moveToNextSiblingOf() throws an exception when the target is in a different tree'); - } - try { - $t5->moveToNextSiblingOf($t2); - $this->assertTrue(true, 'moveToNextSiblingOf() does not throw an exception when the target is in the same tree'); - } catch (PropelException $e) { - $this->fail('moveToNextSiblingOf() does not throw an exception when the target is in the same tree'); - } - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToNextSiblingOf() does not shift anything out of the scope'); - } - - public function testDeleteDescendants() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertEquals(4, $t3->deleteDescendants(), 'deleteDescendants() returns the number of deleted nodes'); - $expected = array( - 't1' => array(1, 6, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'deleteDescendants() shifts the entire subtree correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'deleteDescendants() does not delete anything out of the scope'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierTest.php deleted file mode 100644 index 24555b3cd..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierTest.php +++ /dev/null @@ -1,350 +0,0 @@ -assertEquals(Table9Peer::LEFT_COL, 'table9.TREE_LEFT', 'nested_set adds a LEFT_COL constant'); - $this->assertEquals(Table9Peer::RIGHT_COL, 'table9.TREE_RIGHT', 'nested_set adds a RIGHT_COL constant'); - $this->assertEquals(Table9Peer::LEVEL_COL, 'table9.TREE_LEVEL', 'nested_set adds a LEVEL_COL constant'); - } - - public function testRetrieveRoot() - { - $this->assertTrue(method_exists('Table9Peer', 'retrieveRoot'), 'nested_set adds a retrieveRoot() method'); - Table9Peer::doDeleteAll(); - $this->assertNull(Table9Peer::retrieveRoot(), 'retrieveRoot() returns null as long as no root node is defined'); - $t1 = new Table9(); - $t1->setLeftValue(123); - $t1->setRightValue(456); - $t1->save(); - $this->assertNull(Table9Peer::retrieveRoot(), 'retrieveRoot() returns null as long as no root node is defined'); - $t2 = new Table9(); - $t2->setLeftValue(1); - $t2->setRightValue(2); - $t2->save(); - $this->assertEquals(Table9Peer::retrieveRoot(), $t2, 'retrieveRoot() retrieves the root node'); - } - - public function testRetrieveTree() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $tree = Table9Peer::retrieveTree(); - $this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the whole tree'); - $c = new Criteria(); - $c->add(Table9Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL); - $tree = Table9Peer::retrieveTree($c); - $this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter'); - } - - public function testIsValid() - { - $this->assertTrue(method_exists('Table9Peer', 'isValid'), 'nested_set adds an isValid() method'); - $this->assertFalse(Table9Peer::isValid(null), 'isValid() returns false when passed null '); - $t1 = new Table9(); - $this->assertFalse(Table9Peer::isValid($t1), 'isValid() returns false when passed an empty node object'); - $t2 = new Table9(); - $t2->setLeftValue(5)->setRightValue(2); - $this->assertFalse(Table9Peer::isValid($t2), 'isValid() returns false when passed a node object with left > right'); - $t3 = new Table9(); - $t3->setLeftValue(5)->setRightValue(5); - $this->assertFalse(Table9Peer::isValid($t3), 'isValid() returns false when passed a node object with left = right'); - $t4 = new Table9(); - $t4->setLeftValue(2)->setRightValue(5); - $this->assertTrue(Table9Peer::isValid($t4), 'isValid() returns true when passed a node object with left < right'); - } - - public function testDeleteTree() - { - $this->initTree(); - Table9Peer::deleteTree(); - $this->assertEquals(array(), Table9Peer::doSelect(new Criteria()), 'deleteTree() deletes the whole tree'); - } - - public function testShiftRLValuesDelta() - { - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 1); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(2, 15, 0), - 't2' => array(3, 4, 1), - 't3' => array(5, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes with a positive amount'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = -1, $left = 1); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(0, 13, 0), - 't2' => array(1, 2, 1), - 't3' => array(3, 12, 1), - 't4' => array(4, 5, 2), - 't5' => array(6, 11, 2), - 't6' => array(7, 8, 3), - 't7' => array(9, 10, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues can shift all nodes with a negative amount'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = 3, $left = 1); - Table9Peer::clearInstancePool(); - $expected = array( - 't1'=> array(4, 17, 0), - 't2' => array(5, 6, 1), - 't3' => array(7, 16, 1), - 't4' => array(8, 9, 2), - 't5' => array(10, 15, 2), - 't6' => array(11, 12, 3), - 't7' => array(13, 14, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes several units to the right'); - Table9Peer::shiftRLValues($delta = -3, $left = 1); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes several units to the left'); - } - - public function testShiftRLValuesLeftLimit() - { - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 15); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues does not shift anything when the left parameter is higher than the highest right value'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 5); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 15, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts only the nodes having a LR value higher than the given left parameter'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 1); - Table9Peer::clearInstancePool(); - $expected = array( - 't1'=> array(2, 15, 0), - 't2' => array(3, 4, 1), - 't3' => array(5, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes when the left parameter is 1'); - } - - public function testShiftRLValuesRightLimit() - { - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 0); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues does not shift anything when the right parameter is 0'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 5); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(2, 14, 0), - 't2' => array(3, 4, 1), - 't3' => array(5, 13, 1), - 't4' => array(6, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shiftRLValues shifts only the nodes having a LR value lower than the given right parameter'); - $this->initTree(); - Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 15); - Table9Peer::clearInstancePool(); - $expected = array( - 't1'=> array(2, 15, 0), - 't2' => array(3, 4, 1), - 't3' => array(5, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes when the right parameter is higher than the highest right value'); - } - - public function testShiftLevel() - { - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $this->initTree(); - Table9Peer::shiftLevel($delta = 1, $first = 7, $last = 12); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 3), - 't6' => array(8, 9, 4), - 't7' => array(10, 11, 4), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftLevel shifts all nodes with a left value between the first and last'); - $this->initTree(); - Table9Peer::shiftLevel($delta = -1, $first = 7, $last = 12); - Table9Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 1), - 't6' => array(8, 9, 2), - 't7' => array(10, 11, 2), - ); - $this->assertEquals($this->dumpTree(), $expected, 'shiftLevel shifts all nodes wit ha negative amount'); - } - - public function testUpdateLoadedNodes() - { - $this->assertTrue(method_exists('Table9Peer', 'updateLoadedNodes'), 'nested_set adds a updateLoadedNodes() method'); - $fixtures = $this->initTree(); - Table9Peer::shiftRLValues(1, 5); - $expected = array( - 't1' => array(1, 14), - 't2' => array(2, 3), - 't3' => array(4, 13), - 't4' => array(5, 6), - 't5' => array(7, 12), - 't6' => array(8, 9), - 't7' => array(10, 11), - ); - $actual = array(); - foreach ($fixtures as $t) { - $actual[$t->getTitle()] = array($t->getLeftValue(), $t->getRightValue()); - } - $this->assertEquals($actual, $expected, 'Loaded nodes are not in sync before calling updateLoadedNodes()'); - Table9Peer::updateLoadedNodes(); - $expected = array( - 't1' => array(1, 15), - 't2' => array(2, 3), - 't3' => array(4, 14), - 't4' => array(6, 7), - 't5' => array(8, 13), - 't6' => array(9, 10), - 't7' => array(11, 12), - ); - $actual = array(); - foreach ($fixtures as $t) { - $actual[$t->getTitle()] = array($t->getLeftValue(), $t->getRightValue()); - } - $this->assertEquals($actual, $expected, 'Loaded nodes are in sync after calling updateLoadedNodes()'); - } - - public function testMakeRoomForLeaf() - { - $this->assertTrue(method_exists('Table9Peer', 'makeRoomForLeaf'), 'nested_set adds a makeRoomForLeaf() method'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $t = Table9Peer::makeRoomForLeaf(5); // first child of t3 - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'makeRoomForLeaf() shifts the other nodes correctly'); - foreach ($expected as $key => $values) - { - $this->assertEquals($values, array($$key->getLeftValue(), $$key->getRightValue(), $$key->getLevel()), 'makeRoomForLeaf() updates nodes already in memory'); - } - } - - public function testFixLevels() - { - $fixtures = $this->initTree(); - // reset the levels - foreach ($fixtures as $node) { - $node->setLevel(null)->save(); - } - // fix the levels - Table9Peer::fixLevels(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($expected, $this->dumpTree(), 'fixLevels() fixes the levels correctly'); - Table9Peer::fixLevels(); - $this->assertEquals($expected, $this->dumpTree(), 'fixLevels() can be called several times'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierWithScopeTest.php deleted file mode 100644 index 87026d348..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorPeerBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,253 +0,0 @@ -assertEquals(Table10Peer::LEFT_COL, 'table10.MY_LEFT_COLUMN', 'nested_set adds a LEFT_COL constant using the custom left_column parameter'); - $this->assertEquals(Table10Peer::RIGHT_COL, 'table10.MY_RIGHT_COLUMN', 'nested_set adds a RIGHT_COL constant using the custom right_column parameter'); - $this->assertEquals(Table10Peer::LEVEL_COL, 'table10.MY_LEVEL_COLUMN', 'nested_set adds a LEVEL_COL constant using the custom level_column parameter'); - $this->assertEquals(Table10Peer::SCOPE_COL, 'table10.MY_SCOPE_COLUMN', 'nested_set adds a SCOPE_COL constant when the use_scope parameter is true'); - } - - public function testRetrieveRoots() - { - $this->assertTrue(method_exists('Table10Peer', 'retrieveRoots'), 'nested_set adds a retrieveRoots() method for trees that use scope'); - $this->assertFalse(method_exists('Table9Peer', 'retrieveRoots'), 'nested_set does not add a retrieveRoots() method for trees that don\'t use scope'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertEquals(array($t1, $t8), Table10Peer::retrieveRoots(), 'retrieveRoots() returns the tree roots'); - $c = new Criteria(); - $c->add(Table10Peer::TITLE, 't1'); - $this->assertEquals(array($t1), Table10Peer::retrieveRoots($c), 'retrieveRoots() accepts a Criteria as first parameter'); - } - - public function testRetrieveRoot() - { - $this->assertTrue(method_exists('Table10Peer', 'retrieveRoot'), 'nested_set adds a retrieveRoot() method'); - Table10Peer::doDeleteAll(); - $t1 = new Table10(); - $t1->setLeftValue(1); - $t1->setRightValue(2); - $t1->setScopeValue(2); - $t1->save(); - $this->assertNull(Table10Peer::retrieveRoot(1), 'retrieveRoot() returns null as long as no root node is defined in the required scope'); - $t2 = new Table10(); - $t2->setLeftValue(1); - $t2->setRightValue(2); - $t2->setScopeValue(1); - $t2->save(); - $this->assertEquals(Table10Peer::retrieveRoot(1), $t2, 'retrieveRoot() retrieves the root node in the required scope'); - } - - public function testRetrieveTree() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $tree = Table10Peer::retrieveTree(1); - $this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the scoped tree'); - $tree = Table10Peer::retrieveTree(2); - $this->assertEquals(array($t8, $t9, $t10), $tree, 'retrieveTree() retrieves the scoped tree'); - $c = new Criteria(); - $c->add(Table10Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL); - $tree = Table10Peer::retrieveTree(1, $c); - $this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter'); - } - - public function testDeleteTree() - { - $this->initTreeWithScope(); - Table10Peer::deleteTree(1); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'deleteTree() does not delete anything out of the scope'); - } - - public function testShiftRLValues() - { - $this->assertTrue(method_exists('Table10Peer', 'shiftRLValues'), 'nested_set adds a shiftRLValues() method'); - $this->initTreeWithScope(); - Table10Peer::shiftRLValues(1, 100, null, 1); - Table10Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - ); - $this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues does not shift anything when the first parameter is higher than the highest right value'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope'); - $this->initTreeWithScope(); - Table10Peer::shiftRLValues(1, 1, null, 1); - Table10Peer::clearInstancePool(); - $expected = array( - 't1' => array(2, 15, 0), - 't2' => array(3, 4, 1), - 't3' => array(5, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift all nodes to the right'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope'); - $this->initTreeWithScope(); - Table10Peer::shiftRLValues(-1, 1, null, 1); - Table10Peer::clearInstancePool(); - $expected = array( - 't1' => array(0, 13, 0), - 't2' => array(1, 2, 1), - 't3' => array(3, 12, 1), - 't4' => array(4, 5, 2), - 't5' => array(6, 11, 2), - 't6' => array(7, 8, 3), - 't7' => array(9, 10, 3), - ); - $this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift all nodes to the left'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope'); - $this->initTreeWithScope(); - Table10Peer::shiftRLValues(1, 5, null, 1); - Table10Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 15, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 14, 1), - 't4' => array(6, 7, 2), - 't5' => array(8, 13, 2), - 't6' => array(9, 10, 3), - 't7' => array(11, 12, 3), - ); - $this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift some nodes to the right'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope'); - } - - public function testShiftLevel() - { - $this->initTreeWithScope(); - Table10Peer::shiftLevel($delta = 1, $first = 7, $last = 12, $scope = 1); - Table10Peer::clearInstancePool(); - $expected = array( - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 3), - 't6' => array(8, 9, 4), - 't7' => array(10, 11, 4), - ); - $this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftLevel can shift level whith a scope'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftLevel does not shift anything out of the scope'); - } - - public function testMakeRoomForLeaf() - { - $this->assertTrue(method_exists('Table10Peer', 'makeRoomForLeaf'), 'nested_set adds a makeRoomForLeaf() method'); - $fixtures = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $t = Table10Peer::makeRoomForLeaf(5, 1); // first child of t3 - $expected = array( - 't1' => array(1, 16, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 15, 1), - 't4' => array(7, 8, 2), - 't5' => array(9, 14, 2), - 't6' => array(10, 11, 3), - 't7' => array(12, 13, 3), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(1), 'makeRoomForLeaf() shifts the other nodes correctly'); - $expected = array( - 't8' => array(1, 6, 0), - 't9' => array(2, 3, 1), - 't10' => array(4, 5, 1), - ); - $this->assertEquals($expected, $this->dumpTreeWithScope(2), 'makeRoomForLeaf() does not shift anything out of the scope'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierTest.php deleted file mode 100644 index 8a6f5729b..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierTest.php +++ /dev/null @@ -1,283 +0,0 @@ -initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->descendantsOf($t7) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array()); - $this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants'); - $objs = Table9Query::create() - ->descendantsOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants'); - } - - public function testBranchOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->branchOf($t7) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t7)); - $this->assertEquals($coll, $objs, 'branchOf() filters by descendants and includes object passed as parameter'); - $objs = Table9Query::create() - ->branchOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $objs, 'branchOf() filters by descendants and includes object passed as parameter'); - $objs = Table9Query::create() - ->branchOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $objs, 'branchOf() returns the whole tree for the root node'); - } - - public function testChildrenOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->childrenOf($t6) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array()); - $this->assertEquals($coll, $objs, 'childrenOf() returns empty collection for leaf nodes'); - $objs = Table9Query::create() - ->childrenOf($t5) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t6, $t7)); - $this->assertEquals($coll, $objs, 'childrenOf() filters by children'); - $objs = Table9Query::create() - ->childrenOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t4, $t5)); - $this->assertEquals($coll, $objs, 'childrenOf() filters by children and not by descendants'); - } - - public function testSiblingsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $desc = Table9Query::create() - ->siblingsOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array()); - $this->assertEquals($coll, $desc, 'siblingsOf() returns empty collection for the root node'); - $desc = Table9Query::create() - ->siblingsOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t2)); - $this->assertEquals($coll, $desc, 'siblingsOf() filters by siblings'); - } - - public function testAncestorsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->ancestorsOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array()); - $this->assertEquals($coll, $objs, 'ancestorsOf() returns empty collection for root node'); - $objs = Table9Query::create() - ->ancestorsOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1)); - $this->assertEquals($coll, $objs, 'ancestorsOf() filters by ancestors'); - $objs = Table9Query::create() - ->ancestorsOf($t7) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t3, $t5)); - $this->assertEquals($coll, $objs, 'childrenOf() filters by ancestors'); - } - - public function testRootsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - /* Tree used for tests - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->rootsOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1)); - $this->assertEquals($coll, $objs, 'rootsOf() returns the root node for root node'); - $objs = Table9Query::create() - ->rootsOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t3)); - $this->assertEquals($coll, $objs, 'rootsOf() filters by ancestors and includes the node passed as parameter'); - $objs = Table9Query::create() - ->rootsOf($t7) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t3, $t5, $t7)); - $this->assertEquals($coll, $objs, 'rootsOf() filters by ancestors and includes the node passed as parameter'); - } - - public function testOrderByBranch() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToPrevSiblingOf($t4); - /* Results in - t1 - | \ - t2 t3 - | \ - t5 t4 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t5, $t6, $t7, $t4), 'orderByBranch() orders by branch left to right'); - $objs = Table9Query::create() - ->orderByBranch(true) - ->find(); - $coll = $this->buildCollection(array($t4, $t7, $t6, $t5, $t3, $t2, $t1), 'orderByBranch(true) orders by branch right to left'); - } - - public function testOrderByLevel() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $t5->moveToPrevSiblingOf($t4); - /* Results in - t1 - | \ - t2 t3 - | \ - t5 t4 - | \ - t6 t7 - */ - $objs = Table9Query::create() - ->orderByLevel() - ->find(); - $coll = $this->buildCollection(array($t1, $t2, $t5, $t4, $t6, $t7), 'orderByLevel() orders by level, from the root to the leaf'); - $objs = Table9Query::create() - ->orderByLevel(true) - ->find(); - $coll = $this->buildCollection(array($t7, $t6, $t4, $t5, $t2, $t1), 'orderByLevel(true) orders by level, from the leaf to the root'); - } - - public function testFindRoot() - { - $this->assertTrue(method_exists('Table9Query', 'findRoot'), 'nested_set adds a findRoot() method'); - Table9Query::create()->deleteAll(); - $this->assertNull(Table9Query::create()->findRoot(), 'findRoot() returns null as long as no root node is defined'); - $t1 = new Table9(); - $t1->setLeftValue(123); - $t1->setRightValue(456); - $t1->save(); - $this->assertNull(Table9Query::create()->findRoot(), 'findRoot() returns null as long as no root node is defined'); - $t2 = new Table9(); - $t2->setLeftValue(1); - $t2->setRightValue(2); - $t2->save(); - $this->assertEquals(Table9Query::create()->findRoot(), $t2, 'findRoot() retrieves the root node'); - } - - public function testfindTree() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); - $tree = Table9Query::create()->findTree(); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $tree, 'findTree() retrieves the whole tree, ordered by branch'); - } - - protected function buildCollection($arr) - { - $coll = new PropelObjectCollection(); - $coll->setData($arr); - $coll->setModel('Table9'); - - return $coll; - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierWithScopeTest.php deleted file mode 100644 index a7c283628..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorQueryBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,285 +0,0 @@ -initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->treeRoots() - ->find(); - $coll = $this->buildCollection(array($t1, $t8)); - $this->assertEquals($coll, $objs, 'treeRoots() filters by roots'); - } - - public function testInTree() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $tree = Table10Query::create() - ->inTree(1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $tree, 'inTree() filters by node'); - $tree = Table10Query::create() - ->inTree(2) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t8, $t9, $t10)); - $this->assertEquals($coll, $tree, 'inTree() filters by node'); - } - - public function testDescendantsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->descendantsOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants of the same scope'); - } - - public function testBranchOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->branchOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $objs, 'branchOf() filters by branch of the same scope'); - - } - - public function testChildrenOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->childrenOf($t1) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t2, $t3)); - $this->assertEquals($coll, $objs, 'childrenOf() filters by children of the same scope'); - } - - public function testSiblingsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $desc = Table10Query::create() - ->siblingsOf($t3) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t2)); - $this->assertEquals($coll, $desc, 'siblingsOf() returns filters by siblings of the same scope'); - } - - public function testAncestorsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->ancestorsOf($t5) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t3), 'ancestorsOf() filters by ancestors of the same scope'); - } - - public function testRootsOf() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $objs = Table10Query::create() - ->rootsOf($t5) - ->orderByBranch() - ->find(); - $coll = $this->buildCollection(array($t1, $t3, $t5), 'rootsOf() filters by ancestors of the same scope'); - } - - public function testFindRoot() - { - $this->assertTrue(method_exists('Table10Query', 'findRoot'), 'nested_set adds a findRoot() method'); - Table10Query::create()->deleteAll(); - $this->assertNull(Table10Query::create()->findRoot(1), 'findRoot() returns null as long as no root node is defined'); - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $this->assertEquals($t1, Table10Query::create()->findRoot(1), 'findRoot() returns a tree root'); - $this->assertEquals($t8, Table10Query::create()->findRoot(2), 'findRoot() returns a tree root'); - } - - public function testFindTree() - { - list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); - /* Tree used for tests - Scope 1 - t1 - | \ - t2 t3 - | \ - t4 t5 - | \ - t6 t7 - Scope 2 - t8 - | \ - t9 t10 - */ - $tree = Table10Query::create()->findTree(1); - $coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7)); - $this->assertEquals($coll, $tree, 'findTree() retrieves the tree of a scope, ordered by branch'); - $tree = Table10Query::create()->findTree(2); - $coll = $this->buildCollection(array($t8, $t9, $t10)); - $this->assertEquals($coll, $tree, 'findTree() retrieves the tree of a scope, ordered by branch'); - } - - protected function buildCollection($arr) - { - $coll = new PropelObjectCollection(); - $coll->setData($arr); - $coll->setModel('Table10'); - - return $coll; - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorTest.php deleted file mode 100644 index 06594aac8..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/nestedset/NestedSetBehaviorTest.php +++ /dev/null @@ -1,48 +0,0 @@ -assertEquals(count($table9->getColumns()), 5, 'nested_set adds three column by default'); - $this->assertTrue(method_exists('Table9', 'getTreeLeft'), 'nested_set adds a tree_left column by default'); - $this->assertTrue(method_exists('Table9', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column'); - $this->assertTrue(method_exists('Table9', 'getTreeRight'), 'nested_set adds a tree_right column by default'); - $this->assertTrue(method_exists('Table9', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column'); - $this->assertTrue(method_exists('Table9', 'getTreeLevel'), 'nested_set adds a tree_level column by default'); - $this->assertTrue(method_exists('Table9', 'getLevel'), 'nested_set maps the level getter with the tree_level column'); - $this->assertFalse(method_exists('Table9', 'getTreeScope'), 'nested_set does not add a tree_scope column by default'); - $this->assertFalse(method_exists('Table9', 'getScopeValue'), 'nested_set does not map the scope_value getter with the tree_scope column by default'); - - } - - public function testParameters() - { - $table10 = Table10Peer::getTableMap(); - $this->assertEquals(count($table10->getColumns()), 6, 'nested_set does not add columns when they already exist'); - $this->assertTrue(method_exists('Table10', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column'); - $this->assertTrue(method_exists('Table10', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column'); - $this->assertTrue(method_exists('Table10', 'getLevel'), 'nested_set maps the level getter with the tree_level column'); - $this->assertTrue(method_exists('Table10', 'getScopeValue'), 'nested_set maps the scope_value getter with the tree_scope column when the use_scope parameter is true'); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sluggable/SluggableBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sluggable/SluggableBehaviorTest.php deleted file mode 100644 index a65bf3ea8..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sluggable/SluggableBehaviorTest.php +++ /dev/null @@ -1,299 +0,0 @@ -assertEquals(count($table13->getColumns()), 3, 'Sluggable adds one columns by default'); - $this->assertTrue(method_exists('Table13', 'getSlug'), 'Sluggable adds a slug column by default'); - $table14 = Table14Peer::getTableMap(); - $this->assertEquals(count($table14->getColumns()), 3, 'Sluggable does not add a column when it already exists'); - $this->assertTrue(method_exists('Table14', 'getUrl'), 'Sluggable allows customization of slug_column name'); - $this->assertTrue(method_exists('Table14', 'getSlug'), 'Sluggable adds a standard getter for the slug column'); - } - - public function testObjectGetter() - { - $this->assertTrue(method_exists('Table13', 'getSlug'), 'Sluggable adds a getter for the slug column'); - $t = new Table13(); - $t->setSlug('foo'); - $this->assertEquals('foo', $t->getSlug(), 'getSlug() returns the object slug'); - $this->assertTrue(method_exists('Table14', 'getSlug'), 'Sluggable adds a getter for the slug column, even if the column does not have the default name'); - $t = new Table14(); - $t->setUrl('foo'); - $this->assertEquals('foo', $t->getSlug(), 'getSlug() returns the object slug'); - } - - public function testObjectSetter() - { - $this->assertTrue(method_exists('Table13', 'setSlug'), 'Sluggable adds a setter for the slug column'); - $t = new Table13(); - $t->setSlug('foo'); - $this->assertEquals('foo', $t->getSlug(), 'setSlug() sets the object slug'); - $this->assertTrue(method_exists('Table14', 'setSlug'), 'Sluggable adds a setter for the slug column, even if the column does not have the default name'); - $t = new Table14(); - $t->setSlug('foo'); - $this->assertEquals('foo', $t->getUrl(), 'setSlug() sets the object slug'); - } - - public function testObjectCreateRawSlug() - { - $t = new TestableTable13(); - $this->assertEquals('n-a', $t->createRawSlug(), 'createRawSlug() returns an empty string for an empty object with no pattern'); - $t->setTitle('Hello, World'); - $this->assertEquals('hello-world', $t->createRawSlug(), 'createRawSlug() returns the cleaned up object string representation by default'); - - $t = new TestableTable14(); - $this->assertEquals('/foo/n-a/bar', $t->createRawSlug(), 'createRawSlug() returns a slug for an empty object with a pattern'); - $t->setTitle('Hello, World'); - $this->assertEquals('/foo/hello-world/bar', $t->createRawSlug(), 'createRawSlug() returns a slug based on a pattern'); - } - - public static function cleanupSlugProvider() - { - return array( - array('', 'n-a'), - array('foo', 'foo'), - array('foo bar', 'foo-bar'), - array('foo bar', 'foo-bar'), - array('FoO', 'foo'), - array('fôo', 'foo'), - array(' foo ', 'foo'), - array('f/o:o', 'f-o-o'), - array('foo1', 'foo1'), - ); - } - - /** - * @dataProvider cleanupSlugProvider - */ - public function testObjectCleanupSlugPart($in, $out) - { - $t = new TestableTable13(); - $this->assertEquals($out, $t->cleanupSlugPart($in), 'cleanupSlugPart() cleans up the slug part'); - } - - public static function limitSlugSizeProvider() - { - return array( - array('123', '123'), - array(str_repeat('*', 80), str_repeat('*', 80)), - array(str_repeat('*', 97), str_repeat('*', 97)), - array(str_repeat('*', 98), str_repeat('*', 97)), - array(str_repeat('*', 99), str_repeat('*', 97)), - array(str_repeat('*', 100), str_repeat('*', 97)), - array(str_repeat('*', 150), str_repeat('*', 97)), - ); - } - - /** - * @dataProvider limitSlugSizeProvider - */ - public function testObjectLimitSlugSize($in, $out) - { - $t = new TestableTable14(); - $this->assertEquals($out, $t->limitSlugSize($in), 'limitSlugsize() limits the slug size'); - } - - public function testObjectMakeSlugUnique() - { - Table13Query::create()->deleteAll(); - $t = new TestableTable13(); - $this->assertEquals('', $t->makeSlugUnique(''), 'makeSlugUnique() returns the input slug when the input is empty'); - $this->assertEquals('foo', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns the input slug when the table is empty'); - $t->setSlug('foo'); - $t->save(); - $t = new TestableTable13(); - $this->assertEquals('bar', $t->makeSlugUnique('bar'), 'makeSlugUnique() returns the input slug when the table does not contain a similar slug'); - $t->save(); - $t = new TestableTable13(); - $this->assertEquals('foo-1', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns an incremented input when it already exists'); - $t->setSlug('foo-1'); - $t->save(); - $t = new TestableTable13(); - $this->assertEquals('foo-2', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns an incremented input when it already exists'); - } - - public function testObjectCreateSlug() - { - Table13Query::create()->deleteAll(); - $t = new TestableTable13(); - $this->assertEquals('n-a', $t->createSlug(), 'createSlug() returns n-a for an empty object'); - $t->setTitle('Hello, World!'); - $this->assertEquals('hello-world', $t->createSlug(), 'createSlug() returns a cleaned up slug'); - $t->setSlug('hello-world'); - $t->save(); - $t = new TestableTable13(); - $t->setTitle('Hello; wOrld'); - $this->assertEquals('hello-world-1', $t->createSlug(), 'createSlug() returns a unique slug'); - - Table14Query::create()->deleteAll(); - $t = new TestableTable14(); - $this->assertEquals('/foo/n-a/bar', $t->createSlug(), 'createSlug() returns a slug for an empty object with a pattern'); - $t->setTitle('Hello, World!'); - $this->assertEquals('/foo/hello-world/bar', $t->createSlug(), 'createSlug() returns a cleaned up slug'); - $t->setSlug('/foo/hello-world/bar'); - $t->save(); - $t = new TestableTable14(); - $t->setTitle('Hello; wOrld:'); - $this->assertEquals('/foo/hello-world/bar/1', $t->createSlug(), 'createSlug() returns a unique slug'); - } - - public function testObjectPreSave() - { - Table14Query::create()->deleteAll(); - $t = new Table14(); - $t->save(); - $this->assertEquals('/foo/n-a/bar', $t->getSlug(), 'preSave() sets a default slug for empty objects'); - $t = new Table14(); - $t->setTitle('Hello, World'); - $t->save(); - $this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() sets a cleanued up slug for objects'); - $t = new Table14(); - $t->setTitle('Hello, World'); - $t->save(); - $this->assertEquals('/foo/hello-world/bar/1', $t->getSlug(), 'preSave() sets a unique slug for objects'); - $t = new Table14(); - $t->setTitle('Hello, World'); - $t->setSlug('/foo/custom/bar'); - $t->save(); - $this->assertEquals('/foo/custom/bar', $t->getSlug(), 'preSave() uses the given slug if it exists'); - $t = new Table14(); - $t->setTitle('Hello, World'); - $t->setSlug('/foo/custom/bar'); - $t->save(); - $this->assertEquals('/foo/custom/bar/1', $t->getSlug(), 'preSave() uses the given slug if it exists and makes it unique'); - } - - public function testObjectSlugLifecycle() - { - Table13Query::create()->deleteAll(); - $t = new Table13(); - $t->setTitle('Hello, World'); - $t->save(); - $this->assertEquals('hello-world', $t->getSlug(), 'preSave() creates a slug for new objects'); - $t->setSlug('hello-bar'); - $t->save(); - $this->assertEquals('hello-bar', $t->getSlug(), 'setSlug() allows to override default slug'); - $t->setSlug(''); - $t->save(); - $this->assertEquals('hello-world', $t->getSlug(), 'setSlug(null) relaunches the slug generation'); - - Table14Query::create()->deleteAll(); - $t = new Table14(); - $t->setTitle('Hello, World2'); - $t->setSlug('hello-bar2'); - $t->save(); - $this->assertEquals('hello-bar2', $t->getSlug(), 'setSlug() allows to override default slug, even before save'); - $t->setSlug(''); - $t->save(); - $this->assertEquals('/foo/hello-world2/bar', $t->getSlug(), 'setSlug(null) relaunches the slug generation'); - } - - public function testObjectSlugAutoUpdate() - { - Table13Query::create()->deleteAll(); - $t = new Table13(); - $t->setTitle('Hello, World'); - $t->save(); - $this->assertEquals('hello-world', $t->getSlug(), 'preSave() creates a slug for new objects'); - $t->setTitle('Hello, My World'); - $t->save(); - $this->assertEquals('hello-my-world', $t->getSlug(), 'preSave() autoupdates slug on object change'); - $t->setTitle('Hello, My Whole New World'); - $t->setSlug('hello-bar'); - $t->save(); - $this->assertEquals('hello-bar', $t->getSlug(), 'preSave() does not autoupdate slug when it was set by the user'); - } - - public function testObjectSlugAutoUpdatePermanent() - { - Table14Query::create()->deleteAll(); - $t = new Table14(); - $t->setTitle('Hello, World'); - $t->save(); - $this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() creates a slug for new objects'); - $t->setTitle('Hello, My World'); - $t->save(); - $this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() does not autoupdate slug on object change for permanent slugs'); - $t->setSlug('hello-bar'); - $t->save(); - $this->assertEquals('hello-bar', $t->getSlug(), 'setSlug() still works for permanent slugs'); - } - - public function testQueryFindOneBySlug() - { - $this->assertTrue(method_exists('Table13Query', 'findOneBySlug'), 'The generated query provides a findOneBySlug() method'); - $this->assertTrue(method_exists('Table14Query', 'findOneBySlug'), 'The generated query provides a findOneBySlug() method even if the slug column doesnt have the default name'); - - Table14Query::create()->deleteAll(); - $t1 = new Table14(); - $t1->setTitle('Hello, World'); - $t1->save(); - $t2 = new Table14(); - $t2->setTitle('Hello, Cruel World'); - $t2->save(); - $t = Table14Query::create()->findOneBySlug('/foo/hello-world/bar'); - $this->assertEquals($t1, $t, 'findOneBySlug() returns a single object matching the slug'); - } -} - -class TestableTable13 extends Table13 -{ - public function createSlug() - { - return parent::createSlug(); - } - - public function createRawSlug() - { - return parent::createRawSlug(); - } - - public static function cleanupSlugPart($slug, $separator = '-') - { - return parent::cleanupSlugPart($slug, $separator); - } - - public function makeSlugUnique($slug, $separator = '-', $increment = 0) - { - return parent::makeSlugUnique($slug, $separator, $increment); - } -} - -class TestableTable14 extends Table14 -{ - public function createSlug() - { - return parent::createSlug(); - } - - public function createRawSlug() - { - return parent::createRawSlug(); - } - - public static function limitSlugSize($slug, $incrementReservedSpace = 3) - { - return parent::limitSlugSize($slug, $incrementReservedSpace); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierTest.php deleted file mode 100644 index 125e03a7f..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierTest.php +++ /dev/null @@ -1,279 +0,0 @@ -populateTable11(); - } - - public function testPreInsert() - { - Table11Peer::doDeleteAll(); - $t1 = new Table11(); - $t1->save(); - $this->assertEquals($t1->getRank(), 1, 'Sortable inserts new line in first position if no row present'); - $t2 = new Table11(); - $t2->setTitle('row2'); - $t2->save(); - $this->assertEquals($t2->getRank(), 2, 'Sortable inserts new line in last position'); - } - - public function testPreDelete() - { - $max = Table11Peer::getMaxRank(); - $t3 = Table11Peer::retrieveByRank(3); - $t3->delete(); - $this->assertEquals($max - 1, Table11Peer::getMaxRank(), 'Sortable rearrange subsequent rows on delete'); - $c = new Criteria(); - $c->add(Table11Peer::TITLE, 'row4'); - $t4 = Table11Peer::doSelectOne($c); - $this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete'); - } - - public function testIsFirst() - { - $first = Table11Peer::retrieveByRank(1); - $middle = Table11Peer::retrieveByRank(2); - $last = Table11Peer::retrieveByRank(4); - $this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank'); - $this->assertFalse($middle->isFirst(), 'isFirst() returns false for a middle rank'); - $this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank'); - } - - public function testIsLast() - { - $first = Table11Peer::retrieveByRank(1); - $middle = Table11Peer::retrieveByRank(2); - $last = Table11Peer::retrieveByRank(4); - $this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank'); - $this->assertFalse($middle->isLast(), 'isLast() returns false for a middle rank'); - $this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank'); - } - - public function testGetNext() - { - $t = Table11Peer::retrieveByRank(3); - $this->assertEquals(4, $t->getNext()->getRank(), 'getNext() returns the next object in rank'); - - $t = Table11Peer::retrieveByRank(4); - $this->assertNull($t->getNext(), 'getNext() returns null for the last object'); - } - - public function testGetPrevious() - { - $t = Table11Peer::retrieveByRank(3); - $this->assertEquals(2, $t->getPrevious()->getRank(), 'getPrevious() returns the previous object in rank'); - - $t = Table11Peer::retrieveByRank(1); - $this->assertNull($t->getPrevious(), 'getPrevious() returns null for the first object'); - } - - public function testInsertAtRank() - { - $t = new Table11(); - $t->setTitle('new'); - $t->insertAtRank(2); - $this->assertEquals(2, $t->getRank(), 'insertAtRank() sets the position'); - $this->assertTrue($t->isNew(), 'insertAtRank() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'row1', 2 => 'new', 3 => 'row2', 4 => 'row3', 5 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() shifts the entire suite'); - } - - public function testInsertAtMaxRankPlusOne() - { - $t = new Table11(); - $t->setTitle('new'); - $t->insertAtRank(5); - $this->assertEquals(5, $t->getRank(), 'insertAtRank() sets the position'); - $t->save(); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new'); - $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() can insert an object at the end of the list'); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtNegativeRank() - { - $t = new Table11(); - $t->insertAtRank(0); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtOverMaxRank() - { - $t = new Table11(); - $t->insertAtRank(6); - } - - public function testInsertAtBottom() - { - $t = new Table11(); - $t->setTitle('new'); - $t->insertAtBottom(); - $this->assertEquals(5, $t->getRank(), 'insertAtBottom() sets the position to the last'); - $this->assertTrue($t->isNew(), 'insertAtBottom() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new'); - $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtBottom() does not shift the entire suite'); - } - - public function testInsertAtTop() - { - $t = new Table11(); - $t->setTitle('new'); - $t->insertAtTop(); - $this->assertEquals(1, $t->getRank(), 'insertAtTop() sets the position to 1'); - $this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'new', 2 => 'row1', 3 => 'row2', 4 => 'row3', 5 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtTop() shifts the entire suite'); - } - - public function testMoveToRank() - { - $t2 = Table11Peer::retrieveByRank(2); - $t2->moveToRank(3); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move up'); - $t2->moveToRank(1); - $expected = array(1 => 'row2', 2 => 'row1', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the first rank'); - $t2->moveToRank(4); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the last rank'); - $t2->moveToRank(2); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move down'); - } - - /** - * @expectedException PropelException - */ - public function testMoveToNewObject() - { - $t = new Table11(); - $t->moveToRank(2); - } - - /** - * @expectedException PropelException - */ - public function testMoveToNegativeRank() - { - $t = Table11Peer::retrieveByRank(2); - $t->moveToRank(0); - } - - /** - * @expectedException PropelException - */ - public function testMoveToOverMaxRank() - { - $t = Table11Peer::retrieveByRank(2); - $t->moveToRank(5); - } - - public function testSwapWith() - { - $t2 = Table11Peer::retrieveByRank(2); - $t4 = Table11Peer::retrieveByRank(4); - $t2->swapWith($t4); - $expected = array(1 => 'row1', 2 => 'row4', 3 => 'row3', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'swapWith() swaps ranks of the two objects and leaves the other ranks unchanged'); - } - - public function testMoveUp() - { - $t3 = Table11Peer::retrieveByRank(3); - $res = $t3->moveUp(); - $this->assertEquals($t3, $res, 'moveUp() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank'); - $t3->moveUp(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank'); - $res = $t3->moveUp(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() changes nothing when called on the object at the top'); - } - - public function testMoveDown() - { - $t2 = Table11Peer::retrieveByRank(2); - $res = $t2->moveDown(); - $this->assertEquals($t2, $res, 'moveDown() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank'); - $t2->moveDown(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank'); - $res = $t2->moveDown(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() changes nothing when called on the object at the bottom'); - } - - public function testMoveToTop() - { - $t3 = Table11Peer::retrieveByRank(3); - $res = $t3->moveToTop(); - $this->assertEquals($t3, $res, 'moveToTop() returns the current oobject'); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() moves to the top'); - $res = $t3->moveToTop(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() changes nothing when called on the top node'); - } - - public function testMoveToBottom() - { - $t2 = Table11Peer::retrieveByRank(2); - $res = $t2->moveToBottom(); - $this->assertEquals($t2, $res, 'moveToBottom() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() moves to the bottom'); - $res = $t2->moveToBottom(); - $this->assertFalse($res, 'moveToBottom() returns false when called on the bottom node'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() changes nothing when called on the bottom node'); - } - - public function testRemoveFromList() - { - $t2 = Table11Peer::retrieveByRank(2); - $res = $t2->removeFromList(); - $this->assertTrue($res instanceof Table11, 'removeFromList() returns the current object'); - $this->assertNull($res->getRank(), 'removeFromList() resets the object\'s rank'); - Table11Peer::clearInstancePool(); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() does not change the list until the object is saved'); - $t2->save(); - Table11Peer::clearInstancePool(); - $expected = array(null => 'row2', 1 => 'row1', 2 => 'row3', 3 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() changes the list once the object is saved'); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierWithScopeTest.php deleted file mode 100644 index 22261880a..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorObjectBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,335 +0,0 @@ -populateTable12(); - } - - public function testPreInsert() - { - Table12Peer::doDeleteAll(); - $t1 = new Table12(); - $t1->setScopeValue(1); - $t1->save(); - $this->assertEquals($t1->getRank(), 1, 'Sortable inserts new line in first position if no row present'); - $t2 = new Table12(); - $t2->setScopeValue(1); - $t2->save(); - $this->assertEquals($t2->getRank(), 2, 'Sortable inserts new line in last position'); - $t2 = new Table12(); - $t2->setScopeValue(2); - $t2->save(); - $this->assertEquals($t2->getRank(), 1, 'Sortable inserts new line in last position'); - } - - public function testPreDelete() - { - $max = Table12Peer::getMaxRank(1); - $t3 = Table12Peer::retrieveByRank(3, 1); - $t3->delete(); - $this->assertEquals($max - 1, Table12Peer::getMaxRank(1), 'Sortable rearrange subsequent rows on delete'); - $c = new Criteria(); - $c->add(Table12Peer::TITLE, 'row4'); - $t4 = Table12Peer::doSelectOne($c); - $this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'delete() leaves other suites unchanged'); - } - - public function testIsFirst() - { - $first = Table12Peer::retrieveByRank(1, 1); - $middle = Table12Peer::retrieveByRank(2, 1); - $last = Table12Peer::retrieveByRank(4, 1); - $this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank'); - $this->assertFalse($middle->isFirst(), 'isFirst() returns false for a middle rank'); - $this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank'); - $first = Table12Peer::retrieveByRank(1, 2); - $last = Table12Peer::retrieveByRank(2, 2); - $this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank'); - $this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank'); - } - - public function testIsLast() - { - $first = Table12Peer::retrieveByRank(1, 1); - $middle = Table12Peer::retrieveByRank(2, 1); - $last = Table12Peer::retrieveByRank(4, 1); - $this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank'); - $this->assertFalse($middle->isLast(), 'isLast() returns false for a middle rank'); - $this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank'); - $first = Table12Peer::retrieveByRank(1, 2); - $last = Table12Peer::retrieveByRank(2, 2); - $this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank'); - $this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank'); - } - - public function testGetNext() - { - $t = Table12Peer::retrieveByRank(1, 1); - $this->assertEquals('row2', $t->getNext()->getTitle(), 'getNext() returns the next object in rank in the same suite'); - $t = Table12Peer::retrieveByRank(1, 2); - $this->assertEquals('row6', $t->getNext()->getTitle(), 'getNext() returns the next object in rank in the same suite'); - - $t = Table12Peer::retrieveByRank(3, 1); - $this->assertEquals(4, $t->getNext()->getRank(), 'getNext() returns the next object in rank'); - - $t = Table12Peer::retrieveByRank(4, 1); - $this->assertNull($t->getNext(), 'getNext() returns null for the last object'); - } - - public function testGetPrevious() - { - $t = Table12Peer::retrieveByRank(2, 1); - $this->assertEquals('row1', $t->getPrevious()->getTitle(), 'getPrevious() returns the previous object in rank in the same suite'); - $t = Table12Peer::retrieveByRank(2, 2); - $this->assertEquals('row5', $t->getPrevious()->getTitle(), 'getPrevious() returns the previous object in rank in the same suite'); - - $t = Table12Peer::retrieveByRank(3, 1); - $this->assertEquals(2, $t->getPrevious()->getRank(), 'getPrevious() returns the previous object in rank'); - - $t = Table12Peer::retrieveByRank(1, 1); - $this->assertNull($t->getPrevious(), 'getPrevious() returns null for the first object'); - } - - public function testInsertAtRank() - { - $t = new Table12(); - $t->setTitle('new'); - $t->setScopeValue(1); - $t->insertAtRank(2); - $this->assertEquals(2, $t->getRank(), 'insertAtRank() sets the position'); - $this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'row1', 2 => 'new', 3 => 'row2', 4 => 'row3', 5 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtRank() shifts the entire suite'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtRank() leaves other suites unchanged'); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtNegativeRank() - { - $t = new Table12(); - $t->setScopeValue(1); - $t->insertAtRank(0); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtOverMaxRank() - { - $t = new Table12(); - $t->setScopeValue(1); - $t->insertAtRank(6); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtNoScope() - { - $t = new Table12(); - $t->insertAtRank(3); - } - - public function testInsertAtBottom() - { - $t = new Table12(); - $t->setTitle('new'); - $t->setScopeValue(1); - $t->insertAtBottom(); - $this->assertEquals(5, $t->getRank(), 'insertAtBottom() sets the position to the last'); - $this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtBottom() does not shift the entire suite'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtBottom() leaves other suites unchanged'); - } - - /** - * @expectedException PropelException - */ - public function testInsertAtBottomNoScope() - { - $t = new Table12(); - $t->insertAtBottom(); - } - - public function testInsertAtTop() - { - $t = new Table12(); - $t->setTitle('new'); - $t->setScopeValue(1); - $t->insertAtTop(); - $this->assertEquals(1, $t->getRank(), 'insertAtTop() sets the position to 1'); - $this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object'); - $t->save(); - $expected = array(1 => 'new', 2 => 'row1', 3 => 'row2', 4 => 'row3', 5 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtTop() shifts the entire suite'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtTop() leaves other suites unchanged'); - } - - public function testMoveToRank() - { - $t2 = Table12Peer::retrieveByRank(2, 1); - $t2->moveToRank(3); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move up'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToRank() leaves other suites unchanged'); - $t2->moveToRank(1); - $expected = array(1 => 'row2', 2 => 'row1', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move to the first rank'); - $t2->moveToRank(4); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move to the last rank'); - $t2->moveToRank(2); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move down'); - } - - /** - * @expectedException PropelException - */ - public function testMoveToNewObject() - { - $t = new Table12(); - $t->moveToRank(2); - } - - /** - * @expectedException PropelException - */ - public function testMoveToNegativeRank() - { - $t = Table12Peer::retrieveByRank(2, 1); - $t->moveToRank(0); - } - - /** - * @expectedException PropelException - */ - public function testMoveToOverMaxRank() - { - $t = Table12Peer::retrieveByRank(2, 1); - $t->moveToRank(5); - } - - public function testSwapWith() - { - $t2 = Table12Peer::retrieveByRank(2, 1); - $t4 = Table12Peer::retrieveByRank(4, 1); - $t2->swapWith($t4); - $expected = array(1 => 'row1', 2 => 'row4', 3 => 'row3', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'swapWith() swaps ranks of the two objects and leaves the other ranks unchanged'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'swapWith() leaves other suites unchanged'); - } - - public function testMoveUp() - { - $t3 = Table12Peer::retrieveByRank(3, 1); - $res = $t3->moveUp(); - $this->assertEquals($t3, $res, 'moveUp() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() swaps ranks with the object of higher rank'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveUp() leaves other suites unchanged'); - $t3->moveUp(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() swaps ranks with the object of higher rank'); - $res = $t3->moveUp(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() changes nothing when called on the object at the top'); - } - - public function testMoveDown() - { - $t2 = Table12Peer::retrieveByRank(2, 1); - $res = $t2->moveDown(); - $this->assertEquals($t2, $res, 'moveDown() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() swaps ranks with the object of lower rank'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveDown() leaves other suites unchanged'); - $t2->moveDown(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() swaps ranks with the object of lower rank'); - $res = $t2->moveDown(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() changes nothing when called on the object at the bottom'); - } - - public function testMoveToTop() - { - $t3 = Table12Peer::retrieveByRank(3, 1); - $res = $t3->moveToTop(); - $this->assertEquals($t3, $res, 'moveToTop() returns the current object'); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToTop() moves to the top'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToTop() leaves other suites unchanged'); - $res = $t3->moveToTop(); - $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToTop() changes nothing when called on the top node'); - } - - public function testMoveToBottom() - { - $t2 = Table12Peer::retrieveByRank(2, 1); - $res = $t2->moveToBottom(); - $this->assertEquals($t2, $res, 'moveToBottom() returns the current object'); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToBottom() moves to the bottom'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToBottom() leaves other suites unchanged'); - $res = $t2->moveToBottom(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToBottom() changes nothing when called on the bottom node'); - } - - public function testRemoveFromList() - { - $t2 = Table12Peer::retrieveByRank(2, 1); - $res = $t2->removeFromList(); - $this->assertTrue($res instanceof Table12, 'removeFromList() returns the current object'); - $this->assertNull($res->getRank(), 'removeFromList() resets the object\'s rank'); - Table12Peer::clearInstancePool(); - $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'removeFromList() does not change the list until the object is saved'); - $t2->save(); - Table12Peer::clearInstancePool(); - $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'removeFromList() changes the list once the object is saved'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'removeFromList() leaves other suites unchanged'); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierTest.php deleted file mode 100644 index 3ffb26b7e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierTest.php +++ /dev/null @@ -1,83 +0,0 @@ -populateTable11(); - } - - public function testStaticAttributes() - { - $this->assertEquals(Table11Peer::RANK_COL, 'table11.SORTABLE_RANK'); - } - - public function testGetMaxRank() - { - $this->assertEquals(4, Table11Peer::getMaxRank(), 'getMaxRank() returns the maximum rank'); - $t4 = Table11Peer::retrieveByRank(4); - $t4->delete(); - $this->assertEquals(3, Table11Peer::getMaxRank(), 'getMaxRank() returns the maximum rank'); - Table11Peer::doDeleteAll(); - $this->assertNull(Table11Peer::getMaxRank(), 'getMaxRank() returns null for empty tables'); - } - public function testRetrieveByRank() - { - $t = Table11Peer::retrieveByRank(5); - $this->assertNull($t, 'retrieveByRank() returns null for an unknown rank'); - $t3 = Table11Peer::retrieveByRank(3); - $this->assertEquals(3, $t3->getRank(), 'retrieveByRank() returns the object with the required rank'); - $this->assertEquals('row3', $t3->getTitle(), 'retrieveByRank() returns the object with the required rank'); - } - - public function testReorder() - { - $objects = Table11Peer::doSelect(new Criteria()); - $ids = array(); - foreach ($objects as $object) { - $ids[]= $object->getPrimaryKey(); - } - $ranks = array(4, 3, 2, 1); - $order = array_combine($ids, $ranks); - Table11Peer::reorder($order); - $expected = array(1 => 'row3', 2 => 'row2', 3 => 'row4', 4 => 'row1'); - $this->assertEquals($expected, $this->getFixturesArray(), 'reorder() reorders the suite'); - } - - public function testDoSelectOrderByRank() - { - $objects = Table11Peer::doSelectOrderByRank(); - $oldRank = 0; - while ($object = array_shift($objects)) { - $this->assertTrue($object->getRank() > $oldRank); - $oldRank = $object->getRank(); - } - $objects = Table11Peer::doSelectOrderByRank(null, Criteria::DESC); - $oldRank = 10; - while ($object = array_shift($objects)) { - $this->assertTrue($object->getRank() < $oldRank); - $oldRank = $object->getRank(); - } - } - - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierWithScopeTest.php deleted file mode 100644 index f9a80f6e5..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorPeerBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,114 +0,0 @@ -populateTable12(); - } - - public function testStaticAttributes() - { - $this->assertEquals(Table12Peer::RANK_COL, 'table12.POSITION'); - $this->assertEquals(Table12Peer::SCOPE_COL, 'table12.MY_SCOPE_COLUMN'); - } - - public function testGetMaxRank() - { - $this->assertEquals(4, Table12Peer::getMaxRank(1), 'getMaxRank() returns the maximum rank of the suite'); - $this->assertEquals(2, Table12Peer::getMaxRank(2), 'getMaxRank() returns the maximum rank of the suite'); - $t4 = Table12Peer::retrieveByRank(4, 1); - $t4->delete(); - $this->assertEquals(3, Table12Peer::getMaxRank(1), 'getMaxRank() returns the maximum rank'); - Table12Peer::doDeleteAll(); - $this->assertNull(Table12Peer::getMaxRank(1), 'getMaxRank() returns null for empty tables'); - } - public function testRetrieveByRank() - { - $t = Table12Peer::retrieveByRank(5, 1); - $this->assertNull($t, 'retrieveByRank() returns null for an unknown rank'); - $t3 = Table12Peer::retrieveByRank(3, 1); - $this->assertEquals(3, $t3->getRank(), 'retrieveByRank() returns the object with the required rank in the required suite'); - $this->assertEquals('row3', $t3->getTitle(), 'retrieveByRank() returns the object with the required rank in the required suite'); - $t6 = Table12Peer::retrieveByRank(2, 2); - $this->assertEquals(2, $t6->getRank(), 'retrieveByRank() returns the object with the required rank in the required suite'); - $this->assertEquals('row6', $t6->getTitle(), 'retrieveByRank() returns the object with the required rank in the required suite'); - } - - public function testReorder() - { - $c = new Criteria(); - $c->add(Table12Peer::SCOPE_COL, 1); - $objects = Table12Peer::doSelectOrderByRank($c); - $ids = array(); - foreach ($objects as $object) { - $ids[]= $object->getPrimaryKey(); - } - $ranks = array(4, 3, 2, 1); - $order = array_combine($ids, $ranks); - Table12Peer::reorder($order); - $expected = array(1 => 'row4', 2 => 'row3', 3 => 'row2', 4 => 'row1'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'reorder() reorders the suite'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'reorder() leaves other suites unchanged'); - } - - public function testDoSelectOrderByRank() - { - $c = new Criteria(); - $c->add(Table12Peer::SCOPE_COL, 1); - $objects = Table12Peer::doSelectOrderByRank($c); - $oldRank = 0; - while ($object = array_shift($objects)) { - $this->assertTrue($object->getRank() > $oldRank); - $oldRank = $object->getRank(); - } - $c = new Criteria(); - $c->add(Table12Peer::SCOPE_COL, 1); - $objects = Table12Peer::doSelectOrderByRank($c, Criteria::DESC); - $oldRank = 10; - while ($object = array_shift($objects)) { - $this->assertTrue($object->getRank() < $oldRank); - $oldRank = $object->getRank(); - } - } - - public function testRetrieveList() - { - $this->assertEquals(4, count(Table12Peer::retrieveList(1)), 'retrieveList() returns the list of objects in the scope'); - $this->assertEquals(2, count(Table12Peer::retrieveList(2)), 'retrieveList() returns the list of objects in the scope'); - } - - public function testCountList() - { - $this->assertEquals(4, Table12Peer::countList(1), 'countList() returns the list of objects in the scope'); - $this->assertEquals(2, Table12Peer::countList(2), 'countList() returns the list of objects in the scope'); - } - - public function testDeleteList() - { - $this->assertEquals(4, Table12Peer::deleteList(1), 'deleteList() returns the list of objects in the scope'); - $this->assertEquals(2, Table12Peer::doCount(new Criteria()), 'deleteList() deletes the objects in the scope'); - $this->assertEquals(2, Table12Peer::deleteList(2), 'deleteList() returns the list of objects in the scope'); - $this->assertEquals(0, Table12Peer::doCount(new Criteria()), 'deleteList() deletes the objects in the scope'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierTest.php deleted file mode 100644 index 15614f10c..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierTest.php +++ /dev/null @@ -1,115 +0,0 @@ -populateTable11(); - } - - public function testFilterByRank() - { - $this->assertTrue(Table11Query::create()->filterByRank(1) instanceof Table11Query, 'filterByRank() returns the current query object'); - $this->assertEquals('row1', Table11Query::create()->filterByRank(1)->findOne()->getTitle(), 'filterByRank() filters on the rank'); - $this->assertEquals('row4', Table11Query::create()->filterByRank(4)->findOne()->getTitle(), 'filterByRank() filters on the rank'); - $this->assertNull(Table11Query::create()->filterByRank(5)->findOne(), 'filterByRank() filters on the rank, which makes the query return no result on a non-existent rank'); - } - - public function testOrderByRank() - { - $this->assertTrue(Table11Query::create()->orderByRank() instanceof Table11Query, 'orderByRank() returns the current query object'); - // default order - $query = Table11Query::create()->orderByRank(); - $expectedQuery = Table11Query::create()->addAscendingOrderByColumn(Table11Peer::SORTABLE_RANK); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank asc'); - // asc order - $query = Table11Query::create()->orderByRank(Criteria::ASC); - $expectedQuery = Table11Query::create()->addAscendingOrderByColumn(Table11Peer::SORTABLE_RANK); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction'); - // desc order - $query = Table11Query::create()->orderByRank(Criteria::DESC); - $expectedQuery = Table11Query::create()->addDescendingOrderByColumn(Table11Peer::SORTABLE_RANK); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction'); - } - - /** - * @expectedException PropelException - */ - public function testOrderByRankIncorrectDirection() - { - Table11Query::create()->orderByRank('foo'); - } - - public function testFindList() - { - $ts = Table11Query::create()->findList(); - $this->assertTrue($ts instanceof PropelObjectCollection, 'findList() returns a collection of objects'); - $this->assertEquals(4, count($ts), 'findList() does not filter the query'); - $this->assertEquals('row1', $ts[0]->getTitle(), 'findList() returns an ordered list'); - $this->assertEquals('row2', $ts[1]->getTitle(), 'findList() returns an ordered list'); - $this->assertEquals('row3', $ts[2]->getTitle(), 'findList() returns an ordered list'); - $this->assertEquals('row4', $ts[3]->getTitle(), 'findList() returns an ordered list'); - } - - public function testFindOneByRank() - { - $this->assertTrue(Table11Query::create()->findOneByRank(1) instanceof Table11, 'findOneByRank() returns an instance of the model object'); - $this->assertEquals('row1', Table11Query::create()->findOneByRank(1)->getTitle(), 'findOneByRank() returns a single item based on the rank'); - $this->assertEquals('row4', Table11Query::create()->findOneByRank(4)->getTitle(), 'findOneByRank() returns a single item based on the rank'); - $this->assertNull(Table11Query::create()->findOneByRank(5), 'findOneByRank() returns no result on a non-existent rank'); - } - - public function testGetMaxRank() - { - $this->assertEquals(4, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank'); - // delete one - $t4 = Table11Query::create()->findOneByRank(4); - $t4->delete(); - $this->assertEquals(3, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank'); - // add one - $t = new Table11(); - $t->save(); - $this->assertEquals(4, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank'); - // delete all - Table11Query::create()->deleteAll(); - $this->assertNull(Table11Query::create()->getMaxRank(), 'getMaxRank() returns null for empty tables'); - // add one - $t = new Table11(); - $t->save(); - $this->assertEquals(1, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank'); - } - - public function testReorder() - { - $objects = Table11Query::create()->find(); - $ids = array(); - foreach ($objects as $object) { - $ids[]= $object->getPrimaryKey(); - } - $ranks = array(4, 3, 2, 1); - $order = array_combine($ids, $ranks); - Table11Query::create()->reorder($order); - $expected = array(1 => 'row3', 2 => 'row2', 3 => 'row4', 4 => 'row1'); - $this->assertEquals($expected, $this->getFixturesArray(), 'reorder() reorders the suite'); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierWithScopeTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierWithScopeTest.php deleted file mode 100644 index db6f41b6d..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorQueryBuilderModifierWithScopeTest.php +++ /dev/null @@ -1,142 +0,0 @@ -populateTable12(); - } - - public function testInList() - { - /* List used for tests - scope=1 scope=2 - row1 row5 - row2 row6 - row3 - row4 - */ - $query = Table12Query::create()->inList(1); - $expectedQuery = Table12Query::create()->add(Table12Peer::MY_SCOPE_COLUMN, 1, Criteria::EQUAL); - $this->assertEquals($expectedQuery, $query, 'inList() filters the query by scope'); - $this->assertEquals(4, $query->count(), 'inList() filters the query by scope'); - $query = Table12Query::create()->inList(2); - $expectedQuery = Table12Query::create()->add(Table12Peer::MY_SCOPE_COLUMN, 2, Criteria::EQUAL); - $this->assertEquals($expectedQuery, $query, 'inList() filters the query by scope'); - $this->assertEquals(2, $query->count(), 'inList() filters the query by scope'); - } - - public function testFilterByRank() - { - /* List used for tests - scope=1 scope=2 - row1 row5 - row2 row6 - row3 - row4 - */ - $this->assertEquals('row1', Table12Query::create()->filterByRank(1, 1)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope'); - $this->assertEquals('row5', Table12Query::create()->filterByRank(1, 2)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope'); - $this->assertEquals('row4', Table12Query::create()->filterByRank(4, 1)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope'); - $this->assertNull(Table12Query::create()->filterByRank(4, 2)->findOne(), 'filterByRank() filters on the rank and the scope, which makes the query return no result on a non-existent rank'); - } - - public function testOrderByRank() - { - $this->assertTrue(Table12Query::create()->orderByRank() instanceof Table12Query, 'orderByRank() returns the current query object'); - // default order - $query = Table12Query::create()->orderByRank(); - $expectedQuery = Table12Query::create()->addAscendingOrderByColumn(Table12Peer::POSITION); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank asc'); - // asc order - $query = Table12Query::create()->orderByRank(Criteria::ASC); - $expectedQuery = Table12Query::create()->addAscendingOrderByColumn(Table12Peer::POSITION); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction'); - // desc order - $query = Table12Query::create()->orderByRank(Criteria::DESC); - $expectedQuery = Table12Query::create()->addDescendingOrderByColumn(Table12Peer::POSITION); - $this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction'); - } - - public function testFindList() - { - $ts = Table12Query::create()->findList(1); - $this->assertTrue($ts instanceof PropelObjectCollection, 'findList() returns a collection of objects'); - $this->assertEquals(4, count($ts), 'findList() filters the query by scope'); - $this->assertEquals('row1', $ts[0]->getTitle(), 'findList() returns an ordered scoped list'); - $this->assertEquals('row2', $ts[1]->getTitle(), 'findList() returns an ordered scoped list'); - $this->assertEquals('row3', $ts[2]->getTitle(), 'findList() returns an ordered scoped list'); - $this->assertEquals('row4', $ts[3]->getTitle(), 'findList() returns an ordered scoped list'); - $ts = Table12Query::create()->findList(2); - $this->assertEquals(2, count($ts), 'findList() filters the query by scope'); - $this->assertEquals('row5', $ts[0]->getTitle(), 'findList() returns an ordered scoped list'); - $this->assertEquals('row6', $ts[1]->getTitle(), 'findList() returns an ordered scoped list'); - } - - public function testFindOneByRank() - { - $this->assertTrue(Table12Query::create()->findOneByRank(1, 1) instanceof Table12, 'findOneByRank() returns an instance of the model object'); - $this->assertEquals('row1', Table12Query::create()->findOneByRank(1, 1)->getTitle(), 'findOneByRank() returns a single item based on the rank and the scope'); - $this->assertEquals('row5', Table12Query::create()->findOneByRank(1, 2)->getTitle(), 'findOneByRank() returns a single item based on the rank and the scope'); - $this->assertEquals('row4', Table12Query::create()->findOneByRank(4, 1)->getTitle(), 'findOneByRank() returns a single item based on the rank a,d the scope'); - $this->assertNull(Table12Query::create()->findOneByRank(4, 2), 'findOneByRank() returns no result on a non-existent rank and scope'); - } - - public function testGetMaxRank() - { - $this->assertEquals(4, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank in the scope'); - $this->assertEquals(2, Table12Query::create()->getMaxRank(2), 'getMaxRank() returns the maximum rank in the scope'); - // delete one - $t4 = Table12Query::create()->findOneByRank(4, 1); - $t4->delete(); - $this->assertEquals(3, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank'); - // add one - $t = new Table12(); - $t->setMyScopeColumn(1); - $t->save(); - $this->assertEquals(4, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank'); - // delete all - Table12Query::create()->deleteAll(); - $this->assertNull(Table12Query::create()->getMaxRank(1), 'getMaxRank() returns null for empty tables'); - // add one - $t = new Table12(); - $t->setMyScopeColumn(1); - $t->save(); - $this->assertEquals(1, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank'); - } - - public function testReorder() - { - $objects = Table12Query::create()->findList(1); - $ids = array(); - foreach ($objects as $object) { - $ids[]= $object->getPrimaryKey(); - } - $ranks = array(4, 3, 2, 1); - $order = array_combine($ids, $ranks); - Table12Query::create()->reorder($order); - $expected = array(1 => 'row4', 2 => 'row3', 3 => 'row2', 4 => 'row1'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'reorder() reorders the suite'); - $expected = array(1 => 'row5', 2 => 'row6'); - $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'reorder() leaves other suites unchanged'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorTest.php deleted file mode 100644 index 6192614a5..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/behavior/sortable/SortableBehaviorTest.php +++ /dev/null @@ -1,33 +0,0 @@ -assertEquals(count($table11->getColumns()), 3, 'Sortable adds one columns by default'); - $this->assertTrue(method_exists('Table11', 'getRank'), 'Sortable adds a rank column by default'); - $table12 = Table12Peer::getTableMap(); - $this->assertEquals(count($table12->getColumns()), 4, 'Sortable does not add a column when it already exists'); - $this->assertTrue(method_exists('Table12', 'getPosition'), 'Sortable allows customization of rank_column name'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/NamespaceTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/NamespaceTest.php deleted file mode 100644 index ff69d6f7e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/NamespaceTest.php +++ /dev/null @@ -1,225 +0,0 @@ -markTestSkipped('Namespace support requires PHP 5.3'); - } - parent::setUp(); - Propel::init('fixtures/namespaced/build/conf/bookstore_namespaced-conf.php'); - } - - protected function tearDown() - { - parent::tearDown(); - Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php'); - } - - public function testInsert() - { - $book = new \Foo\Bar\NamespacedBook(); - $book->setTitle('foo'); - $book->save(); - $this->assertFalse($book->isNew()); - - $publisher = new \Baz\NamespacedPublisher(); - $publisher->save(); - $this->assertFalse($publisher->isNew()); - } - - public function testUpdate() - { - $book = new \Foo\Bar\NamespacedBook(); - $book->setTitle('foo'); - $book->save(); - $book->setTitle('bar'); - $book->save(); - $this->assertFalse($book->isNew()); - } - - public function testRelate() - { - $author = new NamespacedAuthor(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedAuthor($author); - $book->save(); - $this->assertFalse($book->isNew()); - $this->assertFalse($author->isNew()); - - $author = new NamespacedAuthor(); - $book = new \Foo\Bar\NamespacedBook(); - $author->addNamespacedBook($book); - $author->save(); - $this->assertFalse($book->isNew()); - $this->assertFalse($author->isNew()); - - $publisher = new \Baz\NamespacedPublisher(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedPublisher($publisher); - $book->save(); - $this->assertFalse($book->isNew()); - $this->assertFalse($publisher->isNew()); - } - - public function testBasicQuery() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - \Baz\NamespacedPublisherQuery::create()->deleteAll(); - $noNamespacedBook = \Foo\Bar\NamespacedBookQuery::create()->findOne(); - $this->assertNull($noNamespacedBook); - $noPublihser = \Baz\NamespacedPublisherQuery::create()->findOne(); - $this->assertNull($noPublihser); - } - - public function testFind() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setTitle('War And Peace'); - $book->save(); - $book2 = \Foo\Bar\NamespacedBookQuery::create()->findPk($book->getId()); - $this->assertEquals($book, $book2); - $book3 = \Foo\Bar\NamespacedBookQuery::create()->findOneByTitle($book->getTitle()); - $this->assertEquals($book, $book3); - } - - public function testGetRelatedManyToOne() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - \Baz\NamespacedPublisherQuery::create()->deleteAll(); - $publisher = new \Baz\NamespacedPublisher(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedPublisher($publisher); - $book->save(); - \Foo\Bar\NamespacedBookPeer::clearInstancePool(); - \Baz\NamespacedPublisherPeer::clearInstancePool(); - $book2 = \Foo\Bar\NamespacedBookQuery::create()->findPk($book->getId()); - $publisher2 = $book2->getNamespacedPublisher(); - $this->assertEquals($publisher->getId(), $publisher2->getId()); - } - - public function testGetRelatedOneToMany() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - \Baz\NamespacedPublisherQuery::create()->deleteAll(); - $author = new NamespacedAuthor(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedAuthor($author); - $book->save(); - \Foo\Bar\NamespacedBookPeer::clearInstancePool(); - NamespacedAuthorPeer::clearInstancePool(); - $author2 = NamespacedAuthorQuery::create()->findPk($author->getId()); - $book2 = $author2->getNamespacedBooks()->getFirst(); - $this->assertEquals($book->getId(), $book2->getId()); - } - - public function testFindWithManyToOne() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - \Baz\NamespacedPublisherQuery::create()->deleteAll(); - $publisher = new \Baz\NamespacedPublisher(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedPublisher($publisher); - $book->save(); - \Foo\Bar\NamespacedBookPeer::clearInstancePool(); - \Baz\NamespacedPublisherPeer::clearInstancePool(); - $book2 = \Foo\Bar\NamespacedBookQuery::create() - ->joinWith('NamespacedPublisher') - ->findPk($book->getId()); - $publisher2 = $book2->getNamespacedPublisher(); - $this->assertEquals($publisher->getId(), $publisher2->getId()); - } - - public function testFindWithOneToMany() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - NamespacedAuthorQuery::create()->deleteAll(); - $author = new NamespacedAuthor(); - $book = new \Foo\Bar\NamespacedBook(); - $book->setNamespacedAuthor($author); - $book->save(); - \Foo\Bar\NamespacedBookPeer::clearInstancePool(); - NamespacedAuthorPeer::clearInstancePool(); - $author2 = NamespacedAuthorQuery::create() - ->joinWith('NamespacedBook') - ->findPk($author->getId()); - $book2 = $author2->getNamespacedBooks()->getFirst(); - $this->assertEquals($book->getId(), $book2->getId()); - } - - public function testSingleTableInheritance() - { - \Foo\Bar\NamespacedBookstoreEmployeeQuery::create()->deleteAll(); - $emp = new \Foo\Bar\NamespacedBookstoreEmployee(); - $emp->setName('Henry'); - $emp->save(); - $man = new \Foo\Bar\NamespacedBookstoreManager(); - $man->setName('John'); - $man->save(); - $cas = new \Foo\Bar\NamespacedBookstoreCashier(); - $cas->setName('William'); - $cas->save(); - $emps = \Foo\Bar\NamespacedBookstoreEmployeeQuery::create() - ->orderByName() - ->find(); - $this->assertEquals(3, count($emps)); - $this->assertTrue($emps[0] instanceof \Foo\Bar\NamespacedBookstoreEmployee); - $this->assertTrue($emps[1] instanceof \Foo\Bar\NamespacedBookstoreManager); - $this->assertTrue($emps[2] instanceof \Foo\Bar\NamespacedBookstoreCashier); - $nbMan = \Foo\Bar\NamespacedBookstoreManagerQuery::create() - ->count(); - $this->assertEquals(1, $nbMan); - } - - public function testManyToMany() - { - \Foo\Bar\NamespacedBookQuery::create()->deleteAll(); - \Baz\NamespacedBookClubQuery::create()->deleteAll(); - NamespacedBookListRelQuery::create()->deleteAll(); - $book1 = new \Foo\Bar\NamespacedBook(); - $book1->setTitle('bar'); - $book1->save(); - $book2 = new \Foo\Bar\NamespacedBook(); - $book2->setTitle('foo'); - $book2->save(); - $bookClub1 = new \Baz\NamespacedBookClub(); - $bookClub1->addNamespacedBook($book1); - $bookClub1->addNamespacedBook($book2); - $bookClub1->save(); - $bookClub2 = new \Baz\NamespacedBookClub(); - $bookClub2->addNamespacedBook($book1); - $bookClub2->save(); - $this->assertEquals(2, $book1->countNamespacedBookClubs()); - $this->assertEquals(1, $book2->countNamespacedBookClubs()); - $nbRels = NamespacedBookListRelQuery::create()->count(); - $this->assertEquals(3, $nbRels); - $con = Propel::getConnection(NamespacedBookListRelPeer::DATABASE_NAME); - $books = \Foo\Bar\NamespacedBookQuery::create() - ->orderByTitle() - ->joinWith('NamespacedBookListRel') - ->joinWith('NamespacedBookListRel.NamespacedBookClub') - ->find($con); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetObjectTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetObjectTest.php deleted file mode 100644 index e6f7fb943..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetObjectTest.php +++ /dev/null @@ -1,187 +0,0 @@ -assertTrue($pp->isRoot(), 'Node must be root'); - } - - /** - * Test xxxNestedSet::isRoot() as false - */ - public function testObjectIsRootFalse() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertFalse($school->isRoot(), 'Node must not be root'); - } - - /** - * Test xxxNestedSet::retrieveParent() as true. - */ - public function testObjectRetrieveParentTrue() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertNotNull($school->retrieveParent(), 'Parent node must exist'); - } - - /** - * Test xxxNestedSet::retrieveParent() as false. - */ - public function testObjectRetrieveParentFalse() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - $this->assertNull($home->retrieveParent(), 'Parent node must not exist and retrieved not be null'); - } - - /** - * Test xxxNestedSet::hasParent() as true. - */ - public function testObjectHasParentTrue() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertTrue($school->hasParent(), 'Node must have parent node'); - } - - /** - * Test xxxNestedSet::hasParent() as false - */ - public function testObjectHasParentFalse() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - $this->assertFalse($home->hasParent(), 'Root node must not have parent'); - } - - /** - * Test xxxNestedSet::isLeaf() as true. - */ - public function testObjectIsLeafTrue() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'simulator', Criteria::EQUAL); - - $simulator = PagePeer::doSelectOne($c); - $this->assertTrue($simulator->isLeaf($simulator), 'Node must be a leaf'); - } - - /** - * Test xxxNestedSet::isLeaf() as false - */ - public function testObjectIsLeafFalse() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'contact', Criteria::EQUAL); - - $contact = PagePeer::doSelectOne($c); - $this->assertFalse($contact->isLeaf($contact), 'Node must not be a leaf'); - } - - /** - * Test xxxNestedSet::makeRoot() - */ - public function testObjectMakeRoot() - { - $page = new Page(); - $page->makeRoot(); - $this->assertEquals(1, $page->getLeftValue(), 'Node left value must equal 1'); - $this->assertEquals(2, $page->getRightValue(), 'Node right value must equal 2'); - } - - /** - * Test xxxNestedSet::makeRoot() exception - * @expectedException PropelException - */ - public function testObjectMakeRootException() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - $home->makeRoot(); - } - - /** - * Test xxxNestedSet::getDescendants() - */ - public function testPeerGetDescendants() - { - $nodesWithoutPool = array(); - CategoryPeer::clearInstancePool(); - $cat = CategoryPeer::retrieveRoot(1); - $children = $cat->getDescendants(); - foreach($children as $child) - { - $nodesWithoutPool[] = $child->getTitle(); - } - $this->assertEquals($nodesWithoutPool, array('Cat_1_1', 'Cat_1_1_1', 'Cat_1_1_1_1')); - } - - /** - * Test xxxNestedSet::getDescendantsTwice() - */ - public function testPeerGetDescendantsTwice() - { - $nodesWithoutPool = array(); - $nodesWithPool = array(); - - CategoryPeer::clearInstancePool(); - $cat = CategoryPeer::retrieveRoot(1); - $children = $cat->getDescendants(); - foreach($children as $child) - { - $nodesWithoutPool[] = $child->getTitle(); - } - - $cat = CategoryPeer::retrieveRoot(1); - $children = $cat->getDescendants(); - foreach($children as $child) - { - $nodesWithPool[] = $child->getTitle(); - } - $this->assertEquals($nodesWithoutPool, $nodesWithPool, 'Retrieved nodes must be the same with and without InstancePooling'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetPeerTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetPeerTest.php deleted file mode 100644 index ae255c010..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetPeerTest.php +++ /dev/null @@ -1,188 +0,0 @@ -assertNotNull($pp, 'Node must exist and not be null'); - $this->assertEquals(1, $pp->getLeftValue(), 'Node left value must be equal to 1'); - } - - /** - * Test retrieveRoot() as false - */ - public function testRetrieveRootNotExist() - { - $pp = PagePeer::retrieveRoot(2); - $this->assertNull($pp, 'Root with such scopeId must not exist'); - } - - /** - * Test xxxNestedSetPeer::isRoot() as true - */ - public function testPeerIsRootTrue() - { - $pp = PagePeer::retrieveRoot(1); - $this->assertTrue(PagePeer::isRoot($pp), 'Node must be root'); - } - - /** - * Test xxxNestedSetPeer::isRoot() as false - */ - public function testPeerIsRootFalse() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertFalse(PagePeer::isRoot($school), 'Node must not be root'); - } - - /** - * Test xxxNestedSetPeer::retrieveParent() as true. - */ - public function testPeerRetrieveParentTrue() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertNotNull(PagePeer::retrieveParent($school), 'Parent node must exist'); - } - - /** - * Test xxxNestedSetPeer::retrieveParent() as false. - */ - public function testPeerRetrieveParentFalse() - { - $c = new Criteria(PagePeer::DATABASE_NAME); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - $this->assertNull(PagePeer::retrieveParent($home), 'Parent node must not exist and retrieved not be null'); - } - - /** - * Test xxxNestedSetPeer::hasParent() as true. - */ - public function testPeerHasParentTrue() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertTrue(PagePeer::hasParent($school), 'Node must have parent node'); - } - - /** - * Test xxxNestedSetPeer::hasParent() as false - */ - public function testPeerHasParentFalse() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - $this->assertFalse(PagePeer::hasParent($home), 'Root node must not have parent'); - } - - /** - * Test xxxNestedSetPeer::isValid() as true. - */ - public function testPeerIsValidTrue() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'school', Criteria::EQUAL); - - $school = PagePeer::doSelectOne($c); - $this->assertTrue(PagePeer::isValid($school), 'Node must be valid'); - } - - /** - * Test xxxNestedSetPeer::isValid() as false - */ - public function testPeerIsValidFalse() - { - $page = new Page(); - $this->assertFalse(PagePeer::isValid($page), 'Node left and right values must be invalid'); - $this->assertFalse(PagePeer::isValid(null), 'Null must be invalid'); - } - - /** - * Test xxxNestedSetPeer::isLeaf() as true. - */ - public function testPeerIsLeafTrue() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'simulator', Criteria::EQUAL); - - $simulator = PagePeer::doSelectOne($c); - $this->assertTrue(PagePeer::isLeaf($simulator), 'Node must be a leaf'); - } - - /** - * Test xxxNestedSetPeer::isLeaf() as false - */ - public function testPeerIsLeafFalse() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'contact', Criteria::EQUAL); - - $contact = PagePeer::doSelectOne($c); - $this->assertFalse(PagePeer::isLeaf($contact), 'Node must not be a leaf'); - } - - /** - * Test xxxNestedSetPeer::createRoot() - */ - public function testPeerCreateRoot() - { - $page = new Page(); - PagePeer::createRoot($page); - $this->assertEquals(1, $page->getLeftValue(), 'Node left value must equal 1'); - $this->assertEquals(2, $page->getRightValue(), 'Node right value must equal 2'); - } - - /** - * Test xxxNestedSetPeer::createRoot() exception - * @expectedException PropelException - */ - public function testPeerCreateRootException() - { - $c = new Criteria(); - $c->add(PagePeer::TITLE, 'home', Criteria::EQUAL); - - $home = PagePeer::doSelectOne($c); - PagePeer::createRoot($home); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetTest.php deleted file mode 100644 index b09178551..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedNestedSetTest.php +++ /dev/null @@ -1,120 +0,0 @@ -getDepth()) - , $item->getId() , ': ' - , $item->getTitle() - , ' [', $item->getLeftValue(), ':', $item->getRightValue() , ']' - . "\n"; - } - } - - /** - * Adds a new Page row with specified parent Id. - * - * @param int $parentId - */ - protected function addNewChildPage($parentId) - { - $db = Propel::getConnection(PagePeer::DATABASE_NAME); - - //$db->beginTransaction(); - - $parent = PagePeer::retrieveByPK($parentId); - $page = new Page(); - $page->setTitle('new page '.time()); - $page->insertAsLastChildOf($parent); - $page->save(); - - //$db->commit(); - } - - /** - * Asserts that the Page table tree integrity is intact. - */ - protected function assertPageTreeIntegrity() - { - $db = Propel::getConnection(PagePeer::DATABASE_NAME); - - $values = array(); - $log = ''; - - foreach ($db->query('SELECT Id, LeftChild, RightChild, Title FROM Page', PDO::FETCH_NUM) as $row) { - - list($id, $leftChild, $rightChild, $title) = $row; - - if (!in_array($leftChild, $values)) { - $values[] = (int) $leftChild; - } else { - $this->fail('Duplicate LeftChild value '.$leftChild); - } - - if (!in_array($rightChild, $values)) { - $values[] = (int) $rightChild; - } else { - $this->fail('Duplicate RightChild value '.$rightChild); - } - - $log .= "[$id($leftChild:$rightChild)]"; - } - - sort($values); - - if ($values[count($values)-1] != count($values)) { - $message = sprintf("Tree integrity NOT ok (%s)\n", $log); - $message .= sprintf('Integrity error: value count: %d, high value: %d', count($values), $values[count($values)-1]); - $this->fail($message); - } - - } - - /** - * Tests adding a node to the Page tree. - */ - public function testAdd() - { - $db = Propel::getConnection(PagePeer::DATABASE_NAME); - - // I'm not sure if the specific ID matters, but this should match original - // code. The ID will change with subsequent runs (e.g. the first time it will be 11) - $startId = $db->query('SELECT MIN(Id) FROM Page')->fetchColumn(); - $this->addNewChildPage($startId + 10); - $this->assertPageTreeIntegrity(); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectLobTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectLobTest.php deleted file mode 100644 index 290e73c4f..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectLobTest.php +++ /dev/null @@ -1,289 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedObjectLobTest extends BookstoreEmptyTestBase -{ - - /** - * Array of filenames pointing to blob/clob files indexed by the basename. - * - * @var array string[] - */ - protected $sampleLobFiles = array(); - - protected function setUp() - { - parent::setUp(); - BookstoreDataPopulator::populate(); - $this->sampleLobFiles['tin_drum.gif'] = TESTS_BASE_DIR . '/etc/lob/tin_drum.gif'; - $this->sampleLobFiles['tin_drum.txt'] = TESTS_BASE_DIR . '/etc/lob/tin_drum.txt'; - $this->sampleLobFiles['propel.gif'] = TESTS_BASE_DIR . '/etc/lob/propel.gif'; - } - - /** - * Gets a LOB filename. - * - * @param string $basename Basename of LOB filename to return (if left blank, will choose random file). - * @return string - * @throws Exception - if specified basename doesn't correspond to a registered LOB filename - */ - protected function getLobFile($basename = null) - { - if ($basename === null) { - $basename = array_rand($this->sampleLobFiles); - } - - if (isset($this->sampleLobFiles[$basename])) { - return $this->sampleLobFiles[$basename]; - } else { - throw new Exception("Invalid base LOB filename: $basename"); - } - } - - /** - * Test the LOB results returned in a resultset. - */ - public function testLobResults() - { - - $blob_path = $this->getLobFile('tin_drum.gif'); - $clob_path = $this->getLobFile('tin_drum.txt'); - - $book = BookPeer::doSelectOne(new Criteria()); - - $m1 = new Media(); - $m1->setBook($book); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - $m1_id = $m1->getId(); - - $m1->reload(); - - $img = $m1->getCoverImage(); - $txt = $m1->getExcerpt(); - - $this->assertType('resource', $img, "Expected results of BLOB method to be a resource."); - $this->assertType('string', $txt, "Expected results of CLOB method to be a string."); - - $stat = fstat($img); - $size = $stat['size']; - - $this->assertEquals(filesize($blob_path), $size, "Expected filesize to match stat(blobrsc)"); - $this->assertEquals(filesize($clob_path), strlen($txt), "Expected filesize to match clob strlen"); - } - - /** - * Test to make sure that file pointer is not when it is fetched - * from the object. - * - * This is actually a test for correct behavior and does not completely fix - * the associated ticket (which was resolved wontfix). - * - * This does test the rewind-after-save functionality, however. - * - * @link http://propel.phpdb.org/trac/ticket/531 - */ - public function testLobRepeatRead() - { - $blob_path = $this->getLobFile('tin_drum.gif'); - $clob_path = $this->getLobFile('tin_drum.txt'); - - $book = BookPeer::doSelectOne(new Criteria()); - - $m1 = new Media(); - $m1->setBook($book); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - - $img = $m1->getCoverImage(); - - // 1) Assert that this resource has been rewound. - - $this->assertEquals(0, ftell($img), "Expected position of cursor in file pointer to be 0"); - - // 1) Assert that we've got a valid stream to start with - - $this->assertType('resource', $img, "Expected results of BLOB method to be a resource."); - - // read first 100 bytes - $firstBytes = fread($img, 100); - - $img2 = $m1->getCoverImage(); - $this->assertSame($img, $img2, "Assert that the two resources are the same."); - - // read next 100 bytes - $nextBytes = fread($img, 100); - - $this->assertNotEquals(bin2hex($firstBytes), bin2hex($nextBytes), "Expected the first 100 and next 100 bytes to not be identical."); - } - - /** - * Tests the setting of null LOBs - */ - public function testLobNulls() - { - $book = BookPeer::doSelectOne(new Criteria()); - - $m1 = new Media(); - $m1->setBook($book); - $this->assertTrue($m1->getCoverImage() === null, "Initial LOB value for a new object should be null."); - - $m1->save(); - $m1_id = $m1->getId(); - - $m2 = new Media(); - $m2->setBook($book); - $m2->setCoverImage(null); - $this->assertTrue($m2->getCoverImage() === null, "Setting a LOB to null should cause accessor to return null."); - - $m2->save(); - $m2_id = $m2->getId(); - - $m1->reload(); - $this->assertTrue($m1->getCoverImage() === null, "Default null LOB value should be null after a reload."); - - $m2->reload(); - $this->assertTrue($m2->getCoverImage() === null, "LOB value set to null should be null after a reload."); - } - - /** - * Tests the setting of LOB (BLOB and CLOB) values. - */ - public function testLobSetting() - { - $blob_path = $this->getLobFile('tin_drum.gif'); - $blob2_path = $this->getLobFile('propel.gif'); - - $clob_path = $this->getLobFile('tin_drum.txt'); - $book = BookPeer::doSelectOne(new Criteria()); - - $m1 = new Media(); - $m1->setBook($book); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - $m1_id = $m1->getId(); - - // 1) Assert that we've got a valid stream to start with - $img = $m1->getCoverImage(); - $this->assertType('resource', $img, "Expected results of BLOB method to be a resource."); - - // 2) Test setting a BLOB column with file contents - $m1->setCoverImage(file_get_contents($blob2_path)); - $this->assertType('resource', $m1->getCoverImage(), "Expected to get a resource back after setting BLOB with file contents."); - - // commit those changes & reload - $m1->save(); - - // 3) Verify that we've got a valid resource after reload - $m1->reload(); - $this->assertType('resource', $m1->getCoverImage(), "Expected to get a resource back after setting reloading object."); - - // 4) Test isModified() behavior - $fp = fopen("php://temp", "r+"); - fwrite($fp, file_get_contents($blob2_path)); - - $m1->setCoverImage($fp); - $this->assertTrue($m1->isModified(), "Expected Media object to be modified, despite fact that stream is to same data"); - - // 5) Test external modification of the stream (and re-setting it into the object) - $stream = $m1->getCoverImage(); - fwrite($stream, file_get_contents($blob_path)); // change the contents of the stream - - $m1->setCoverImage($stream); - - $this->assertTrue($m1->isModified(), "Expected Media object to be modified when stream contents changed."); - $this->assertNotEquals(file_get_contents($blob2_path), stream_get_contents($m1->getCoverImage())); - - $m1->save(); - - // 6) Assert that when we call the setter with a stream, that the file in db gets updated. - - $m1->reload(); // start with a fresh copy from db - - // Ensure that object is set up correctly - $this->assertNotEquals(file_get_contents($blob_path), stream_get_contents($m1->getCoverImage()), "The object is not correctly set up to verify the stream-setting test."); - - $fp = fopen($blob_path, "r"); - $m1->setCoverImage($fp); - $m1->save(); - $m1->reload(); // refresh from db - - // Assert that we've updated the db - $this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1->getCoverImage()), "Expected the updated BLOB value after setting with a stream."); - - // 7) Assert that 'w' mode works - - } - - public function testLobSetting_WriteMode() - { - $blob_path = $this->getLobFile('tin_drum.gif'); - $blob2_path = $this->getLobFile('propel.gif'); - - $clob_path = $this->getLobFile('tin_drum.txt'); - $book = BookPeer::doSelectOne(new Criteria()); - - $m1 = new Media(); - $m1->setBook($book); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - - MediaPeer::clearInstancePool(); - - // make sure we have the latest from the db: - $m2 = MediaPeer::retrieveByPK($m1->getId()); - - // now attempt to assign a temporary stream, opened in 'w' mode, to the db - - $stream = fopen("php://memory", 'w'); - fwrite($stream, file_get_contents($blob2_path)); - $m2->setCoverImage($stream); - $m2->save(); - fclose($stream); - - $m2->reload(); - $this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2->getCoverImage()), "Expected contents to match when setting stream w/ 'w' mode"); - - $stream2 = fopen("php://memory", 'w+'); - fwrite($stream2, file_get_contents($blob_path)); - rewind($stream2); - $this->assertEquals(file_get_contents($blob_path), stream_get_contents($stream2), "Expecting setup to be correct"); - - $m2->setCoverImage($stream2); - $m2->save(); - $m2->reload(); - - $this->assertEquals(file_get_contents($blob_path), stream_get_contents($m2->getCoverImage()), "Expected contents to match when setting stream w/ 'w+' mode"); - - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectRelTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectRelTest.php deleted file mode 100644 index 465545560..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectRelTest.php +++ /dev/null @@ -1,352 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedObjectRelTest extends BookstoreEmptyTestBase -{ - - protected function setUp() - { - parent::setUp(); - } - - /** - * Tests one side of a bi-directional setting of many-to-many relationships. - */ - public function testManyToMany_Dir1() - { - $list = new BookClubList(); - $list->setGroupLeader('Archimedes Q. Porter'); - // No save ... - - $book = new Book(); - $book->setTitle( "Jungle Expedition Handbook" ); - $book->setISBN('TEST'); - // No save ... - - $this->assertEquals(0, count($list->getBookListRels()) ); - $this->assertEquals(0, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - - $xref = new BookListRel(); - $xref->setBook($book); - $list->addBookListRel($xref); - - $this->assertEquals(1, count($list->getBookListRels())); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - - $list->save(); - - $this->assertEquals(1, count($list->getBookListRels()) ); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) ); - - } - - /** - * Tests reverse setting of one of many-to-many relationship, with all saves cascaded. - */ - public function testManyToMany_Dir2_Unsaved() - { - $list = new BookClubList(); - $list->setGroupLeader('Archimedes Q. Porter'); - // No save ... - - $book = new Book(); - $book->setTitle( "Jungle Expedition Handbook" ); - $book->setISBN('TEST'); - // No save (yet) ... - - $this->assertEquals(0, count($list->getBookListRels()) ); - $this->assertEquals(0, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - - $xref = new BookListRel(); - $xref->setBookClubList($list); - $book->addBookListRel($xref); - - $this->assertEquals(1, count($list->getBookListRels()) ); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - $book->save(); - - $this->assertEquals(1, count($list->getBookListRels()) ); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) ); - - } - - /** - * Tests reverse setting of relationships, saving one of the objects first. - * @link http://propel.phpdb.org/trac/ticket/508 - */ - public function testManyToMany_Dir2_Saved() - { - $list = new BookClubList(); - $list->setGroupLeader('Archimedes Q. Porter'); - $list->save(); - - $book = new Book(); - $book->setTitle( "Jungle Expedition Handbook" ); - $book->setISBN('TEST'); - // No save (yet) ... - - $this->assertEquals(0, count($list->getBookListRels()) ); - $this->assertEquals(0, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - - // Now set the relationship from the opposite direction. - - $xref = new BookListRel(); - $xref->setBookClubList($list); - $book->addBookListRel($xref); - - $this->assertEquals(1, count($list->getBookListRels()) ); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) ); - $book->save(); - - $this->assertEquals(1, count($list->getBookListRels()) ); - $this->assertEquals(1, count($book->getBookListRels()) ); - $this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) ); - - } - - public function testManyToManyGetterExists() - { - $this->assertTrue(method_exists('BookClubList', 'getBooks'), 'Object generator correcly adds getter for the crossRefFk'); - $this->assertFalse(method_exists('BookClubList', 'getBookClubLists'), 'Object generator correcly adds getter for the crossRefFk'); - } - - public function testManyToManyGetterNewObject() - { - $blc1 = new BookClubList(); - $books = $blc1->getBooks(); - $this->assertTrue($books instanceof PropelObjectCollection, 'getCrossRefFK() returns a Propel collection'); - $this->assertEquals('Book', $books->getModel(), 'getCrossRefFK() returns a collection of the correct model'); - $this->assertEquals(0, count($books), 'getCrossRefFK() returns an empty list for new objects'); - $query = BookQuery::create() - ->filterByTitle('Harry Potter and the Order of the Phoenix'); - $books = $blc1->getBooks($query); - $this->assertEquals(0, count($books), 'getCrossRefFK() accepts a query as first parameter'); - } - - public function testManyToManyGetter() - { - BookstoreDataPopulator::populate(); - $blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs'); - $books = $blc1->getBooks(); - $this->assertTrue($books instanceof PropelObjectCollection, 'getCrossRefFK() returns a Propel collection'); - $this->assertEquals('Book', $books->getModel(), 'getCrossRefFK() returns a collection of the correct model'); - $this->assertEquals(2, count($books), 'getCrossRefFK() returns the correct list of objects'); - $query = BookQuery::create() - ->filterByTitle('Harry Potter and the Order of the Phoenix'); - $books = $blc1->getBooks($query); - $this->assertEquals(1, count($books), 'getCrossRefFK() accepts a query as first parameter'); - } - - public function testManyToManyCounterExists() - { - $this->assertTrue(method_exists('BookClubList', 'countBooks'), 'Object generator correcly adds counter for the crossRefFk'); - $this->assertFalse(method_exists('BookClubList', 'countBookClubLists'), 'Object generator correcly adds counter for the crossRefFk'); - } - - public function testManyToManyCounterNewObject() - { - $blc1 = new BookClubList(); - $nbBooks = $blc1->countBooks(); - $this->assertEquals(0, $nbBooks, 'countCrossRefFK() returns 0 for new objects'); - $query = BookQuery::create() - ->filterByTitle('Harry Potter and the Order of the Phoenix'); - $nbBooks = $blc1->countBooks($query); - $this->assertEquals(0, $nbBooks, 'countCrossRefFK() accepts a query as first parameter'); - } - - public function testManyToManyCounter() - { - BookstoreDataPopulator::populate(); - $blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs'); - $nbBooks = $blc1->countBooks(); - $this->assertEquals(2, $nbBooks, 'countCrossRefFK() returns the correct list of objects'); - $query = BookQuery::create() - ->filterByTitle('Harry Potter and the Order of the Phoenix'); - $nbBooks = $blc1->countBooks($query); - $this->assertEquals(1, $nbBooks, 'countCrossRefFK() accepts a query as first parameter'); - } - - public function testManyToManyAdd() - { - $list = new BookClubList(); - $list->setGroupLeader('Archimedes Q. Porter'); - - $book = new Book(); - $book->setTitle( "Jungle Expedition Handbook" ); - $book->setISBN('TEST'); - - $list->addBook($book); - $this->assertEquals(1, $list->countBooks(), 'addCrossFk() sets the internal collection properly'); - $this->assertEquals(1, $list->countBookListRels(), 'addCrossFk() sets the internal cross reference collection properly'); - - $list->save(); - $this->assertFalse($book->isNew(), 'related object is saved if added'); - $rels = $list->getBookListRels(); - $rel = $rels[0]; - $this->assertFalse($rel->isNew(), 'cross object is saved if added'); - - $list->clearBookListRels(); - $list->clearBooks(); - $books = $list->getBooks(); - $expected = new PropelObjectCollection(array($book)); - $expected->setModel('Book'); - $this->assertEquals($expected, $books, 'addCrossFk() adds the object properly'); - $this->assertEquals(1, $list->countBookListRels()); - } - - - /** - * Test behavior of columns that are implicated in multiple foreign keys. - * @link http://propel.phpdb.org/trac/ticket/228 - */ - public function testMultiFkImplication() - { - BookstoreDataPopulator::populate(); - // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry - $b = new Bookstore(); - $b->setStoreName("Foo!"); - $b->save(); - - $c = new Contest(); - $c->setName("Bookathon Contest"); - $c->save(); - - $bc = new BookstoreContest(); - $bc->setBookstore($b); - $bc->setContest($c); - $bc->save(); - - $c = new Customer(); - $c->setName("Happy Customer"); - $c->save(); - - $bce = new BookstoreContestEntry(); - $bce->setBookstore($b); - $bce->setBookstoreContest($bc); - $bce->setCustomer($c); - $bce->save(); - - $bce->setBookstoreId(null); - - $this->assertNull($bce->getBookstoreContest()); - $this->assertNull($bce->getBookstore()); - } - - /** - * Test the clearing of related object collection. - * @link http://propel.phpdb.org/trac/ticket/529 - */ - public function testClearRefFk() - { - BookstoreDataPopulator::populate(); - $book = new Book(); - $book->setISBN("Foo-bar-baz"); - $book->setTitle("The book title"); - - // No save ... - - $r = new Review(); - $r->setReviewedBy('Me'); - $r->setReviewDate(new DateTime("now")); - - $book->addReview($r); - - // No save (yet) ... - - $this->assertEquals(1, count($book->getReviews()) ); - $book->clearReviews(); - $this->assertEquals(0, count($book->getReviews())); - } - - /** - * This tests to see whether modified objects are being silently overwritten by calls to fk accessor methods. - * @link http://propel.phpdb.org/trac/ticket/509#comment:5 - */ - public function testModifiedObjectOverwrite() - { - BookstoreDataPopulator::populate(); - $author = new Author(); - $author->setFirstName("John"); - $author->setLastName("Public"); - - $books = $author->getBooks(); // empty, of course - $this->assertEquals(0, count($books), "Expected empty collection."); - - $book = new Book(); - $book->setTitle("A sample book"); - $book->setISBN("INITIAL ISBN"); - - $author->addBook($book); - - $author->save(); - - $book->setISBN("MODIFIED ISBN"); - - $books = $author->getBooks(); - $this->assertEquals(1, count($books), "Expected 1 book."); - $this->assertSame($book, $books[0], "Expected the same object to be returned by fk accessor."); - $this->assertEquals("MODIFIED ISBN", $books[0]->getISBN(), "Expected the modified value NOT to have been overwritten."); - } - - public function testFKGetterUseInstancePool() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $author = AuthorPeer::doSelectOne(new Criteria(), $con); - // populate book instance pool - $books = $author->getBooks(null, $con); - $sql = $con->getLastExecutedQuery(); - $author = $books[0]->getAuthor($con); - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'refFK getter uses instance pool if possible'); - } - - public function testRefFKGetJoin() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - PublisherPeer::clearInstancePool(); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $author = AuthorPeer::doSelectOne(new Criteria(), $con); - // populate book instance pool - $books = $author->getBooksJoinPublisher(null, $con); - $sql = $con->getLastExecutedQuery(); - $publisher = $books[0]->getPublisher($con); - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'refFK getter uses instance pool if possible'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectTest.php deleted file mode 100644 index 63dead162..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedObjectTest.php +++ /dev/null @@ -1,1355 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedObjectTest extends BookstoreEmptyTestBase -{ - protected function setUp() - { - parent::setUp(); - require_once 'tools/helpers/bookstore/behavior/TestAuthor.php'; - } - - /** - * Test saving an object after setting default values for it. - */ - public function testSaveWithDefaultValues() - { - // From the schema.xml, I am relying on the following: - // - that 'Penguin' is the default Name for a Publisher - // - that 2001-01-01 is the default ReviewDate for a Review - - // 1) check regular values (VARCHAR) - $pub = new Publisher(); - $pub->setName('Penguin'); - $pub->save(); - $this->assertTrue($pub->getId() !== null, "Expect Publisher to have been saved when default value set."); - - // 2) check date/time values - $review = new Review(); - // note that this is different from how it's represented in schema, but should resolve to same unix timestamp - $review->setReviewDate('2001-01-01'); - $this->assertTrue($review->isModified(), "Expect Review to have been marked 'modified' after default date/time value set."); - - } - - /** - * Test isModified() to be false after setting default value second time - */ - public function testDefaultValueSetTwice() - { - $pub = new Publisher(); - $pub->setName('Penguin'); - $pub->save(); - - $pubId = $pub->getId(); - - PublisherPeer::clearInstancePool(); - - $pub2 = PublisherPeer::retrieveByPK($pubId); - $pub2->setName('Penguin'); - $this->assertFalse($pub2->isModified(), "Expect Publisher to be not modified after setting default value second time."); - } - - public function testHasApplyDefaultValues() - { - $this->assertTrue(method_exists('Publisher', 'applyDefaultValues'), 'Tables with default values should have an applyDefaultValues() method'); - $this->assertFalse(method_exists('Book', 'applyDefaultValues'), 'Tables with no default values should not have an applyDefaultValues() method'); - } - - /** - * Test default return values. - */ - public function testDefaultValues() - { - $r = new Review(); - $this->assertEquals('2001-01-01', $r->getReviewDate('Y-m-d')); - - $this->assertFalse($r->isModified(), "expected isModified() to be false"); - - $acct = new BookstoreEmployeeAccount(); - $this->assertEquals(true, $acct->getEnabled()); - $this->assertFalse($acct->isModified()); - - $acct->setLogin("testuser"); - $acct->setPassword("testpass"); - $this->assertTrue($acct->isModified()); - } - - /** - * Tests the use of default expressions and the reloadOnInsert and reloadOnUpdate attributes. - * - * @link http://propel.phpdb.org/trac/ticket/378 - * @link http://propel.phpdb.org/trac/ticket/555 - */ - public function testDefaultExpresions() - { - if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) { - $this->markTestSkipped("Cannot test default expressions with SQLite"); - } - - $b = new Bookstore(); - $b->setStoreName("Foo!"); - $b->save(); - - $employee = new BookstoreEmployee(); - $employee->setName("Johnny Walker"); - - $acct = new BookstoreEmployeeAccount(); - $acct->setBookstoreEmployee($employee); - $acct->setLogin("test-login"); - - $this->assertNull($acct->getCreated(), "Expected created column to be NULL."); - $this->assertNull($acct->getAuthenticator(), "Expected authenticator column to be NULL."); - - $acct->save(); - - $acct = BookstoreEmployeeAccountPeer::retrieveByPK($acct->getEmployeeId()); - - $this->assertNotNull($acct->getAuthenticator(), "Expected a valid (non-NULL) authenticator column after save."); - $this->assertEquals('Password', $acct->getAuthenticator(), "Expected authenticator='Password' after save."); - $this->assertNotNull($acct->getCreated(), "Expected a valid date after retrieving saved object."); - - $now = new DateTime("now"); - $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d")); - - $acct->setCreated($now); - $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d")); - - // Unfortunately we can't really test the conjunction of reloadOnInsert and reloadOnUpdate when using just - // default values. (At least not in a cross-db way.) - } - - /** - * Tests the use of default expressions and the reloadOnInsert attribute. - * - * @link http://propel.phpdb.org/trac/ticket/378 - * @link http://propel.phpdb.org/trac/ticket/555 - */ - public function testDefaultExpresions_ReloadOnInsert() - { - if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) { - $this->markTestSkipped("Cannot test default date expressions with SQLite"); - } - - // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry - - $b = new Bookstore(); - $b->setStoreName("Barnes & Noble"); - $b->save(); - - $c = new Contest(); - $c->setName("Bookathon Contest"); - $c->save(); - - $bc = new BookstoreContest(); - $bc->setBookstore($b); - $bc->setContest($c); - $bc->save(); - - $c = new Customer(); - $c->setName("Happy Customer"); - $c->save(); - - $bce = new BookstoreContestEntry(); - $bce->setBookstore($b); - $bce->setBookstoreContest($bc); - $bce->setCustomer($c); - $bce->save(); - - $this->assertNotNull($bce->getEntryDate(), "Expected a non-null entry_date after save."); - } - - /** - * Tests the overriding reloadOnInsert at runtime. - * - * @link http://propel.phpdb.org/trac/ticket/378 - * @link http://propel.phpdb.org/trac/ticket/555 - */ - public function testDefaultExpresions_ReloadOnInsert_Override() - { - if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) { - $this->markTestSkipped("Cannot test default date expressions with SQLite"); - } - - // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry - $b = new Bookstore(); - $b->setStoreName("Barnes & Noble"); - $b->save(); - - $c = new Contest(); - $c->setName("Bookathon Contest"); - $c->save(); - - $bc = new BookstoreContest(); - $bc->setBookstore($b); - $bc->setContest($c); - $bc->save(); - - $c = new Customer(); - $c->setName("Happy Customer"); - $c->save(); - - $bce = new BookstoreContestEntry(); - $bce->setBookstore($b); - $bce->setBookstoreContest($bc); - $bce->setCustomer($c); - $bce->save(null, $skipReload=true); - - $this->assertNull($bce->getEntryDate(), "Expected a NULL entry_date after save."); - } - - /** - * Tests the use of default expressions and the reloadOnUpdate attribute. - * - * @link http://propel.phpdb.org/trac/ticket/555 - */ - public function testDefaultExpresions_ReloadOnUpdate() - { - $b = new Bookstore(); - $b->setStoreName("Foo!"); - $b->save(); - - $sale = new BookstoreSale(); - $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria())); - $sale->setSaleName("Spring Sale"); - $sale->save(); - - // Expect that default values are set, but not default expressions - $this->assertNull($sale->getDiscount(), "Expected discount to be NULL."); - - $sale->setSaleName("Winter Clearance"); - $sale->save(); - // Since reloadOnUpdate = true, we expect the discount to be set now. - - $this->assertNotNull($sale->getDiscount(), "Expected discount to be non-NULL after save."); - } - - /** - * Tests the overriding reloadOnUpdate at runtime. - * - * @link http://propel.phpdb.org/trac/ticket/378 - * @link http://propel.phpdb.org/trac/ticket/555 - */ - public function testDefaultExpresions_ReloadOnUpdate_Override() - { - $b = new Bookstore(); - $b->setStoreName("Foo!"); - $b->save(); - - $sale = new BookstoreSale(); - $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria())); - $sale->setSaleName("Spring Sale"); - $sale->save(); - - // Expect that default values are set, but not default expressions - $this->assertNull($sale->getDiscount(), "Expected discount to be NULL."); - - $sale->setSaleName("Winter Clearance"); - $sale->save(null, $skipReload=true); - - // Since reloadOnUpdate = true, we expect the discount to be set now. - - $this->assertNull($sale->getDiscount(), "Expected NULL value for discount after save."); - } - - /** - * Test the behavior of date/time/values. - * This requires that the model was built with propel.useDateTimeClass=true. - */ - public function testTemporalValues_PreEpoch() - { - $r = new Review(); - - $preEpochDate = new DateTime('1602-02-02'); - - $r->setReviewDate($preEpochDate); - - $this->assertEquals('1602-02-02', $r->getReviewDate(null)->format("Y-m-d")); - - $r->setReviewDate('1702-02-02'); - - $this->assertTrue($r->isModified()); - - $this->assertEquals('1702-02-02', $r->getReviewDate(null)->format("Y-m-d")); - - // Now test for setting null - $r->setReviewDate(null); - $this->assertNull($r->getReviewDate()); - - } - - /** - * Test setting invalid date/time. - */ - public function testSetTemporalValue_Invalid() - { - $this->markTestSkipped(); - // FIXME - Figure out why this doesn't work (causes a PHP ERROR instead of throwing Exception) in - // the Phing+PHPUnit context - $r = new Review(); - try { - $r->setReviewDate("Invalid Date"); - $this->fail("Expected PropelException when setting date column w/ invalid date"); - } catch (PropelException $x) { - print "Caught expected PropelException: " . $x->__toString(); - } - } - - /** - * Test setting TIMESTAMP columns w/ unix int timestamp. - */ - public function testTemporalValues_Unix() - { - $store = new Bookstore(); - $store->setStoreName("test"); - $store->setStoreOpenTime(strtotime('12:55')); - $store->save(); - $this->assertEquals('12:55', $store->getStoreOpenTime(null)->format('H:i')); - - $acct = new BookstoreEmployeeAccount(); - $acct->setCreated(time()); - $this->assertEquals(date('Y-m-d H:i'), $acct->getCreated('Y-m-d H:i')); - - $review = new Review(); - $review->setReviewDate(time()); - $this->assertEquals(date('Y-m-d'), $review->getReviewDate('Y-m-d')); - } - - /** - * Test setting empty temporal values. - * @link http://propel.phpdb.org/trac/ticket/586 - */ - public function testTemporalValues_Empty() - { - $review = new Review(); - $review->setReviewDate(''); - $this->assertNull($review->getReviewDate()); - } - - /** - * Test setting TIME columns. - */ - public function testTemporalValues_TimeSetting() - { - $store = new Bookstore(); - $store->setStoreName("test"); - $store->setStoreOpenTime("12:55"); - $store->save(); - - $store = new Bookstore(); - $store->setStoreName("test2"); - $store->setStoreOpenTime(new DateTime("12:55")); - $store->save(); - } - - /** - * Test setting TIME columns. - */ - public function testTemporalValues_DateSetting() - { - BookstoreDataPopulator::populate(); - - $r = new Review(); - $r->setBook(BookPeer::doSelectOne(new Criteria())); - $r->setReviewDate(new DateTime('1999-12-20')); - $r->setReviewedBy("Hans"); - $r->setRecommended(false); - $r->save(); - } - - /** - * Testing creating & saving new object & instance pool. - */ - public function testObjectInstances_New() - { - $emp = new BookstoreEmployee(); - $emp->setName(md5(microtime())); - $emp->save(); - $id = $emp->getId(); - - $retrieved = BookstoreEmployeePeer::retrieveByPK($id); - $this->assertSame($emp, $retrieved, "Expected same object (from instance pool)"); - } - - /** - * - */ - public function testObjectInstances_Fkeys() - { - // Establish a relationship between one employee and account - // and then change the employee_id and ensure that the account - // is not pulling the old employee. - - $pub1 = new Publisher(); - $pub1->setName('Publisher 1'); - $pub1->save(); - - $pub2 = new Publisher(); - $pub2->setName('Publisher 2'); - $pub2->save(); - - $book = new Book(); - $book->setTitle("Book Title"); - $book->setISBN("1234"); - $book->setPublisher($pub1); - $book->save(); - - $this->assertSame($pub1, $book->getPublisher()); - - // now change values behind the scenes - $con = Propel::getConnection(BookstoreEmployeeAccountPeer::DATABASE_NAME); - $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET " - . " publisher_id = " . $pub2->getId() - . " WHERE id = " . $book->getId()); - - - $book2 = BookPeer::retrieveByPK($book->getId()); - $this->assertSame($book, $book2, "Expected same book object instance"); - - $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have OLD publisher id before reload()"); - - $book->reload(); - - $this->assertEquals($pub2->getId(), $book->getPublisherId(), "Expected book to have new publisher id"); - $this->assertSame($pub2, $book->getPublisher(), "Expected book to have new publisher object associated."); - - // Now let's set it back, just to be double sure ... - - $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET " - . " publisher_id = " . $pub1->getId() - . " WHERE id = " . $book->getId()); - - $book->reload(); - - $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have old publisher id (again)."); - $this->assertSame($pub1, $book->getPublisher(), "Expected book to have old publisher object associated (again)."); - - } - - /** - * Test the effect of typecast on primary key values and instance pool retrieval. - */ - public function testObjectInstancePoolTypecasting() - { - $reader = new BookReader(); - $reader->setName("Tester"); - $reader->save(); - $readerId = $reader->getId(); - - $book = new Book(); - $book->setTitle("BookTest"); - $book->setISBN("TEST"); - $book->save(); - $bookId = $book->getId(); - - $opinion = new BookOpinion(); - $opinion->setBookId((string)$bookId); - $opinion->setReaderId((string)$readerId); - $opinion->setRating(5); - $opinion->setRecommendToFriend(false); - $opinion->save(); - - - $opinion2 = BookOpinionPeer::retrieveByPK($bookId, $readerId); - - $this->assertSame($opinion, $opinion2, "Expected same object to be retrieved from differently type-casted primary key values."); - - } - - /** - * Test the reload() method. - */ - public function testReload() - { - BookstoreDataPopulator::populate(); - $a = AuthorPeer::doSelectOne(new Criteria()); - - $origName = $a->getFirstName(); - - $a->setFirstName(md5(time())); - - $this->assertNotEquals($origName, $a->getFirstName()); - $this->assertTrue($a->isModified()); - - $a->reload(); - - $this->assertEquals($origName, $a->getFirstName()); - $this->assertFalse($a->isModified()); - - } - - /** - * Test reload(deep=true) method. - */ - public function testReloadDeep() - { - BookstoreDataPopulator::populate(); - - // arbitrary book - $b = BookPeer::doSelectOne(new Criteria()); - - // arbitrary, different author - $c = new Criteria(); - $c->add(AuthorPeer::ID, $b->getAuthorId(), Criteria::NOT_EQUAL); - $a = AuthorPeer::doSelectOne($c); - - $origAuthor = $b->getAuthor(); - - $b->setAuthor($a); - - $this->assertNotEquals($origAuthor, $b->getAuthor(), "Expected just-set object to be different from obj from DB"); - $this->assertTrue($b->isModified()); - - $b->reload($deep=true); - - $this->assertEquals($origAuthor, $b->getAuthor(), "Expected object in DB to be restored"); - $this->assertFalse($a->isModified()); - } - - /** - * Test saving an object and getting correct number of affected rows from save(). - * This includes tests of cascading saves to fk-related objects. - */ - public function testSaveReturnValues() - { - - $author = new Author(); - $author->setFirstName("Mark"); - $author->setLastName("Kurlansky"); - // do not save - - $pub = new Publisher(); - $pub->setName("Penguin Books"); - // do not save - - $book = new Book(); - $book->setTitle("Salt: A World History"); - $book->setISBN("0142001619"); - $book->setAuthor($author); - $book->setPublisher($pub); - - $affected = $book->save(); - $this->assertEquals(3, $affected, "Expected 3 affected rows when saving book + publisher + author."); - - // change nothing ... - $affected = $book->save(); - $this->assertEquals(0, $affected, "Expected 0 affected rows when saving already-saved book."); - - // modify the book (UPDATE) - $book->setTitle("Salt A World History"); - $affected = $book->save(); - $this->assertEquals(1, $affected, "Expected 1 affected row when saving modified book."); - - // modify the related author - $author->setLastName("Kurlanski"); - $affected = $book->save(); - $this->assertEquals(1, $affected, "Expected 1 affected row when saving book with updated author."); - - // modify both the related author and the book - $author->setLastName("Kurlansky"); - $book->setTitle("Salt: A World History"); - $affected = $book->save(); - $this->assertEquals(2, $affected, "Expected 2 affected rows when saving updated book with updated author."); - - } - - /** - * Test deleting an object using the delete() method. - */ - public function testDelete() - { - BookstoreDataPopulator::populate(); - - // 1) grab an arbitrary object - $book = BookPeer::doSelectOne(new Criteria()); - $bookId = $book->getId(); - - // 2) delete it - $book->delete(); - - // 3) make sure it can't be save()d now that it's deleted - try { - $book->setTitle("Will Fail"); - $book->save(); - $this->fail("Expect an exception to be thrown when attempting to save() a deleted object."); - } catch (PropelException $e) {} - - // 4) make sure that it doesn't exist in db - $book = BookPeer::retrieveByPK($bookId); - $this->assertNull($book, "Expect NULL from retrieveByPK on deleted Book."); - - } - - /** - * - */ - public function testNoColsModified() - { - $e1 = new BookstoreEmployee(); - $e1->setName('Employee 1'); - - $e2 = new BookstoreEmployee(); - $e2->setName('Employee 2'); - - $super = new BookstoreEmployee(); - // we don't know who the supervisor is yet - $super->addSubordinate($e1); - $super->addSubordinate($e2); - - $affected = $super->save(); - - } - - /** - * Tests new one-to-one functionality. - */ - public function testOneToOne() - { - BookstoreDataPopulator::populate(); - - $emp = BookstoreEmployeePeer::doSelectOne(new Criteria()); - - $acct = new BookstoreEmployeeAccount(); - $acct->setBookstoreEmployee($emp); - $acct->setLogin("testuser"); - $acct->setPassword("testpass"); - - $this->assertSame($emp->getBookstoreEmployeeAccount(), $acct, "Expected same object instance."); - } - - /** - * Test the type sensitivity of the resturning columns. - * - */ - public function testTypeSensitive() - { - BookstoreDataPopulator::populate(); - - $book = BookPeer::doSelectOne(new Criteria()); - - $r = new Review(); - $r->setReviewedBy("testTypeSensitive Tester"); - $r->setReviewDate(time()); - $r->setBook($book); - $r->setRecommended(true); - $r->save(); - - $id = $r->getId(); - unset($r); - - // clear the instance cache to force reload from database. - ReviewPeer::clearInstancePool(); - BookPeer::clearInstancePool(); - - // reload and verify that the types are the same - $r2 = ReviewPeer::retrieveByPK($id); - - $this->assertType('integer', $r2->getId(), "Expected getId() to return an integer."); - $this->assertType('string', $r2->getReviewedBy(), "Expected getReviewedBy() to return a string."); - $this->assertType('boolean', $r2->getRecommended(), "Expected getRecommended() to return a boolean."); - $this->assertType('Book', $r2->getBook(), "Expected getBook() to return a Book."); - $this->assertType('float', $r2->getBook()->getPrice(), "Expected Book->getPrice() to return a float."); - $this->assertType('DateTime', $r2->getReviewDate(null), "Expected Book->getReviewDate() to return a DateTime."); - - } - - /** - * This is a test for expected exceptions when saving UNIQUE. - * See http://propel.phpdb.org/trac/ticket/2 - */ - public function testSaveUnique() - { - // The whole test is in a transaction, but this test needs real transactions - $this->con->commit(); - - $emp = new BookstoreEmployee(); - $emp->setName(md5(microtime())); - - $acct = new BookstoreEmployeeAccount(); - $acct->setBookstoreEmployee($emp); - $acct->setLogin("foo"); - $acct->setPassword("bar"); - $acct->save(); - - // now attempt to create a new acct - $acct2 = $acct->copy(); - - try { - $acct2->save(); - $this->fail("Expected PropelException in first attempt to save object with duplicate value for UNIQUE constraint."); - } catch (Exception $x) { - try { - // attempt to save it again - $acct3 = $acct->copy(); - $acct3->save(); - $this->fail("Expected PropelException in second attempt to save object with duplicate value for UNIQUE constraint."); - } catch (Exception $x) { - // this is expected. - } - // now let's double check that it can succeed if we're not violating the constraint. - $acct3->setLogin("foo2"); - $acct3->save(); - } - - $this->con->beginTransaction(); - } - - /** - * Test for correct reporting of isModified(). - */ - public function testIsModified() - { - // 1) Basic test - - $a = new Author(); - $a->setFirstName("John"); - $a->setLastName("Doe"); - $a->setAge(25); - - $this->assertTrue($a->isModified(), "Expected Author to be modified after setting values."); - - $a->save(); - - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values."); - - // 2) Test behavior with setting vars of different types - - // checking setting int col to string val - $a->setAge('25'); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after setting int column to string-cast of same value."); - - $a->setFirstName("John2"); - $this->assertTrue($a->isModified(), "Expected Author to be modified after changing string column value."); - - // checking setting string col to int val - $a->setFirstName("1"); - $a->save(); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values."); - - $a->setFirstName(1); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after setting string column to int-cast of same value."); - - // 3) Test for appropriate behavior of NULL - - // checking "" -> NULL - $a->setFirstName(""); - $a->save(); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values."); - - $a->setFirstName(null); - $this->assertTrue($a->isModified(), "Expected Author to be modified after changing empty string column value to NULL."); - - $a->setFirstName("John"); - $a->setAge(0); - $a->save(); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values."); - - $a->setAge(null); - $this->assertTrue($a->isModified(), "Expected Author to be modified after changing 0-value int column to NULL."); - - $a->save(); - $this->assertFalse($a->isModified(), "Expected Author to be unmodified after saving set values."); - - $a->setAge(0); - $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL-value int column to 0."); - - } - - /** - * Test the BaseObject#equals(). - */ - public function testEquals() - { - BookstoreDataPopulator::populate(); - - $b = BookPeer::doSelectOne(new Criteria()); - $c = new Book(); - $c->setId($b->getId()); - $this->assertTrue($b->equals($c), "Expected Book objects to be equal()"); - - $a = new Author(); - $a->setId($b->getId()); - $this->assertFalse($b->equals($a), "Expected Book and Author with same primary key NOT to match."); - } - - /** - * Test checking for non-default values. - * @see http://propel.phpdb.org/trac/ticket/331 - */ - public function testHasOnlyDefaultValues() - { - $emp = new BookstoreEmployee(); - $emp->setName(md5(microtime())); - - $acct2 = new BookstoreEmployeeAccount(); - - $acct = new BookstoreEmployeeAccount(); - $acct->setBookstoreEmployee($emp); - $acct->setLogin("foo"); - $acct->setPassword("bar"); - $acct->save(); - - $this->assertFalse($acct->isModified(), "Expected BookstoreEmployeeAccount NOT to be modified after save()."); - - $acct->setEnabled(true); - $acct->setPassword($acct2->getPassword()); - - $this->assertTrue($acct->isModified(), "Expected BookstoreEmployeeAccount to be modified after setting default values."); - - $this->assertTrue($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to not have only default values."); - - $acct->setPassword("bar"); - $this->assertFalse($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to have at one non-default value after setting one value to non-default."); - - // Test a default date/time value - $r = new Review(); - $r->setReviewDate(new DateTime("now")); - $this->assertFalse($r->hasOnlyDefaultValues()); - } - - public function testDefaultFkColVal() - { - BookstoreDataPopulator::populate(); - - $sale = new BookstoreSale(); - $this->assertEquals(1, $sale->getBookstoreId(), "Expected BookstoreSale object to have a default bookstore_id of 1."); - - $bookstore = BookstorePeer::doSelectOne(new Criteria()); - - $sale->setBookstore($bookstore); - $this->assertEquals($bookstore->getId(), $sale->getBookstoreId(), "Expected FK id to have changed when assigned a valid FK."); - - $sale->setBookstore(null); - $this->assertEquals(1, $sale->getBookstoreId(), "Expected BookstoreSale object to have reset to default ID."); - - $sale->setPublisher(null); - $this->assertEquals(null, $sale->getPublisherId(), "Expected BookstoreSale object to have reset to NULL publisher ID."); - } - - public function testCountRefFk() - { - $book = new Book(); - $book->setTitle("Test Book"); - $book->setISBN("TT-EE-SS-TT"); - - $num = 5; - - for ($i=2; $i < $num + 2; $i++) { - $r = new Review(); - $r->setReviewedBy('Hans ' . $num); - $dt = new DateTime("now"); - $dt->modify("-".$i." weeks"); - $r->setReviewDate($dt); - $r->setRecommended(($i % 2) == 0); - $book->addReview($r); - } - - $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num"); - $this->assertEquals($num, count($book->getReviews()), "Expected getReviews to return $num reviews"); - - $book->save(); - - BookPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - - $book = BookPeer::retrieveByPK($book->getId()); - $this->assertEquals($num, $book->countReviews(), "Expected countReviews() to return $num (after save)"); - $this->assertEquals($num, count($book->getReviews()), "Expected getReviews() to return $num (after save)"); - - // Now set different criteria and expect different results - $c = new Criteria(); - $c->add(ReviewPeer::RECOMMENDED, false); - $this->assertEquals(floor($num/2), $book->countReviews($c), "Expected " . floor($num/2) . " results from countReviews(recomm=false)"); - - // Change Criteria, run again -- expect different. - $c = new Criteria(); - $c->add(ReviewPeer::RECOMMENDED, true); - $this->assertEquals(ceil($num/2), count($book->getReviews($c)), "Expected " . ceil($num/2) . " results from getReviews(recomm=true)"); - - $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num with new empty Criteria"); - } - - /** - * Test copyInto method. - */ - public function testCopyInto_Deep() - { - BookstoreDataPopulator::populate(); - - // Test a "normal" object - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Harry%', Criteria::LIKE); - - $book = BookPeer::doSelectOne($c); - $reviews = $book->getReviews(); - - $b2 = $book->copy(true); - $this->assertType('Book', $b2); - $this->assertNull($b2->getId()); - - $r2 = $b2->getReviews(); - - $this->assertEquals(count($reviews), count($r2)); - - // Test a one-to-one object - $emp = BookstoreEmployeePeer::doSelectOne(new Criteria()); - $e2 = $emp->copy(true); - - $this->assertType('BookstoreEmployee', $e2); - $this->assertNull($e2->getId()); - - $this->assertEquals($emp->getBookstoreEmployeeAccount()->getLogin(), $e2->getBookstoreEmployeeAccount()->getLogin()); - } - - /** - * Test copying when an object has composite primary key. - * @link http://propel.phpdb.org/trac/ticket/618 - */ - public function testCopy_CompositePK() - { - $br = new BookReader(); - $br->setName("TestReader"); - $br->save(); - $br->copy(); - - $b = new Book(); - $b->setTitle("TestBook"); - $b->setISBN("XX-XX-XX-XX"); - $b->save(); - - $op = new BookOpinion(); - $op->setBookReader($br); - $op->setBook($b); - $op->setRating(10); - $op->setRecommendToFriend(true); - $op->save(); - - - $br2 = $br->copy(true); - - $this->assertNull($br2->getId()); - - $opinions = $br2->getBookOpinions(); - $this->assertEquals(1, count($opinions), "Expected to have a related BookOpinion after copy()"); - - // We DO expect the reader_id to be null - $this->assertNull($opinions[0]->getReaderId()); - // but we DO NOT expect the book_id to be null - $this->assertEquals($op->getBookId(), $opinions[0]->getBookId()); - } - - public function testToArray() - { - $b = new Book(); - $b->setTitle('Don Juan'); - - $arr1 = $b->toArray(); - $expectedKeys = array( - 'Id', - 'Title', - 'ISBN', - 'Price', - 'PublisherId', - 'AuthorId' - ); - $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() returns an associative array with BasePeer::TYPE_PHPNAME keys by default'); - $this->assertEquals('Don Juan', $arr1['Title'], 'toArray() returns an associative array representation of the object'); - } - - public function testToArrayKeyType() - { - $b = new Book(); - $b->setTitle('Don Juan'); - - $arr1 = $b->toArray(BasePeer::TYPE_COLNAME); - $expectedKeys = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID - ); - $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() accepts a $keyType parameter to change the result keys'); - $this->assertEquals('Don Juan', $arr1[BookPeer::TITLE], 'toArray() returns an associative array representation of the object'); - } - - /** - * Test the toArray() method with new lazyLoad param. - * @link http://propel.phpdb.org/trac/ticket/527 - */ - public function testToArrayLazyLoad() - { - BookstoreDataPopulator::populate(); - - $c = new Criteria(); - $c->add(MediaPeer::COVER_IMAGE, null, Criteria::NOT_EQUAL); - $c->add(MediaPeer::EXCERPT, null, Criteria::NOT_EQUAL); - - $m = MediaPeer::doSelectOne($c); - if ($m === null) { - $this->fail("Test requires at least one media row w/ cover_image and excerpt NOT NULL"); - } - - $arr1 = $m->toArray(BasePeer::TYPE_COLNAME); - $this->assertNotNull($arr1[MediaPeer::COVER_IMAGE]); - $this->assertType('resource', $arr1[MediaPeer::COVER_IMAGE]); - - $arr2 = $m->toArray(BasePeer::TYPE_COLNAME, false); - $this->assertNull($arr2[MediaPeer::COVER_IMAGE]); - $this->assertNull($arr2[MediaPeer::EXCERPT]); - - $diffKeys = array_keys(array_diff($arr1, $arr2)); - - $expectedDiff = array(MediaPeer::COVER_IMAGE, MediaPeer::EXCERPT); - - $this->assertEquals($expectedDiff, $diffKeys); - } - - public function testToArrayIncludeForeignObjects() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - PublisherPeer::clearInstancePool(); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Don Juan'); - $books = BookPeer::doSelectJoinAuthor($c); - $book = $books[0]; - - $arr1 = $book->toArray(BasePeer::TYPE_PHPNAME, null, true); - $expectedKeys = array( - 'Id', - 'Title', - 'ISBN', - 'Price', - 'PublisherId', - 'AuthorId', - 'Author' - ); - $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() can return sub arrays for hydrated related objects'); - $this->assertEquals('George', $arr1['Author']['FirstName'], 'toArray() can return sub arrays for hydrated related objects'); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Don Juan'); - $books = BookPeer::doSelectJoinAll($c); - $book = $books[0]; - - $arr2 = $book->toArray(BasePeer::TYPE_PHPNAME, null, true); - $expectedKeys = array( - 'Id', - 'Title', - 'ISBN', - 'Price', - 'PublisherId', - 'AuthorId', - 'Publisher', - 'Author' - ); - $this->assertEquals($expectedKeys, array_keys($arr2), 'toArray() can return sub arrays for hydrated related objects'); - } - - /** - * Test regexp validator for ticket:542 - * @link http://propel.phpdb.org/trac/ticket/542 - */ - public function testRegexValidator() - { - $b = new Bookstore(); - $b->setWebsite("http://this.is.valid.com/foo.bar"); - $res = $b->validate(); - $this->assertTrue($res, "Expected URL to validate"); - } - - /** - * Test that setting the auto-increment primary key will result in exception. - */ - public function testSettingAutoIncrementPK() - { - // The whole test is in a transaction, but this test needs real transactions - $this->con->commit(); - - $b = new Bookstore(); - $b->setId(1); - $b->setStoreName("Test"); - try { - $b->save(); - $this->fail("Expected setting auto-increment primary key to result in Exception"); - } catch (Exception $x) { - $this->assertType('PropelException', $x); - } - - // ... but we should silently ignore NULL values, since these are really - // the same as "not set" in PHP world. - $b = new Bookstore(); - $b->setId(null); - $b->setStoreName("Test2"); - try { - $b->save(); - } catch (Exception $x) { - $this->fail("Expected no exception when setting auto-increment primary key to NULL"); - } - // success ... - - $this->con->beginTransaction(); - } - - /** - * Checks wether we are allowed to specify the primary key on a - * table with allowPkInsert=true set - * - * saves the object, gets it from data-source again and then compares - * them for equality (thus the instance pool is also checked) - */ - public function testAllowPkInsertOnIdMethodNativeTable() - { - $cu = new Customer; - $cu->setPrimaryKey(100000); - $cu->save(); - - $this->assertEquals(100000, $cu->getPrimaryKey()); - - $cu2 = CustomerPeer::retrieveByPk(100000); - - $this->assertSame($cu, $cu2); - } - /** - * Checks if it is allowed to save new, empty objects with a auto increment column - */ - public function testAllowEmptyWithAutoIncrement() - { - $bookreader = new BookReader(); - $bookreader->save(); - - $this->assertFalse($bookreader->isNew() ); - } - - /** - * Test foreign key relationships based on references to unique cols but not PK. - * @link http://propel.phpdb.org/trac/ticket/691 - */ - public function testUniqueFkRel() - { - $employee = new BookstoreEmployee(); - $employee->setName("Johnny Walker"); - - $acct = new BookstoreEmployeeAccount(); - $acct->setBookstoreEmployee($employee); - $acct->setLogin("test-login"); - $acct->save(); - $acctId = $acct->getEmployeeId(); - - $al = new AcctAuditLog(); - $al->setBookstoreEmployeeAccount($acct); - $al->save(); - $alId = $al->getId(); - - BookstoreEmployeePeer::clearInstancePool(); - BookstoreEmployeeAccountPeer::clearInstancePool(); - AcctAuditLogPeer::clearInstancePool(); - - $al2 = AcctAuditLogPeer::retrieveByPK($alId); - /* @var $al2 AcctAuditLog */ - $mapacct = $al2->getBookstoreEmployeeAccount(); - $lookupacct = BookstoreEmployeeAccountPeer::retrieveByPK($acctId); - - $logs = $lookupacct->getAcctAuditLogs(); - - $this->assertTrue(count($logs) == 1, "Expected 1 audit log result."); - $this->assertEquals($logs[0]->getId(), $al->getId(), "Expected returned audit log to match created audit log."); - } - - public function testIsPrimaryKeyNull() - { - $b = new Book(); - $this->assertTrue($b->isPrimaryKeyNull()); - $b->setPrimaryKey(123); - $this->assertFalse($b->isPrimaryKeyNull()); - $b->setPrimaryKey(null); - $this->assertTrue($b->isPrimaryKeyNull()); - } - - public function testIsPrimaryKeyNullCompmosite() - { - $b = new BookOpinion(); - $this->assertTrue($b->isPrimaryKeyNull()); - $b->setPrimaryKey(array(123, 456)); - $this->assertFalse($b->isPrimaryKeyNull()); - $b->setPrimaryKey(array(123, null)); - $this->assertFalse($b->isPrimaryKeyNull()); - $b->setPrimaryKey(array(null, 456)); - $this->assertFalse($b->isPrimaryKeyNull()); - $b->setPrimaryKey(array(null, null)); - $this->assertTrue($b->isPrimaryKeyNull()); - } - - public function testAddPrimaryString() - { - $this->assertFalse(method_exists('Author', '__toString'), 'addPrimaryString() does not add a __toString() method if no column has the primaryString attribute'); - $this->assertTrue(method_exists('Book', '__toString'), 'addPrimaryString() adds a __toString() method if a column has the primaryString attribute'); - $book = new Book(); - $book->setTitle('foo'); - $this->assertEquals((string) $book, 'foo', 'addPrimaryString() adds a __toString() method returning the value of the the first column where primaryString is true'); - } - - public function testPreInsert() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $this->assertEquals('PreInsertedFirstname', $author->getFirstName()); - } - - public function testPreUpdate() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $author->setNew(false); - $author->save(); - $this->assertEquals('PreUpdatedFirstname', $author->getFirstName()); - } - - public function testPostInsert() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $this->assertEquals('PostInsertedLastName', $author->getLastName()); - } - - public function testPostUpdate() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $author->setNew(false); - $author->save(); - $this->assertEquals('PostUpdatedLastName', $author->getLastName()); - } - - public function testPreSave() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $this->assertEquals('pre@save.com', $author->getEmail()); - } - - public function testPreSaveFalse() - { - $con = Propel::getConnection(AuthorPeer::DATABASE_NAME); - $author = new TestAuthorSaveFalse(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $res = $author->save($con); - $this->assertEquals(0, $res); - $this->assertEquals('pre@save.com', $author->getEmail()); - $this->assertNotEquals(115, $author->getAge()); - $this->assertTrue($author->isNew()); - $this->assertEquals(1, $con->getNestedTransactionCount()); - } - - public function testPostSave() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $this->assertEquals(115, $author->getAge()); - } - - public function testPreDelete() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $author->delete(); - $this->assertEquals("Pre-Deleted", $author->getFirstName()); - } - - public function testPreDeleteFalse() - { - $con = Propel::getConnection(AuthorPeer::DATABASE_NAME); - $author = new TestAuthorDeleteFalse(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save($con); - $author->delete($con); - $this->assertEquals("Pre-Deleted", $author->getFirstName()); - $this->assertNotEquals("Post-Deleted", $author->getLastName()); - $this->assertFalse($author->isDeleted()); - $this->assertEquals(1, $con->getNestedTransactionCount()); - } - - public function testPostDelete() - { - $author = new TestAuthor(); - $author->setFirstName("bogus"); - $author->setLastName("Lastname"); - $author->save(); - $author->delete(); - $this->assertEquals("Post-Deleted", $author->getLastName()); - } - - public function testMagicVirtualColumnGetter() - { - $book = new Book(); - $book->setVirtualColumn('Foo', 'bar'); - $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns'); - $book = new Book(); - $book->setVirtualColumn('foo', 'bar'); - $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns starting with a lowercase character'); - } - - public static function conditionsForTestReadOnly() - { - return array( - array('reload'), - array('delete'), - array('save'), - array('doSave'), - ); - } - - /** - * @dataProvider conditionsForTestReadOnly - */ - public function testReadOnly($method) - { - $cv = new ContestView(); - $this->assertFalse(method_exists($cv, $method), 'readOnly tables end up with no ' . $method . ' method in the generated object class'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoDeleteTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoDeleteTest.php deleted file mode 100644 index b68a53ba4..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoDeleteTest.php +++ /dev/null @@ -1,545 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedPeerDoDeleteTest extends BookstoreEmptyTestBase -{ - protected function setUp() - { - parent::setUp(); - BookstoreDataPopulator::populate(); - } - - /** - * Test ability to delete multiple rows via single Criteria object. - */ - public function testDoDelete_MultiTable() { - - $selc = new Criteria(); - $selc->add(BookPeer::TITLE, "Harry Potter and the Order of the Phoenix"); - $hp = BookPeer::doSelectOne($selc); - - // print "Attempting to delete [multi-table] by found pk: "; - $c = new Criteria(); - $c->add(BookPeer::ID, $hp->getId()); - // The only way for multi-delete to work currently - // is to specify the author_id and publisher_id (i.e. the fkeys - // have to be in the criteria). - $c->add(AuthorPeer::ID, $hp->getAuthorId()); - $c->add(PublisherPeer::ID, $hp->getPublisherId()); - $c->setSingleRecord(true); - BookPeer::doDelete($c); - - //print_r(AuthorPeer::doSelect(new Criteria())); - - // check to make sure the right # of records was removed - $this->assertEquals(3, count(AuthorPeer::doSelect(new Criteria())), "Expected 3 authors after deleting."); - $this->assertEquals(3, count(PublisherPeer::doSelect(new Criteria())), "Expected 3 publishers after deleting."); - $this->assertEquals(3, count(BookPeer::doSelect(new Criteria())), "Expected 3 books after deleting."); - } - - /** - * Test using a complex criteria to delete multiple rows from a single table. - */ - public function testDoDelete_ComplexCriteria() { - - //print "Attempting to delete books by complex criteria: "; - $c = new Criteria(); - $cn = $c->getNewCriterion(BookPeer::ISBN, "043935806X"); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0380977427")); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0140422161")); - $c->add($cn); - BookPeer::doDelete($c); - - // now there should only be one book left; "The Tin Drum" - - $books = BookPeer::doSelect(new Criteria()); - - $this->assertEquals(1, count($books), "Expected 1 book remaining after deleting."); - $this->assertEquals("The Tin Drum", $books[0]->getTitle(), "Expect the only remaining book to be 'The Tin Drum'"); - } - - /** - * Test that cascading deletes are happening correctly (whether emulated or native). - */ - public function testDoDelete_Cascade_Simple() - { - - // The 'media' table will cascade from book deletes - - // 1) Assert the row exists right now - - $medias = MediaPeer::doSelect(new Criteria()); - $this->assertTrue(count($medias) > 0, "Expected to find at least one row in 'media' table."); - $media = $medias[0]; - $mediaId = $media->getId(); - - // 2) Delete the owning book - - $owningBookId = $media->getBookId(); - BookPeer::doDelete($owningBookId); - - // 3) Assert that the media row is now also gone - - $obj = MediaPeer::retrieveByPK($mediaId); - $this->assertNull($obj, "Expect NULL when retrieving on no matching Media."); - - } - - /** - * Test that cascading deletes are happening correctly for composite pk. - * @link http://propel.phpdb.org/trac/ticket/544 - */ - public function testDoDelete_Cascade_CompositePK() - { - - $origBceCount = BookstoreContestEntryPeer::doCount(new Criteria()); - - $cust1 = new Customer(); - $cust1->setName("Cust1"); - $cust1->save(); - - $cust2 = new Customer(); - $cust2->setName("Cust2"); - $cust2->save(); - - $c1 = new Contest(); - $c1->setName("Contest1"); - $c1->save(); - - $c2 = new Contest(); - $c2->setName("Contest2"); - $c2->save(); - - $store1 = new Bookstore(); - $store1->setStoreName("Store1"); - $store1->save(); - - $bc1 = new BookstoreContest(); - $bc1->setBookstore($store1); - $bc1->setContest($c1); - $bc1->save(); - - $bc2 = new BookstoreContest(); - $bc2->setBookstore($store1); - $bc2->setContest($c2); - $bc2->save(); - - $bce1 = new BookstoreContestEntry(); - $bce1->setEntryDate("now"); - $bce1->setCustomer($cust1); - $bce1->setBookstoreContest($bc1); - $bce1->save(); - - $bce2 = new BookstoreContestEntry(); - $bce2->setEntryDate("now"); - $bce2->setCustomer($cust1); - $bce2->setBookstoreContest($bc2); - $bce2->save(); - - // Now, if we remove $bc1, we expect *only* bce1 to be no longer valid. - - BookstoreContestPeer::doDelete($bc1); - - $newCount = BookstoreContestEntryPeer::doCount(new Criteria()); - - $this->assertEquals($origBceCount + 1, $newCount, "Expected new number of rows in BCE to be orig + 1"); - - $bcetest = BookstoreContestEntryPeer::retrieveByPK($store1->getId(), $c1->getId(), $cust1->getId()); - $this->assertNull($bcetest, "Expected BCE for store1 to be cascade deleted."); - - $bcetest2 = BookstoreContestEntryPeer::retrieveByPK($store1->getId(), $c2->getId(), $cust1->getId()); - $this->assertNotNull($bcetest2, "Expected BCE for store2 to NOT be cascade deleted."); - - } - - /** - * Test that onDelete="SETNULL" is happening correctly (whether emulated or native). - */ - public function testDoDelete_SetNull() { - - // The 'author_id' column in 'book' table will be set to null when author is deleted. - - // 1) Get an arbitrary book - $c = new Criteria(); - $book = BookPeer::doSelectOne($c); - $bookId = $book->getId(); - $authorId = $book->getAuthorId(); - unset($book); - - // 2) Delete the author for that book - AuthorPeer::doDelete($authorId); - - // 3) Assert that the book.author_id column is now NULL - - $book = BookPeer::retrieveByPK($bookId); - $this->assertNull($book->getAuthorId(), "Expect the book.author_id to be NULL after the author was removed."); - - } - - /** - * Test deleting a row by passing in the primary key to the doDelete() method. - */ - public function testDoDelete_ByPK() { - - // 1) get an arbitrary book - $book = BookPeer::doSelectOne(new Criteria()); - $bookId = $book->getId(); - - // 2) now delete that book - BookPeer::doDelete($bookId); - - // 3) now make sure it's gone - $obj = BookPeer::retrieveByPK($bookId); - $this->assertNull($obj, "Expect NULL when retrieving on no matching Book."); - - } - - public function testDoDelete_ByPks() { - // 1) get all of the books - $books = BookPeer::doSelect(new Criteria()); - $bookCount = count($books); - - // 2) we have enough books to do this test - $this->assertGreaterThan(1, $bookCount, 'There are at least two books'); - - // 3) select two random books - $book1 = $books[0]; - $book2 = $books[1]; - - // 4) delete the books - BookPeer::doDelete(array($book1->getId(), $book2->getId())); - - // 5) we should have two less books than before - $this->assertEquals($bookCount-2, BookPeer::doCount(new Criteria()), 'Two books deleted successfully.'); - } - - /** - * Test deleting a row by passing the generated object to doDelete(). - */ - public function testDoDelete_ByObj() { - - // 1) get an arbitrary book - $book = BookPeer::doSelectOne(new Criteria()); - $bookId = $book->getId(); - - // 2) now delete that book - BookPeer::doDelete($book); - - // 3) now make sure it's gone - $obj = BookPeer::retrieveByPK($bookId); - $this->assertNull($obj, "Expect NULL when retrieving on no matching Book."); - - } - - - /** - * Test the doDeleteAll() method for single table. - */ - public function testDoDeleteAll() { - - BookPeer::doDeleteAll(); - $this->assertEquals(0, count(BookPeer::doSelect(new Criteria())), "Expect all book rows to have been deleted."); - } - - /** - * Test the state of the instance pool after a doDeleteAll() call. - */ - public function testDoDeleteAllInstancePool() - { - $review = ReviewPeer::doSelectOne(new Criteria); - $book = $review->getBook(); - BookPeer::doDeleteAll(); - $this->assertNull(BookPeer::retrieveByPk($book->getId()), 'doDeleteAll invalidates instance pool'); - $this->assertNull(ReviewPeer::retrieveByPk($review->getId()), 'doDeleteAll invalidates instance pool of releted tables with ON DELETE CASCADE'); - } - - /** - * Test the doDeleteAll() method when onDelete="CASCADE". - */ - public function testDoDeleteAll_Cascade() { - - BookPeer::doDeleteAll(); - $this->assertEquals(0, count(MediaPeer::doSelect(new Criteria())), "Expect all media rows to have been cascade deleted."); - $this->assertEquals(0, count(ReviewPeer::doSelect(new Criteria())), "Expect all review rows to have been cascade deleted."); - } - - /** - * Test the doDeleteAll() method when onDelete="SETNULL". - */ - public function testDoDeleteAll_SetNull() { - - $c = new Criteria(); - $c->add(BookPeer::AUTHOR_ID, null, Criteria::NOT_EQUAL); - - // 1) make sure there are some books with valid authors - $this->assertTrue(count(BookPeer::doSelect($c)) > 0, "Expect some book.author_id columns that are not NULL."); - - // 2) delete all the authors - AuthorPeer::doDeleteAll(); - - // 3) now verify that the book.author_id columns are all nul - $this->assertEquals(0, count(BookPeer::doSelect($c)), "Expect all book.author_id columns to be NULL."); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/519 - */ - public function testDoDeleteCompositePK() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - ReaderFavoritePeer::doDeleteAll(); - // Create books with IDs 1 to 3 - // Create readers with IDs 1 and 2 - - $this->createBookWithId(1); - $this->createBookWithId(2); - $this->createBookWithId(3); - $this->createReaderWithId(1); - $this->createReaderWithId(2); - - for ($i=1; $i <= 3; $i++) { - for ($j=1; $j <= 2; $j++) { - $bo = new BookOpinion(); - $bo->setBookId($i); - $bo->setReaderId($j); - $bo->save(); - - $rf = new ReaderFavorite(); - $rf->setBookId($i); - $rf->setReaderId($j); - $rf->save(); - } - } - - $this->assertEquals(6, ReaderFavoritePeer::doCount(new Criteria())); - - // Now delete 2 of those rows (2 is special in that it is the number of rows - // being deleted, as well as the number of things in the primary key) - ReaderFavoritePeer::doDelete(array(array(1,1), array(2,2))); - $this->assertEquals(4, ReaderFavoritePeer::doCount(new Criteria())); - - //Note: these composite PK's are pairs of (BookId, ReaderId) - $this->assertNotNull(ReaderFavoritePeer::retrieveByPK(2,1)); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPK(1,2)); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,1)); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,2)); - $this->assertNull(ReaderFavoritePeer::retrieveByPK(1,1)); - $this->assertNull(ReaderFavoritePeer::retrieveByPK(2,2)); - - //test deletion of a single composite PK - ReaderFavoritePeer::doDelete(array(3,1)); - $this->assertEquals(3, ReaderFavoritePeer::doCount(new Criteria())); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPK(2,1)); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPK(1,2)); - $this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,2)); - $this->assertNull(ReaderFavoritePeer::retrieveByPK(1,1)); - $this->assertNull(ReaderFavoritePeer::retrieveByPK(2,2)); - $this->assertNull(ReaderFavoritePeer::retrieveByPk(3,1)); - - //test deleting the last three - ReaderFavoritePeer::doDelete(array(array(2,1), array(1,2), array(3,2))); - $this->assertEquals(0, ReaderFavoritePeer::doCount(new Criteria())); - } - - /** - * Test the doInsert() method when passed a Criteria object. - */ - public function testDoInsert_Criteria() { - - $name = "A Sample Publisher - " . time(); - - $values = new Criteria(); - $values->add(PublisherPeer::NAME, $name); - PublisherPeer::doInsert($values); - - $c = new Criteria(); - $c->add(PublisherPeer::NAME, $name); - - $matches = PublisherPeer::doSelect($c); - $this->assertEquals(1, count($matches), "Expect there to be exactly 1 publisher just-inserted."); - $this->assertTrue( 1 != $matches[0]->getId(), "Expected to have different ID than one put in values Criteria."); - - } - - /** - * Test the doInsert() method when passed a generated object. - */ - public function testDoInsert_Obj() { - - $name = "A Sample Publisher - " . time(); - - $values = new Publisher(); - $values->setName($name); - PublisherPeer::doInsert($values); - - $c = new Criteria(); - $c->add(PublisherPeer::NAME, $name); - - $matches = PublisherPeer::doSelect($c); - $this->assertEquals(1, count($matches), "Expect there to be exactly 1 publisher just-inserted."); - $this->assertTrue( 1 != $matches[0]->getId(), "Expected to have different ID than one put in values Criteria."); - - } - - /** - * Tests the return type of doCount*() methods. - */ - public function testDoCountType() - { - $c = new Criteria(); - $this->assertType('integer', BookPeer::doCount($c), "Expected doCount() to return an integer."); - $this->assertType('integer', BookPeer::doCountJoinAll($c), "Expected doCountJoinAll() to return an integer."); - $this->assertType('integer', BookPeer::doCountJoinAuthor($c), "Expected doCountJoinAuthor() to return an integer."); - } - - /** - * Tests the doCount() method with limit/offset. - */ - public function testDoCountLimitOffset() - { - BookPeer::doDeleteAll(); - - for ($i=0; $i < 25; $i++) { - $b = new Book(); - $b->setTitle("Book $i"); - $b->setISBN("ISBN $i"); - $b->save(); - } - - $c = new Criteria(); - $totalCount = BookPeer::doCount($c); - - $this->assertEquals(25, $totalCount); - - $c2 = new Criteria(); - $c2->setLimit(10); - $this->assertEquals(10, BookPeer::doCount($c2)); - - $c3 = new Criteria(); - $c3->setOffset(10); - $this->assertEquals(15, BookPeer::doCount($c3)); - - $c4 = new Criteria(); - $c4->setOffset(5); - $c4->setLimit(5); - $this->assertEquals(5, BookPeer::doCount($c4)); - - $c5 = new Criteria(); - $c5->setOffset(20); - $c5->setLimit(10); - $this->assertEquals(5, BookPeer::doCount($c5)); - } - - /** - * Test doCountJoin*() methods. - */ - public function testDoCountJoin() - { - BookPeer::doDeleteAll(); - - for ($i=0; $i < 25; $i++) { - $b = new Book(); - $b->setTitle("Book $i"); - $b->setISBN("ISBN $i"); - $b->save(); - } - - $c = new Criteria(); - $totalCount = BookPeer::doCount($c); - - $this->assertEquals($totalCount, BookPeer::doCountJoinAuthor($c)); - $this->assertEquals($totalCount, BookPeer::doCountJoinPublisher($c)); - } - - /** - * Test doCountJoin*() methods with ORDER BY columns in Criteria. - * @link http://propel.phpdb.org/trac/ticket/627 - */ - public function testDoCountJoinWithOrderBy() - { - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addAscendingOrderByColumn(BookPeer::ID); - - // None of these should not throw an exception! - BookPeer::doCountJoinAll($c); - BookPeer::doCountJoinAllExceptAuthor($c); - BookPeer::doCountJoinAuthor($c); - } - - /** - * Test passing null values to removeInstanceFromPool(). - */ - public function testRemoveInstanceFromPool_Null() - { - // if it throws an exception, then it's broken. - try { - BookPeer::removeInstanceFromPool(null); - } catch (Exception $x) { - $this->fail("Expected to get no exception when removing an instance from the pool."); - } - } - - /** - * @see testDoDeleteCompositePK() - */ - private function createBookWithId($id) - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $b = BookPeer::retrieveByPK($id); - if (!$b) { - $b = new Book(); - $b->setTitle("Book$id")->setISBN("BookISBN$id")->save(); - $b1Id = $b->getId(); - $sql = "UPDATE " . BookPeer::TABLE_NAME . " SET id = ? WHERE id = ?"; - $stmt = $con->prepare($sql); - $stmt->bindValue(1, $id); - $stmt->bindValue(2, $b1Id); - $stmt->execute(); - } - } - - /** - * @see testDoDeleteCompositePK() - */ - private function createReaderWithId($id) - { - $con = Propel::getConnection(BookReaderPeer::DATABASE_NAME); - $r = BookReaderPeer::retrieveByPK($id); - if (!$r) { - $r = new BookReader(); - $r->setName('Reader'.$id)->save(); - $r1Id = $r->getId(); - $sql = "UPDATE " . BookReaderPeer::TABLE_NAME . " SET id = ? WHERE id = ?"; - $stmt = $con->prepare($sql); - $stmt->bindValue(1, $id); - $stmt->bindValue(2, $r1Id); - $stmt->execute(); - } - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoSelectTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoSelectTest.php deleted file mode 100644 index e6be9d3f6..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerDoSelectTest.php +++ /dev/null @@ -1,439 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedPeerDoSelectTest extends BookstoreEmptyTestBase -{ - protected function setUp() - { - parent::setUp(); - BookstoreDataPopulator::populate(); - } - - public function testDoSelect() - { - $books = BookPeer::doSelect(new Criteria()); - $this->assertEquals(4, count($books), 'doSelect() with an empty Criteria returns all results'); - $book1 = $books[0]; - - $c = new Criteria(); - $c->add(BookPeer::ID, $book1->getId()); - $res = BookPeer::doSelect($c); - $this->assertEquals(array($book1), $res, 'doSelect() accepts a Criteria object with a condition'); - - $c = new Criteria(); - $c->add(BookPeer::ID, $book1->getId()); - $c->add(BookPeer::TITLE, $book1->getTitle()); - $res = BookPeer::doSelect($c); - $this->assertEquals(array($book1), $res, 'doSelect() accepts a Criteria object with several condition'); - - $c = new Criteria(); - $c->add(BookPeer::ID, 'foo'); - $res = BookPeer::doSelect($c); - $this->assertEquals(array(), $res, 'doSelect() accepts an incorrect Criteria'); - } - - /** - * Tests performing doSelect() and doSelectJoin() using LIMITs. - */ - public function testDoSelect_Limit() { - - // 1) get the total number of items in a particular table - $count = BookPeer::doCount(new Criteria()); - - $this->assertTrue($count > 1, "Need more than 1 record in books table to perform this test."); - - $limitcount = $count - 1; - - $lc = new Criteria(); - $lc->setLimit($limitcount); - - $results = BookPeer::doSelect($lc); - - $this->assertEquals($limitcount, count($results), "Expected $limitcount results from BookPeer::doSelect()"); - - // re-create it just to avoid side-effects - $lc2 = new Criteria(); - $lc2->setLimit($limitcount); - $results2 = BookPeer::doSelectJoinAuthor($lc2); - - $this->assertEquals($limitcount, count($results2), "Expected $limitcount results from BookPeer::doSelectJoinAuthor()"); - - } - - /** - * Test the basic functionality of the doSelectJoin*() methods. - */ - public function testDoSelectJoin() - { - - BookPeer::clearInstancePool(); - - $c = new Criteria(); - - $books = BookPeer::doSelect($c); - $obj = $books[0]; - // $size = strlen(serialize($obj)); - - BookPeer::clearInstancePool(); - - $joinBooks = BookPeer::doSelectJoinAuthor($c); - $obj2 = $joinBooks[0]; - $obj2Array = $obj2->toArray(BasePeer::TYPE_PHPNAME, true, true); - // $joinSize = strlen(serialize($obj2)); - - $this->assertEquals(count($books), count($joinBooks), "Expected to find same number of rows in doSelectJoin*() call as doSelect() call."); - - // $this->assertTrue($joinSize > $size, "Expected a serialized join object to be larger than a non-join object."); - - $this->assertTrue(array_key_exists('Author', $obj2Array)); - } - - /** - * Test the doSelectJoin*() methods when the related object is NULL. - */ - public function testDoSelectJoin_NullFk() - { - $b1 = new Book(); - $b1->setTitle("Test NULLFK 1"); - $b1->setISBN("NULLFK-1"); - $b1->save(); - - $b2 = new Book(); - $b2->setTitle("Test NULLFK 2"); - $b2->setISBN("NULLFK-2"); - $b2->setAuthor(new Author()); - $b2->getAuthor()->setFirstName("Hans")->setLastName("L"); - $b2->save(); - - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - - $c = new Criteria(); - $c->add(BookPeer::ISBN, 'NULLFK-%', Criteria::LIKE); - $c->addAscendingOrderByColumn(BookPeer::ISBN); - - $matches = BookPeer::doSelectJoinAuthor($c); - $this->assertEquals(2, count($matches), "Expected 2 matches back from new books; got back " . count($matches)); - - $this->assertNull($matches[0]->getAuthor(), "Expected first book author to be null"); - $this->assertType('Author', $matches[1]->getAuthor(), "Expected valid Author object for second book."); - } - - public function testDoSelectJoinOneToOne() - { - $con = Propel::getConnection(); - $count = $con->getQueryCount(); - Propel::disableInstancePooling(); - $c = new Criteria(); - $accs = BookstoreEmployeeAccountPeer::doSelectJoinBookstoreEmployee($c); - Propel::enableInstancePooling(); - $this->assertEquals(1, $con->getQueryCount() - $count, 'doSelectJoin() makes only one query in a one-to-one relationship'); - } - - public function testDoSelectOne() - { - $books = BookPeer::doSelect(new Criteria()); - $book1 = $books[0]; - - $c = new Criteria(); - $c->add(BookPeer::ID, $book1->getId()); - $res = BookPeer::doSelectOne($c); - $this->assertEquals($book1, $res, 'doSelectOne() returns a single object'); - - $c = new Criteria(); - $c->add(BookPeer::ID, 'foo'); - $res = BookPeer::doSelectOne($c); - $this->assertNull($res, 'doSelectOne() returns null if the Criteria matches no record'); - } - - public function testObjectInstances() - { - - $sample = BookPeer::doSelectOne(new Criteria()); - $samplePk = $sample->getPrimaryKey(); - - // 1) make sure consecutive calls to retrieveByPK() return the same object. - - $b1 = BookPeer::retrieveByPK($samplePk); - $b2 = BookPeer::retrieveByPK($samplePk); - - $sampleval = md5(microtime()); - - $this->assertTrue($b1 === $b2, "Expected object instances to match for calls with same retrieveByPK() method signature."); - - // 2) make sure that calls to doSelect also return references to the same objects. - $allbooks = BookPeer::doSelect(new Criteria()); - foreach ($allbooks as $testb) { - if ($testb->getPrimaryKey() == $b1->getPrimaryKey()) { - $this->assertTrue($testb === $b1, "Expected same object instance from doSelect() as from retrieveByPK()"); - } - } - - // 3) test fetching related objects - $book = BookPeer::retrieveByPK($samplePk); - - $bookauthor = $book->getAuthor(); - - $author = AuthorPeer::retrieveByPK($bookauthor->getId()); - - $this->assertTrue($bookauthor === $author, "Expected same object instance when calling fk object accessor as retrieveByPK()"); - - // 4) test a doSelectJoin() - $morebooks = BookPeer::doSelectJoinAuthor(new Criteria()); - for ($i=0,$j=0; $j < count($morebooks); $i++, $j++) { - $testb1 = $allbooks[$i]; - $testb2 = $allbooks[$j]; - $this->assertTrue($testb1 === $testb2, "Expected the same objects from consecutive doSelect() calls."); - // we could probably also test this by just verifying that $book & $testb are the same - if ($testb1->getPrimaryKey() === $book) { - $this->assertTrue($book->getAuthor() === $testb1->getAuthor(), "Expected same author object in calls to pkey-matching books."); - } - } - - - // 5) test creating a new object, saving it, and then retrieving that object (should all be same instance) - $b = new BookstoreEmployee(); - $b->setName("Testing"); - $b->setJobTitle("Testing"); - $b->save(); - - $empId = $b->getId(); - - $this->assertSame($b, BookstoreEmployeePeer::retrieveByPK($empId), "Expected newly saved object to be same instance as pooled."); - - } - - /** - * Test inheritance features. - */ - public function testInheritance() - { - $manager = new BookstoreManager(); - $manager->setName("Manager 1"); - $manager->setJobTitle("Warehouse Manager"); - $manager->save(); - $managerId = $manager->getId(); - - $employee = new BookstoreEmployee(); - $employee->setName("Employee 1"); - $employee->setJobTitle("Janitor"); - $employee->setSupervisorId($managerId); - $employee->save(); - $empId = $employee->getId(); - - $cashier = new BookstoreCashier(); - $cashier->setName("Cashier 1"); - $cashier->setJobTitle("Cashier"); - $cashier->save(); - $cashierId = $cashier->getId(); - - // 1) test the pooled instances' - $c = new Criteria(); - $c->add(BookstoreEmployeePeer::ID, array($managerId, $empId, $cashierId), Criteria::IN); - $c->addAscendingOrderByColumn(BookstoreEmployeePeer::ID); - - $objects = BookstoreEmployeePeer::doSelect($c); - - $this->assertEquals(3, count($objects), "Expected 3 objects to be returned."); - - list($o1, $o2, $o3) = $objects; - - $this->assertSame($o1, $manager); - $this->assertSame($o2, $employee); - $this->assertSame($o3, $cashier); - - // 2) test a forced reload from database - BookstoreEmployeePeer::clearInstancePool(); - - list($o1,$o2,$o3) = BookstoreEmployeePeer::doSelect($c); - - $this->assertTrue($o1 instanceof BookstoreManager, "Expected BookstoreManager object, got " . get_class($o1)); - $this->assertTrue($o2 instanceof BookstoreEmployee, "Expected BookstoreEmployee object, got " . get_class($o2)); - $this->assertTrue($o3 instanceof BookstoreCashier, "Expected BookstoreCashier object, got " . get_class($o3)); - - } - - /** - * Test hydration of joined rows that contain lazy load columns. - * @link http://propel.phpdb.org/trac/ticket/464 - */ - public function testHydrationJoinLazyLoad() - { - BookstoreEmployeeAccountPeer::doDeleteAll(); - BookstoreEmployeePeer::doDeleteAll(); - AcctAccessRolePeer::doDeleteAll(); - - $bemp2 = new BookstoreEmployee(); - $bemp2->setName("Pieter"); - $bemp2->setJobTitle("Clerk"); - $bemp2->save(); - - $role = new AcctAccessRole(); - $role->setName("Admin"); - - $bempacct = new BookstoreEmployeeAccount(); - $bempacct->setBookstoreEmployee($bemp2); - $bempacct->setAcctAccessRole($role); - $bempacct->setLogin("john"); - $bempacct->setPassword("johnp4ss"); - $bempacct->save(); - - $c = new Criteria(); - $results = BookstoreEmployeeAccountPeer::doSelectJoinAll($c); - $o = $results[0]; - - $this->assertEquals('Admin', $o->getAcctAccessRole()->getName()); - } - - /** - * Testing foreign keys with multiple referrer columns. - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testMultiColFk() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - ReaderFavoritePeer::doDeleteAll(); - - $b1 = new Book(); - $b1->setTitle("Book1"); - $b1->setISBN("ISBN-1"); - $b1->save(); - - $r1 = new BookReader(); - $r1-> setName("Me"); - $r1->save(); - - $bo1 = new BookOpinion(); - $bo1->setBookId($b1->getId()); - $bo1->setReaderId($r1->getId()); - $bo1->setRating(9); - $bo1->setRecommendToFriend(true); - $bo1->save(); - - $rf1 = new ReaderFavorite(); - $rf1->setReaderId($r1->getId()); - $rf1->setBookId($b1->getId()); - $rf1->save(); - - $c = new Criteria(ReaderFavoritePeer::DATABASE_NAME); - $c->add(ReaderFavoritePeer::BOOK_ID, $b1->getId()); - $c->add(ReaderFavoritePeer::READER_ID, $r1->getId()); - - $results = ReaderFavoritePeer::doSelectJoinBookOpinion($c); - $this->assertEquals(1, count($results), "Expected 1 result"); - } - - /** - * Testing foreign keys with multiple referrer columns. - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testMultiColJoin() - { - BookstoreContestPeer::doDeleteAll(); - BookstoreContestEntryPeer::doDeleteAll(); - - $bs = new Bookstore(); - $bs->setStoreName("Test1"); - $bs->setPopulationServed(5); - $bs->save(); - $bs1Id = $bs->getId(); - - $bs2 = new Bookstore(); - $bs2->setStoreName("Test2"); - $bs2->setPopulationServed(5); - $bs2->save(); - $bs2Id = $bs2->getId(); - - $ct1 = new Contest(); - $ct1->setName("Contest1!"); - $ct1->save(); - $ct1Id = $ct1->getId(); - - $ct2 = new Contest(); - $ct2->setName("Contest2!"); - $ct2->save(); - $ct2Id = $ct2->getId(); - - $cmr = new Customer(); - $cmr->setName("Customer1"); - $cmr->save(); - $cmr1Id = $cmr->getId(); - - $cmr2 = new Customer(); - $cmr2->setName("Customer2"); - $cmr2->save(); - $cmr2Id = $cmr2->getId(); - - $contest = new BookstoreContest(); - $contest->setBookstoreId($bs1Id); - $contest->setContestId($ct1Id); - $contest->save(); - - $contest = new BookstoreContest(); - $contest->setBookstoreId($bs2Id); - $contest->setContestId($ct1Id); - $contest->save(); - - $entry = new BookstoreContestEntry(); - $entry->setBookstoreId($bs1Id); - $entry->setContestId($ct1Id); - $entry->setCustomerId($cmr1Id); - $entry->save(); - - $entry = new BookstoreContestEntry(); - $entry->setBookstoreId($bs1Id); - $entry->setContestId($ct1Id); - $entry->setCustomerId($cmr2Id); - $entry->save(); - - // Note: this test isn't really working very well. We setup fkeys that - // require that the BookstoreContest rows exist and then try to violate - // the rules ... :-/ This may work in some lenient databases, but an error - // is expected here. - - /* - * Commented out for now ... though without it, this test may not really be testing anything - $entry = new BookstoreContestEntry(); - $entry->setBookstoreId($bs1Id); - $entry->setContestId($ct2Id); - $entry->setCustomerId($cmr2Id); - $entry->save(); - */ - - - $c = new Criteria(); - $c->addJoin(array(BookstoreContestEntryPeer::BOOKSTORE_ID, BookstoreContestEntryPeer::CONTEST_ID), array(BookstoreContestPeer::BOOKSTORE_ID, BookstoreContestPeer::CONTEST_ID) ); - - $results = BookstoreContestEntryPeer::doSelect($c); - $this->assertEquals(2, count($results) ); - foreach ($results as $result) { - $this->assertEquals($bs1Id, $result->getBookstoreId() ); - $this->assertEquals($ct1Id, $result->getContestId() ); - } - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerTest.php deleted file mode 100644 index 91d3755ce..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/GeneratedPeerTest.php +++ /dev/null @@ -1,90 +0,0 @@ - - * @package generator.builder.om - */ -class GeneratedPeerTest extends BookstoreTestBase -{ - public function testAlias() - { - $this->assertEquals('foo.ID', BookPeer::alias('foo', BookPeer::ID), 'alias() returns a column name using the table alias'); - $this->assertEquals('book.ID', BookPeer::alias('book', BookPeer::ID), 'alias() returns a column name using the table alias'); - $this->assertEquals('foo.COVER_IMAGE', MediaPeer::alias('foo', MediaPeer::COVER_IMAGE), 'alias() also works for lazy-loaded columns'); - $this->assertEquals('foo.SUBTITLE', EssayPeer::alias('foo', EssayPeer::SUBTITLE), 'alias() also works for columns with custom phpName'); - } - - public function testAddSelectColumns() - { - $c = new Criteria(); - BookPeer::addSelectColumns($c); - $expected = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID - ); - $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() adds the columns of the model to the criteria'); - } - - public function testAddSelectColumnsLazyLoad() - { - $c = new Criteria(); - MediaPeer::addSelectColumns($c); - $expected = array( - MediaPeer::ID, - MediaPeer::BOOK_ID - ); - $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns'); - } - - public function testAddSelectColumnsAlias() - { - $c = new Criteria(); - BookPeer::addSelectColumns($c, 'foo'); - $expected = array( - 'foo.ID', - 'foo.TITLE', - 'foo.ISBN', - 'foo.PRICE', - 'foo.PUBLISHER_ID', - 'foo.AUTHOR_ID' - ); - $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() uses the second parameter as a table alias'); - } - - public function testAddSelectColumnsAliasLazyLoad() - { - $c = new Criteria(); - MediaPeer::addSelectColumns($c, 'bar'); - $expected = array( - 'bar.ID', - 'bar.BOOK_ID' - ); - $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns but uses the second parameter as an alias'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderNamespaceTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderNamespaceTest.php deleted file mode 100644 index c78f9532a..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderNamespaceTest.php +++ /dev/null @@ -1,149 +0,0 @@ -addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertNull($builder->getNamespace(), 'Builder namespace is null when neither the db nor the table have namespace'); - } - - public function testDbNamespace() - { - $d = new Database('fooDb'); - $d->setNamespace('Foo\\Bar'); - $t = new Table('fooTable'); - $d->addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the database namespace when no table namespace is set'); - } - - public function testTableNamespace() - { - $d = new Database('fooDb'); - $t = new Table('fooTable'); - $t->setNamespace('Foo\\Bar'); - $d->addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when no database namespace is set'); - } - - public function testAbsoluteTableNamespace() - { - $d = new Database('fooDb'); - $t = new Table('fooTable'); - $t->setNamespace('\\Foo\\Bar'); - $d->addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when it is set as absolute'); - } - - public function testAbsoluteTableNamespaceAndDbNamespace() - { - $d = new Database('fooDb'); - $d->setNamespace('Baz'); - $t = new Table('fooTable'); - $t->setNamespace('\\Foo\\Bar'); - $d->addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when it is set as absolute'); - } - - public function testTableNamespaceAndDbNamespace() - { - $d = new Database('fooDb'); - $d->setNamespace('Baz'); - $t = new Table('fooTable'); - $t->setNamespace('Foo\\Bar'); - $d->addTable($t); - $builder = new TestableOMBuilder2($t); - $this->assertEquals('Baz\\Foo\\Bar', $builder->getNamespace(), 'Builder namespace is composed from the database and table namespaces when both are set'); - } - - public function testDeclareClassNamespace() - { - $builder = new TestableOMBuilder2(new Table('fooTable')); - $builder->declareClassNamespace('Foo'); - $this->assertEquals(array('' => array('Foo')), $builder->getDeclaredClasses()); - $builder->declareClassNamespace('Bar'); - $this->assertEquals(array('' => array('Foo', 'Bar')), $builder->getDeclaredClasses()); - $builder->declareClassNamespace('Foo'); - $this->assertEquals(array('' => array('Foo', 'Bar')), $builder->getDeclaredClasses()); - $builder = new TestableOMBuilder2(new Table('fooTable')); - $builder->declareClassNamespace('Foo', 'Foo'); - $this->assertEquals(array('Foo' => array('Foo')), $builder->getDeclaredClasses()); - $builder->declareClassNamespace('Bar', 'Foo'); - $this->assertEquals(array('Foo' => array('Foo', 'Bar')), $builder->getDeclaredClasses()); - $builder->declareClassNamespace('Foo', 'Foo'); - $this->assertEquals(array('Foo' => array('Foo', 'Bar')), $builder->getDeclaredClasses()); - $builder->declareClassNamespace('Bar', 'Bar'); - $this->assertEquals(array('Foo' => array('Foo', 'Bar'), 'Bar' => array('Bar')), $builder->getDeclaredClasses()); - } - - public function testGetDeclareClass() - { - $builder = new TestableOMBuilder2(new Table('fooTable')); - $this->assertEquals(array(), $builder->getDeclaredClasses()); - $builder->declareClass('\\Foo'); - $this->assertEquals(array('Foo'), $builder->getDeclaredClasses('')); - $builder->declareClass('Bar'); - $this->assertEquals(array('Foo', 'Bar'), $builder->getDeclaredClasses('')); - $builder->declareClass('Foo\\Bar'); - $this->assertEquals(array('Bar'), $builder->getDeclaredClasses('Foo')); - $builder->declareClass('Foo\\Bar\\Baz'); - $this->assertEquals(array('Bar'), $builder->getDeclaredClasses('Foo')); - $this->assertEquals(array('Baz'), $builder->getDeclaredClasses('Foo\\Bar')); - $builder->declareClass('\\Hello\\World'); - $this->assertEquals(array('World'), $builder->getDeclaredClasses('Hello')); - } - - public function testDeclareClasses() - { - $builder = new TestableOMBuilder2(new Table('fooTable')); - $builder->declareClasses('Foo', '\\Bar', 'Baz\\Baz', 'Hello\\Cruel\\World'); - $expected = array( - '' => array('Foo', 'Bar'), - 'Baz' => array('Baz'), - 'Hello\\Cruel' => array('World') - ); - $this->assertEquals($expected, $builder->getDeclaredClasses()); - } -} - -class TestableOMBuilder2 extends OMBuilder -{ - public static function getRelatedBySuffix(ForeignKey $fk) - { - return parent::getRelatedBySuffix($fk); - } - - public static function getRefRelatedBySuffix(ForeignKey $fk) - { - return parent::getRefRelatedBySuffix($fk); - } - - public function getUnprefixedClassname() {} -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderTest.php deleted file mode 100644 index 1d7162e70..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/OMBuilderTest.php +++ /dev/null @@ -1,89 +0,0 @@ -parseFile('fixtures/bookstore/schema.xml'); - $this->database = $appData->getDatabase("bookstore"); - } - - protected function getForeignKey($tableName, $index) - { - $fks = $this->database->getTable($tableName)->getForeignKeys(); - return $fks[$index]; - } - - public static function getRelatedBySuffixDataProvider() - { - return array( - array('book', 0, '', ''), - array('essay', 0, 'RelatedByFirstAuthor', 'RelatedByFirstAuthor'), - array('essay', 1, 'RelatedBySecondAuthor', 'RelatedBySecondAuthor'), - array('essay', 2, 'RelatedById', 'RelatedByNextEssayId'), - array('bookstore_employee', 0, 'RelatedById', 'RelatedBySupervisorId'), - array('composite_essay', 0, 'RelatedById0', 'RelatedByFirstEssayId'), - array('composite_essay', 1, 'RelatedById1', 'RelatedBySecondEssayId'), - array('man', 0, 'RelatedByWifeId', 'RelatedByWifeId'), - array('woman', 0, 'RelatedByHusbandId', 'RelatedByHusbandId'), - ); - } - - /** - * @dataProvider getRelatedBySuffixDataProvider - */ - public function testGetRelatedBySuffix($table, $index, $expectedSuffix, $expectedReverseSuffix) - { - $fk = $this->getForeignKey($table, $index); - $this->assertEquals($expectedSuffix, TestableOMBuilder::getRefRelatedBySuffix($fk)); - $this->assertEquals($expectedReverseSuffix, TestableOMBuilder::getRelatedBySuffix($fk)); - } - - public function testClear() - { - $b = new Book(); - $b->setNew(false); - $b->clear(); - $this->assertTrue($b->isNew(), 'clear() sets the object to new'); - $b = new Book(); - $b->setDeleted(true); - $b->clear(); - $this->assertFalse($b->isDeleted(), 'clear() sets the object to not deleted'); - } -} - -class TestableOMBuilder extends OMBuilder -{ - public static function getRelatedBySuffix(ForeignKey $fk) - { - return parent::getRelatedBySuffix($fk); - } - - public static function getRefRelatedBySuffix(ForeignKey $fk) - { - return parent::getRefRelatedBySuffix($fk); - } - - public function getUnprefixedClassname() {} -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/PHP5TableMapBuilderTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/PHP5TableMapBuilderTest.php deleted file mode 100644 index f6463e51b..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/PHP5TableMapBuilderTest.php +++ /dev/null @@ -1,149 +0,0 @@ -databaseMap = Propel::getDatabaseMap('bookstore'); - } - - public function testColumnDefaultValue() - { - $table = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount'); - $this->assertNull($table->getColumn('login')->getDefaultValue(), 'null default values are correctly mapped'); - $this->assertEquals('\'@\'\'34"', $table->getColumn('password')->getDefaultValue(), 'string default values are correctly escaped and mapped'); - $this->assertTrue($table->getColumn('enabled')->getDefaultValue(), 'boolean default values are correctly mapped'); - $this->assertFalse($table->getColumn('not_enabled')->getDefaultValue(), 'boolean default values are correctly mapped'); - $this->assertEquals('CURRENT_TIMESTAMP', $table->getColumn('created')->getDefaultValue(), 'expression default values are correctly mapped'); - $this->assertNull($table->getColumn('role_id')->getDefaultValue(), 'explicit null default values are correctly mapped'); - } - - public function testRelationCount() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(9, count($bookTable->getRelations()), 'The map builder creates relations for both incoming and outgoing keys'); - } - - public function testSimpleRelationName() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertTrue($bookTable->hasRelation('Publisher'), 'The map builder creates relations based on the foreign table name, calemized'); - $this->assertTrue($bookTable->hasRelation('BookListRel'), 'The map builder creates relations based on the foreign table phpName, if provided'); - } - - public function testAliasRelationName() - { - $bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $this->assertTrue($bookEmpTable->hasRelation('Supervisor'), 'The map builder creates relations based on the foreign key phpName'); - $this->assertTrue($bookEmpTable->hasRelation('Subordinate'), 'The map builder creates relations based on the foreign key refPhpName'); - } - - public function testDuplicateRelationName() - { - $essayTable = $this->databaseMap->getTableByPhpName('Essay'); - $this->assertTrue($essayTable->hasRelation('AuthorRelatedByFirstAuthor'), 'The map builder creates relations based on the foreign table name and the foreign key'); - $this->assertTrue($essayTable->hasRelation('AuthorRelatedBySecondAuthor'), 'The map builder creates relations based on the foreign table name and the foreign key'); - } - - public function testRelationDirectionManyToOne() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(RelationMap::MANY_TO_ONE, $bookTable->getRelation('Publisher')->getType(), 'The map builder creates MANY_TO_ONE relations for every foreign key'); - $this->assertEquals(RelationMap::MANY_TO_ONE, $bookTable->getRelation('Author')->getType(), 'The map builder creates MANY_TO_ONE relations for every foreign key'); - } - - public function testRelationDirectionOneToMany() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('Review')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('Media')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookListRel')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookOpinion')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('ReaderFavorite')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookstoreContest')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key'); - } - - public function testRelationDirectionOneToOne() - { - $bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $this->assertEquals(RelationMap::ONE_TO_ONE, $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getType(), 'The map builder creates ONE_TO_ONE relations for every incoming foreign key to a primary key'); - } - - public function testRelationDirectionManyToMAny() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(RelationMap::MANY_TO_MANY, $bookTable->getRelation('BookClubList')->getType(), 'The map builder creates MANY_TO_MANY relations for every cross key'); - } - - public function testRelationsColumns() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $expectedMapping = array('book.PUBLISHER_ID' => 'publisher.ID'); - $this->assertEquals($expectedMapping, $bookTable->getRelation('Publisher')->getColumnMappings(), 'The map builder adds columns in the correct order for foreign keys'); - $expectedMapping = array('review.BOOK_ID' => 'book.ID'); - $this->assertEquals($expectedMapping, $bookTable->getRelation('Review')->getColumnMappings(), 'The map builder adds columns in the correct order for incoming foreign keys'); - $publisherTable = $this->databaseMap->getTableByPhpName('Publisher'); - $expectedMapping = array('book.PUBLISHER_ID' => 'publisher.ID'); - $this->assertEquals($expectedMapping, $publisherTable->getRelation('Book')->getColumnMappings(), 'The map builder adds local columns where the foreign key lies'); - $rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite'); - $expectedMapping = array( - 'reader_favorite.BOOK_ID' => 'book_opinion.BOOK_ID', - 'reader_favorite.READER_ID' => 'book_opinion.READER_ID' - ); - $this->assertEquals($expectedMapping, $rfTable->getRelation('BookOpinion')->getColumnMappings(), 'The map builder adds all columns for composite foreign keys'); - $expectedMapping = array(); - $this->assertEquals($expectedMapping, $bookTable->getRelation('BookClubList')->getColumnMappings(), 'The map builder provides no column mapping for many-to-many relationships'); - } - - public function testRelationOnDelete() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals('SET NULL', $bookTable->getRelation('Publisher')->getOnDelete(), 'The map builder adds columns with the correct onDelete'); - } - - public function testRelationOnUpdate() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertNull($bookTable->getRelation('Publisher')->getOnUpdate(), 'The map builder adds columns with onDelete null by default'); - $this->assertEquals('CASCADE', $bookTable->getRelation('Author')->getOnUpdate(), 'The map builder adds columns with the correct onUpdate'); - } - - public function testBehaviors() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals($bookTable->getBehaviors(), array(), 'getBehaviors() returns an empty array when no behaviors are registered'); - $tmap = Propel::getDatabaseMap(Table1Peer::DATABASE_NAME)->getTable(Table1Peer::TABLE_NAME); - $expectedBehaviorParams = array('timestampable' => array('create_column' => 'created_on', 'update_column' => 'updated_on')); - $this->assertEquals($tmap->getBehaviors(), $expectedBehaviorParams, 'The map builder creates a getBehaviors() method to retrieve behaviors parameters when behaviors are registered'); - } - - public function testSingleTableInheritance() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertFalse($bookTable->isSingleTableInheritance(), 'isSingleTabkeInheritance() returns false by default'); - - $empTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $this->assertTrue($empTable->isSingleTableInheritance(), 'isSingleTabkeInheritance() returns true for tables using single table inheritance'); - - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderInheritanceTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderInheritanceTest.php deleted file mode 100644 index 10fbb1e23..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderInheritanceTest.php +++ /dev/null @@ -1,95 +0,0 @@ -assertTrue($query instanceof BookstoreCashierQuery, 'the create() factory returns an instance of the correct class'); - } - - public function testFindFilter() - { - BookstoreDataPopulator::depopulate($this->con); - $employee = new BookstoreEmployee(); - $employee->save($this->con); - $manager = new BookstoreManager(); - $manager->save($this->con); - $cashier1 = new BookstoreCashier(); - $cashier1->save($this->con); - $cashier2 = new BookstoreCashier(); - $cashier2->save($this->con); - $nbEmp = BookstoreEmployeeQuery::create()->count($this->con); - $this->assertEquals(4, $nbEmp, 'find() in main query returns all results'); - $nbMan = BookstoreManagerQuery::create()->count($this->con); - $this->assertEquals(1, $nbMan, 'find() in sub query returns only child results'); - $nbCash = BookstoreCashierQuery::create()->count($this->con); - $this->assertEquals(2, $nbCash, 'find() in sub query returns only child results'); - } - - public function testUpdateFilter() - { - BookstoreDataPopulator::depopulate($this->con); - $manager = new BookstoreManager(); - $manager->save($this->con); - $cashier1 = new BookstoreCashier(); - $cashier1->save($this->con); - $cashier2 = new BookstoreCashier(); - $cashier2->save($this->con); - BookstoreManagerQuery::create()->update(array('Name' => 'foo'), $this->con); - $nbMan = BookstoreEmployeeQuery::create() - ->filterByName('foo') - ->count($this->con); - $this->assertEquals(1, $nbMan, 'Update in sub query affects only child results'); - } - - public function testDeleteFilter() - { - BookstoreDataPopulator::depopulate($this->con); - $manager = new BookstoreManager(); - $manager->save($this->con); - $cashier1 = new BookstoreCashier(); - $cashier1->save($this->con); - $cashier2 = new BookstoreCashier(); - $cashier2->save($this->con); - BookstoreManagerQuery::create() - ->filterByName() - ->delete(); - $nbCash = BookstoreEmployeeQuery::create()->count(); - $this->assertEquals(2, $nbCash, 'Delete in sub query affects only child results'); - } - - public function testDeleteAllFilter() - { - BookstoreDataPopulator::depopulate($this->con); - $manager = new BookstoreManager(); - $manager->save($this->con); - $cashier1 = new BookstoreCashier(); - $cashier1->save($this->con); - $cashier2 = new BookstoreCashier(); - $cashier2->save($this->con); - BookstoreManagerQuery::create()->deleteAll(); - $nbCash = BookstoreEmployeeQuery::create()->count(); - $this->assertEquals(2, $nbCash, 'Delete in sub query affects only child results'); - } -} - diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderTest.php deleted file mode 100644 index 056c1afd4..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/om/QueryBuilderTest.php +++ /dev/null @@ -1,912 +0,0 @@ -assertTrue($q instanceof ModelCriteria, 'Model query extends ModelCriteria'); - } - - public function testConstructor() - { - $query = new BookQuery(); - $this->assertEquals($query->getDbName(), 'bookstore', 'Constructor sets dabatase name'); - $this->assertEquals($query->getModelName(), 'Book', 'Constructor sets model name'); - } - - public function testCreate() - { - $query = BookQuery::create(); - $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); - $this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name'); - $this->assertEquals($query->getModelName(), 'Book', 'create() sets model name'); - $query = BookQuery::create('foo'); - $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); - $this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name'); - $this->assertEquals($query->getModelName(), 'Book', 'create() sets model name'); - $this->assertEquals($query->getModelAlias(), 'foo', 'create() can set the model alias'); - } - - public function testCreateCustom() - { - // see the myBookQuery class definition at the end of this file - $query = myCustomBookQuery::create(); - $this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class'); - $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); - $this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name'); - $this->assertEquals($query->getModelName(), 'Book', 'create() sets model name'); - $query = myCustomBookQuery::create('foo'); - $this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class'); - $this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name'); - $this->assertEquals($query->getModelName(), 'Book', 'create() sets model name'); - $this->assertEquals($query->getModelAlias(), 'foo', 'create() can set the model alias'); - } - - public function testBasePreSelect() - { - $method = new ReflectionMethod('Table2Query', 'basePreSelect'); - $this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreSelect() by default'); - - $method = new ReflectionMethod('Table3Query', 'basePreSelect'); - $this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreSelect() when a behavior is registered'); - } - - public function testBasePreDelete() - { - $method = new ReflectionMethod('Table2Query', 'basePreDelete'); - $this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreDelete() by default'); - - $method = new ReflectionMethod('Table3Query', 'basePreDelete'); - $this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreDelete() when a behavior is registered'); - } - - public function testBasePostDelete() - { - $method = new ReflectionMethod('Table2Query', 'basePostDelete'); - $this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostDelete() by default'); - - $method = new ReflectionMethod('Table3Query', 'basePostDelete'); - $this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostDelete() when a behavior is registered'); - } - - public function testBasePreUpdate() - { - $method = new ReflectionMethod('Table2Query', 'basePreUpdate'); - $this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreUpdate() by default'); - - $method = new ReflectionMethod('Table3Query', 'basePreUpdate'); - $this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreUpdate() when a behavior is registered'); - } - - public function testBasePostUpdate() - { - $method = new ReflectionMethod('Table2Query', 'basePostUpdate'); - $this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostUpdate() by default'); - - $method = new ReflectionMethod('Table3Query', 'basePostUpdate'); - $this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostUpdate() when a behavior is registered'); - } - - public function testQuery() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $q = new BookQuery(); - $book = $q - ->setModelAlias('b') - ->where('b.Title like ?', 'Don%') - ->orderBy('b.ISBN', 'desc') - ->findOne(); - $this->assertTrue($book instanceof Book); - $this->assertEquals('Don Juan', $book->getTitle()); - } - - public function testFindPk() - { - $method = new ReflectionMethod('Table4Query', 'findPk'); - $this->assertEquals('BaseTable4Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPk()'); - } - - public function testFindPkSimpleKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - BookPeer::clearInstancePool(); - $con = Propel::getConnection('bookstore'); - - // prepare the test data - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Id', 'desc'); - $testBook = $c->findOne(); - $count = $con->getQueryCount(); - - BookPeer::clearInstancePool(); - - $q = new BookQuery(); - $book = $q->findPk($testBook->getId()); - $this->assertEquals($testBook, $book, 'BaseQuery overrides findPk() to make it faster'); - $this->assertEquals($count+1, $con->getQueryCount(), 'findPk() issues a database query when instance pool is empty'); - - $q = new BookQuery(); - $book = $q->findPk($testBook->getId()); - $this->assertEquals($testBook, $book, 'BaseQuery overrides findPk() to make it faster'); - $this->assertEquals($count+1, $con->getQueryCount(), 'findPk() does not issue a database query when instance is in pool'); - } - - public function testFindPkCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - BookPeer::clearInstancePool(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRelTest = $c->findOne(); - $pk = $bookListRelTest->getPrimaryKey(); - - $q = new BookListRelQuery(); - $bookListRel = $q->findPk($pk); - $this->assertEquals($bookListRelTest, $bookListRel, 'BaseQuery overrides findPk() for composite primary keysto make it faster'); - } - - public function testFindPks() - { - $method = new ReflectionMethod('Table4Query', 'findPks'); - $this->assertEquals('BaseTable4Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPks()'); - } - - public function testFindPksSimpleKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - BookPeer::clearInstancePool(); - - // prepare the test data - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Id', 'desc'); - $testBooks = $c->find(); - $testBook1 = $testBooks->pop(); - $testBook2 = $testBooks->pop(); - - $q = new BookQuery(); - $books = $q->findPks(array($testBook1->getId(), $testBook2->getId())); - $this->assertEquals(array($testBook1, $testBook2), $books->getData(), 'BaseQuery overrides findPks() to make it faster'); - } - - public function testFindPksCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - BookPeer::clearInstancePool(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRelTest = $c->find(); - $search = array(); - foreach ($bookListRelTest as $obj) { - $search[]= $obj->getPrimaryKey(); - } - - $q = new BookListRelQuery(); - $objs = $q->findPks($search); - $this->assertEquals($bookListRelTest, $objs, 'BaseQuery overrides findPks() for composite primary keys to make it work'); - } - - public function testFilterBy() - { - foreach (BookPeer::getFieldNames(BasePeer::TYPE_PHPNAME) as $colName) { - $filterMethod = 'filterBy' . $colName; - $this->assertTrue(method_exists('BookQuery', $filterMethod), 'QueryBuilder adds filterByColumn() methods for every column'); - $q = BookQuery::create()->$filterMethod(1); - $this->assertTrue($q instanceof BookQuery, 'filterByColumn() returns the current query instance'); - } - } - - public function testFilterByPrimaryKeySimpleKey() - { - $q = BookQuery::create()->filterByPrimaryKey(12); - $q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK column'); - - $q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKey(12); - $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByPrimaryKey() uses true table alias if set'); - } - - public function testFilterByPrimaryKeyCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - BookPeer::clearInstancePool(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRelTest = $c->findOne(); - $pk = $bookListRelTest->getPrimaryKey(); - - $q = new BookListRelQuery(); - $q->filterByPrimaryKey($pk); - - $q1 = BookListRelQuery::create() - ->add(BookListRelPeer::BOOK_ID, $pk[0], Criteria::EQUAL) - ->add(BookListRelPeer::BOOK_CLUB_LIST_ID, $pk[1], Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK columns'); - } - - public function testFilterByPrimaryKeysSimpleKey() - { - $q = BookQuery::create()->filterByPrimaryKeys(array(10, 11, 12)); - $q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::IN); - $this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a Criteria::IN on the PK column'); - - $q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKeys(array(10, 11, 12)); - $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', array(10, 11, 12), Criteria::IN); - $this->assertEquals($q1, $q, 'filterByPrimaryKeys() uses true table alias if set'); - } - - public function testFilterByPrimaryKeysCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - BookPeer::clearInstancePool(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRelTest = $c->find(); - $search = array(); - foreach ($bookListRelTest as $obj) { - $search[]= $obj->getPrimaryKey(); - } - - $q = new BookListRelQuery(); - $q->filterByPrimaryKeys($search); - - $q1 = BookListRelQuery::create(); - foreach ($search as $key) { - $cton0 = $q1->getNewCriterion(BookListRelPeer::BOOK_ID, $key[0], Criteria::EQUAL); - $cton1 = $q1->getNewCriterion(BookListRelPeer::BOOK_CLUB_LIST_ID, $key[1], Criteria::EQUAL); - $cton0->addAnd($cton1); - $q1->addOr($cton0); - } - $this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a series of Criteria::EQUAL in the PK columns'); - } - - public function testFilterByIntegerPk() - { - $q = BookQuery::create()->filterById(12); - $q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::EQUAL by default'); - - $q = BookQuery::create()->filterById(12, Criteria::NOT_EQUAL); - $q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByPkColumn() accepts an optional comparison operator'); - - $q = BookQuery::create()->setModelAlias('b', true)->filterById(12); - $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByPkColumn() uses true table alias if set'); - - $q = BookQuery::create()->filterById(array(10, 11, 12)); - $q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::IN); - $this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::IN when passed a simple array key'); - - $q = BookQuery::create()->filterById(array(10, 11, 12), Criteria::NOT_IN); - $q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::NOT_IN); - $this->assertEquals($q1, $q, 'filterByPkColumn() accepts a comparison when passed a simple array key'); - } - - public function testFilterByNumber() - { - $q = BookQuery::create()->filterByPrice(12); - $q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::EQUAL by default'); - - $q = BookQuery::create()->filterByPrice(12, Criteria::NOT_EQUAL); - $q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() accepts an optional comparison operator'); - - $q = BookQuery::create()->setModelAlias('b', true)->filterByPrice(12); - $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.PRICE', 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() uses true table alias if set'); - - $q = BookQuery::create()->filterByPrice(array(10, 11, 12)); - $q1 = BookQuery::create()->add(BookPeer::PRICE, array(10, 11, 12), Criteria::IN); - $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::IN when passed a simple array key'); - - $q = BookQuery::create()->filterByPrice(array(10, 11, 12), Criteria::NOT_IN); - $q1 = BookQuery::create()->add(BookPeer::PRICE, array(10, 11, 12), Criteria::NOT_IN); - $this->assertEquals($q1, $q, 'filterByNumColumn() accepts a comparison when passed a simple array key'); - - $q = BookQuery::create()->filterByPrice(array('min' => 10)); - $q1 = BookQuery::create()->add(BookPeer::PRICE, 10, Criteria::GREATER_EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key'); - - $q = BookQuery::create()->filterByPrice(array('max' => 12)); - $q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::LESS_EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key'); - - $q = BookQuery::create()->filterByPrice(array('min' => 10, 'max' => 12)); - $q1 = BookQuery::create() - ->add(BookPeer::PRICE, 10, Criteria::GREATER_EQUAL) - ->addAnd(BookPeer::PRICE, 12, Criteria::LESS_EQUAL); - $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a between when passed both a \'min\' and a \'max\' key'); - } - - public function testFilterByTimestamp() - { - $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12); - $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::EQUAL by default'); - - $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12, Criteria::NOT_EQUAL); - $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() accepts an optional comparison operator'); - - $q = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->filterByCreated(12); - $q1 = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->add('b.CREATED', 12, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() uses true table alias if set'); - - $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('min' => 10)); - $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 10, Criteria::GREATER_EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key'); - - $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('max' => 12)); - $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::LESS_EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key'); - - $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('min' => 10, 'max' => 12)); - $q1 = BookstoreEmployeeAccountQuery::create() - ->add(BookstoreEmployeeAccountPeer::CREATED, 10, Criteria::GREATER_EQUAL) - ->addAnd(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::LESS_EQUAL); - $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a between when passed both a \'min\' and a \'max\' key'); - } - - public function testFilterByString() - { - $q = BookQuery::create()->filterByTitle('foo'); - $q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo', Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::EQUAL by default'); - - $q = BookQuery::create()->filterByTitle('foo', Criteria::NOT_EQUAL); - $q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo', Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByStringColumn() accepts an optional comparison operator'); - - $q = BookQuery::create()->setModelAlias('b', true)->filterByTitle('foo'); - $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.TITLE', 'foo', Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByStringColumn() uses true table alias if set'); - - $q = BookQuery::create()->filterByTitle(array('foo', 'bar')); - $q1 = BookQuery::create()->add(BookPeer::TITLE, array('foo', 'bar'), Criteria::IN); - $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::IN when passed an array'); - - $q = BookQuery::create()->filterByTitle(array('foo', 'bar'), Criteria::NOT_IN); - $q1 = BookQuery::create()->add(BookPeer::TITLE, array('foo', 'bar'), Criteria::NOT_IN); - $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed an array'); - - $q = BookQuery::create()->filterByTitle('foo%'); - $q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::LIKE); - $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a % wildcard'); - - $q = BookQuery::create()->filterByTitle('foo%', Criteria::NOT_LIKE); - $q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::NOT_LIKE); - $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard'); - - $q = BookQuery::create()->filterByTitle('foo%', Criteria::EQUAL); - $q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard'); - - $q = BookQuery::create()->filterByTitle('*foo'); - $q1 = BookQuery::create()->add(BookPeer::TITLE, '%foo', Criteria::LIKE); - $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a * wildcard, and turns * into %'); - - $q = BookQuery::create()->filterByTitle('*f%o*o%'); - $q1 = BookQuery::create()->add(BookPeer::TITLE, '%f%o%o%', Criteria::LIKE); - $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with mixed wildcards, and turns *s into %s'); - } - - public function testFilterByBoolean() - { - $q = ReviewQuery::create()->filterByRecommended(true); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default'); - - $q = ReviewQuery::create()->filterByRecommended(true, Criteria::NOT_EQUAL); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() accepts an optional comparison operator'); - - $q = ReviewQuery::create()->filterByRecommended(false); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default'); - - $q = ReviewQuery::create()->setModelAlias('b', true)->filterByRecommended(true); - $q1 = ReviewQuery::create()->setModelAlias('b', true)->add('b.RECOMMENDED', true, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() uses true table alias if set'); - - $q = ReviewQuery::create()->filterByRecommended('true'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); - - $q = ReviewQuery::create()->filterByRecommended('yes'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); - - $q = ReviewQuery::create()->filterByRecommended('1'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); - - $q = ReviewQuery::create()->filterByRecommended('false'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); - - $q = ReviewQuery::create()->filterByRecommended('no'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); - - $q = ReviewQuery::create()->filterByRecommended('0'); - $q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); - } - - public function testFilterByFk() - { - $this->assertTrue(method_exists('BookQuery', 'filterByAuthor'), 'QueryBuilder adds filterByFk() methods'); - $this->assertTrue(method_exists('BookQuery', 'filterByPublisher'), 'QueryBuilder adds filterByFk() methods for all fkeys'); - - $this->assertTrue(method_exists('EssayQuery', 'filterByAuthorRelatedByFirstAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table'); - $this->assertTrue(method_exists('EssayQuery', 'filterByAuthorRelatedBySecondAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table'); - } - - public function testFilterByFkSimpleKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // prepare the test data - $testBook = BookQuery::create() - ->innerJoin('Book.Author') // just in case there are books with no author - ->findOne(); - $testAuthor = $testBook->getAuthor(); - - $book = BookQuery::create() - ->filterByAuthor($testAuthor) - ->findOne(); - $this->assertEquals($testBook, $book, 'Generated query handles filterByFk() methods correctly for simple fkeys'); - - $q = BookQuery::create()->filterByAuthor($testAuthor); - $q1 = BookQuery::create()->add(BookPeer::AUTHOR_ID, $testAuthor->getId(), Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByFk() translates to a Criteria::EQUAL by default'); - - $q = BookQuery::create()->filterByAuthor($testAuthor, Criteria::NOT_EQUAL); - $q1 = BookQuery::create()->add(BookPeer::AUTHOR_ID, $testAuthor->getId(), Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByFk() accepts an optional comparison operator'); - } - - public function testFilterByFkCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - BookstoreDataPopulator::populateOpinionFavorite(); - - // prepare the test data - $testOpinion = BookOpinionQuery::create() - ->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author - ->findOne(); - $testFavorite = $testOpinion->getReaderFavorite(); - - $favorite = ReaderFavoriteQuery::create() - ->filterByBookOpinion($testOpinion) - ->findOne(); - $this->assertEquals($testFavorite, $favorite, 'Generated query handles filterByFk() methods correctly for composite fkeys'); - } - - public function testFilterByRefFk() - { - $this->assertTrue(method_exists('BookQuery', 'filterByReview'), 'QueryBuilder adds filterByRefFk() methods'); - $this->assertTrue(method_exists('BookQuery', 'filterByMedia'), 'QueryBuilder adds filterByRefFk() methods for all fkeys'); - - $this->assertTrue(method_exists('AuthorQuery', 'filterByEssayRelatedByFirstAuthor'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table'); - $this->assertTrue(method_exists('AuthorQuery', 'filterByEssayRelatedBySecondAuthor'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table'); - } - - public function testFilterByRefFkSimpleKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // prepare the test data - $testBook = BookQuery::create() - ->innerJoin('Book.Author') // just in case there are books with no author - ->findOne(); - $testAuthor = $testBook->getAuthor(); - - $author = AuthorQuery::create() - ->filterByBook($testBook) - ->findOne(); - $this->assertEquals($testAuthor, $author, 'Generated query handles filterByRefFk() methods correctly for simple fkeys'); - - $q = AuthorQuery::create()->filterByBook($testBook); - $q1 = AuthorQuery::create()->add(AuthorPeer::ID, $testBook->getAuthorId(), Criteria::EQUAL); - $this->assertEquals($q1, $q, 'filterByRefFk() translates to a Criteria::EQUAL by default'); - - $q = AuthorQuery::create()->filterByBook($testBook, Criteria::NOT_EQUAL); - $q1 = AuthorQuery::create()->add(AuthorPeer::ID, $testBook->getAuthorId(), Criteria::NOT_EQUAL); - $this->assertEquals($q1, $q, 'filterByRefFk() accepts an optional comparison operator'); - } - - public function testFilterByRefFkCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - BookstoreDataPopulator::populateOpinionFavorite(); - - // prepare the test data - $testOpinion = BookOpinionQuery::create() - ->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author - ->findOne(); - $testFavorite = $testOpinion->getReaderFavorite(); - - $opinion = BookOpinionQuery::create() - ->filterByReaderFavorite($testFavorite) - ->findOne(); - $this->assertEquals($testOpinion, $opinion, 'Generated query handles filterByRefFk() methods correctly for composite fkeys'); - } - - public function testFilterByCrossFK() - { - $this->assertTrue(method_exists('BookQuery', 'filterByBookClubList'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships'); - $this->assertFalse(method_exists('BookQuery', 'filterByBook'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships'); - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - $blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs'); - $nbBooks = BookQuery::create() - ->filterByBookClubList($blc1) - ->count(); - $this->assertEquals(2, $nbBooks, 'Generated query handles filterByCrossRefFK() methods correctly'); - } - - public function testJoinFk() - { - $q = BookQuery::create() - ->joinAuthor(); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() translates to a left join on non-required columns'); - - $q = ReviewQuery::create() - ->joinBook(); - $q1 = ReviewQuery::create() - ->join('Review.Book', Criteria::INNER_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() translates to an inner join on required columns'); - - $q = BookQuery::create() - ->joinAuthor('a'); - $q1 = BookQuery::create() - ->join('Book.Author a', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() accepts a relation alias as first parameter'); - - $q = BookQuery::create() - ->joinAuthor('', Criteria::INNER_JOIN); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::INNER_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() accepts a join type as second parameter'); - - $q = EssayQuery::create() - ->joinAuthorRelatedBySecondAuthor(); - $q1 = EssayQuery::create() - ->join('Essay.AuthorRelatedBySecondAuthor', "INNER JOIN"); - $this->assertTrue($q->equals($q1), 'joinFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema'); - } - - public function testJoinFkAlias() - { - $q = BookQuery::create('b') - ->joinAuthor('a'); - $q1 = BookQuery::create('b') - ->join('b.Author a', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() works fine with table aliases'); - - $q = BookQuery::create() - ->setModelAlias('b', true) - ->joinAuthor('a'); - $q1 = BookQuery::create() - ->setModelAlias('b', true) - ->join('b.Author a', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinFk() works fine with true table aliases'); - } - - public function testJoinRefFk() - { - $q = AuthorQuery::create() - ->joinBook(); - $q1 = AuthorQuery::create() - ->join('Author.Book', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinRefFk() translates to a left join on non-required columns'); - - $q = BookQuery::create() - ->joinreview(); - $q1 = BookQuery::create() - ->join('Book.Review', Criteria::INNER_JOIN); - $this->assertTrue($q->equals($q1), 'joinRefFk() translates to an inner join on required columns'); - - $q = AuthorQuery::create() - ->joinBook('b'); - $q1 = AuthorQuery::create() - ->join('Author.Book b', Criteria::LEFT_JOIN); - $this->assertTrue($q->equals($q1), 'joinRefFk() accepts a relation alias as first parameter'); - - $q = AuthorQuery::create() - ->joinBook('', Criteria::INNER_JOIN); - $q1 = AuthorQuery::create() - ->join('Author.Book', Criteria::INNER_JOIN); - $this->assertTrue($q->equals($q1), 'joinRefFk() accepts a join type as second parameter'); - - $q = AuthorQuery::create() - ->joinEssayRelatedBySecondAuthor(); - $q1 = AuthorQuery::create() - ->join('Author.EssayRelatedBySecondAuthor', Criteria::INNER_JOIN); - $this->assertTrue($q->equals($q1), 'joinRefFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema'); - } - - public function testUseFkQuerySimple() - { - $q = BookQuery::create() - ->useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse(); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on a left join on non-required columns'); - - $q = ReviewQuery::create() - ->useBookQuery() - ->filterByTitle('War And Peace') - ->endUse(); - $q1 = ReviewQuery::create() - ->join('Review.Book', Criteria::INNER_JOIN) - ->add(BookPeer::TITLE, 'War And Peace', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on aninner join on required columns'); - } - - public function testUseFkQueryJoinType() - { - $q = BookQuery::create() - ->useAuthorQuery(null, Criteria::LEFT_JOIN) - ->filterByFirstName('Leo') - ->endUse(); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() accepts a join type as second parameter'); - } - - public function testUseFkQueryAlias() - { - $q = BookQuery::create() - ->useAuthorQuery('a') - ->filterByFirstName('Leo') - ->endUse(); - $join = new ModelJoin(); - $join->setJoinType(Criteria::LEFT_JOIN); - $join->setTableMap(AuthorPeer::getTableMap()); - $join->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'a'); - $join->setRelationAlias('a'); - $q1 = BookQuery::create() - ->addAlias('a', AuthorPeer::TABLE_NAME) - ->addJoinObject($join, 'a') - ->add('a.FIRST_NAME', 'Leo', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() uses the first argument as a table alias'); - } - - public function testUseFkQueryMixed() - { - $q = BookQuery::create() - ->useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->filterByTitle('War And Peace'); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL) - ->add(BookPeer::TITLE, 'War And Peace', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() allows combining conditions on main and related query'); - } - - public function testUseFkQueryTwice() - { - $q = BookQuery::create() - ->useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->useAuthorQuery() - ->filterByLastName('Tolstoi') - ->endUse(); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL) - ->add(AuthorPeer::LAST_NAME, 'Tolstoi', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation does not create two joins'); - } - - public function testUseFkQueryTwiceTwoAliases() - { - $q = BookQuery::create() - ->useAuthorQuery('a') - ->filterByFirstName('Leo') - ->endUse() - ->useAuthorQuery('b') - ->filterByLastName('Tolstoi') - ->endUse(); - $join1 = new ModelJoin(); - $join1->setJoinType(Criteria::LEFT_JOIN); - $join1->setTableMap(AuthorPeer::getTableMap()); - $join1->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'a'); - $join1->setRelationAlias('a'); - $join2 = new ModelJoin(); - $join2->setJoinType(Criteria::LEFT_JOIN); - $join2->setTableMap(AuthorPeer::getTableMap()); - $join2->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'b'); - $join2->setRelationAlias('b'); - $q1 = BookQuery::create() - ->addAlias('a', AuthorPeer::TABLE_NAME) - ->addJoinObject($join1, 'a') - ->add('a.FIRST_NAME', 'Leo', Criteria::EQUAL) - ->addAlias('b', AuthorPeer::TABLE_NAME) - ->addJoinObject($join2, 'b') - ->add('b.LAST_NAME', 'Tolstoi', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation with two aliases creates two joins'); - } - - public function testUseFkQueryNested() - { - $q = ReviewQuery::create() - ->useBookQuery() - ->useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->endUse(); - $q1 = ReviewQuery::create() - ->join('Review.Book', Criteria::INNER_JOIN) - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL); - // embedded queries create joins that keep a relation to the parent - // as this is not testable, we need to use another testing technique - $params = array(); - $result = BasePeer::createSelectSql($q, $params); - $expectedParams = array(); - $expectedResult = BasePeer::createSelectSql($q1, $expectedParams); - $this->assertEquals($expectedParams, $params, 'useFkQuery() called nested creates two joins'); - $this->assertEquals($expectedResult, $result, 'useFkQuery() called nested creates two joins'); - } - - public function testUseFkQueryTwoRelations() - { - $q = BookQuery::create() - ->useAuthorQuery() - ->filterByFirstName('Leo') - ->endUse() - ->usePublisherQuery() - ->filterByName('Penguin') - ->endUse(); - $q1 = BookQuery::create() - ->join('Book.Author', Criteria::LEFT_JOIN) - ->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL) - ->join('Book.Publisher', Criteria::LEFT_JOIN) - ->add(PublisherPeer::NAME, 'Penguin', Criteria::EQUAL); - $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on two relations creates two joins'); - } - - public function testPrune() - { - $q = BookQuery::create()->prune(); - $this->assertTrue($q instanceof BookQuery, 'prune() returns the current Query object'); - } - - public function testPruneSimpleKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $nbBooks = BookQuery::create()->prune()->count(); - $this->assertEquals(4, $nbBooks, 'prune() does nothing when passed a null object'); - - $testBook = BookQuery::create()->findOne(); - $nbBooks = BookQuery::create()->prune($testBook)->count(); - $this->assertEquals(3, $nbBooks, 'prune() removes an object from the result'); - } - - public function testPruneCompositeKey() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - BookPeer::clearInstancePool(); - - $nbBookListRel = BookListRelQuery::create()->prune()->count(); - $this->assertEquals(2, $nbBookListRel, 'prune() does nothing when passed a null object'); - - $testBookListRel = BookListRelQuery::create()->findOne(); - $nbBookListRel = BookListRelQuery::create()->prune($testBookListRel)->count(); - $this->assertEquals(1, $nbBookListRel, 'prune() removes an object from the result'); - } -} - -class myCustomBookQuery extends BookQuery -{ - public static function create($modelAlias = null, $criteria = null) - { - if ($criteria instanceof myCustomBookQuery) { - return $criteria; - } - $query = new myCustomBookQuery(); - if (null !== $modelAlias) { - $query->setModelAlias($modelAlias); - } - if ($criteria instanceof Criteria) { - $query->mergeWith($criteria); - } - return $query; - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/util/PropelTemplateTest.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/util/PropelTemplateTest.php deleted file mode 100644 index bba32ac12..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/util/PropelTemplateTest.php +++ /dev/null @@ -1,54 +0,0 @@ -setTemplate('Hello, '); - $res = $t->render(); - $this->assertEquals('Hello, 3', $res); - } - - public function testRenderStringOneParam() - { - $t = new PropelTemplate(); - $t->setTemplate('Hello, '); - $res = $t->render(array('name' => 'John')); - $this->assertEquals('Hello, John', $res); - } - - public function testRenderStringParams() - { - $time = time(); - $t = new PropelTemplate(); - $t->setTemplate('Hello, , it is to go!'); - $res = $t->render(array('name' => 'John', 'time' => $time)); - $this->assertEquals('Hello, John, it is ' . $time . ' to go!', $res); - } - - public function testRenderFile() - { - $t = new PropelTemplate(); - $t->setTemplateFile(dirname(__FILE__).'/template.php'); - $res = $t->render(array('name' => 'John')); - $this->assertEquals('Hello, John', $res); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/builder/util/template.php b/airtime_mvc/library/propel/test/testsuite/generator/builder/util/template.php deleted file mode 100644 index 2ae040501..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/builder/util/template.php +++ /dev/null @@ -1 +0,0 @@ -Hello, \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/model/BehaviorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/model/BehaviorTest.php deleted file mode 100644 index af1daecb8..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/model/BehaviorTest.php +++ /dev/null @@ -1,113 +0,0 @@ -Martin Poeschl - * @version $Revision: 1773 $ - * @package generator.model - */ -class BehaviorTest extends PHPUnit_Framework_TestCase { - - private $xmlToAppData; - private $appData; - - public function testSetupObject() - { - $b = new Behavior(); - $b->loadFromXML(array('name' => 'foo')); - $this->assertEquals($b->getName(), 'foo', 'setupObject() sets the Behavior name from XML attributes'); - } - - public function testName() - { - $b = new Behavior(); - $this->assertNull($b->getName(), 'Behavior name is null by default'); - $b->setName('foo'); - $this->assertEquals($b->getName(), 'foo', 'setName() sets the name, and getName() gets it'); - } - - public function testTable() - { - $b = new Behavior(); - $this->assertNull($b->getTable(), 'Behavior Table is null by default'); - $t = new Table(); - $t->setName('fooTable'); - $b->setTable($t); - $this->assertEquals($b->getTable(), $t, 'setTable() sets the name, and getTable() gets it'); - } - - public function testParameters() - { - $b = new Behavior(); - $this->assertEquals($b->getParameters(), array(), 'Behavior parameters is an empty array by default'); - $b->addParameter(array('name' => 'foo', 'value' => 'bar')); - $this->assertEquals($b->getParameters(), array('foo' => 'bar'), 'addParameter() sets a parameter from an associative array'); - $b->addParameter(array('name' => 'foo2', 'value' => 'bar2')); - $this->assertEquals($b->getParameters(), array('foo' => 'bar', 'foo2' => 'bar2'), 'addParameter() adds a parameter from an associative array'); - $b->addParameter(array('name' => 'foo', 'value' => 'bar3')); - $this->assertEquals($b->getParameters(), array('foo' => 'bar3', 'foo2' => 'bar2'), 'addParameter() changes a parameter from an associative array'); - $this->assertEquals($b->getParameter('foo'), 'bar3', 'getParameter() retrieves a parameter value by name'); - $b->setParameters(array('foo3' => 'bar3', 'foo4' => 'bar4')); - $this->assertEquals($b->getParameters(), array('foo3' => 'bar3', 'foo4' => 'bar4'), 'setParameters() changes the whole parameter array'); - } - - /** - * test if the tables get the package name from the properties file - * - */ - public function testXmlToAppData() - { - include_once 'builder/util/XmlToAppData.php'; - $this->xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - $this->appData = $this->xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml'); - $table = $this->appData->getDatabase("bookstore-behavior")->getTable('table1'); - $behaviors = $table->getBehaviors(); - $this->assertEquals(count($behaviors), 1, 'XmlToAppData ads as many behaviors as there are behaviors tags'); - $behavior = $table->getBehavior('timestampable'); - $this->assertEquals($behavior->getTable()->getName(), 'table1', 'XmlToAppData sets the behavior table correctly'); - $this->assertEquals($behavior->getParameters(), array('create_column' => 'created_on', 'update_column' => 'updated_on'), 'XmlToAppData sets the behavior parameters correctly'); - } - - public function testMofifyTable() - { - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php'); - $tmap = Propel::getDatabaseMap(Table2Peer::DATABASE_NAME)->getTable(Table2Peer::TABLE_NAME); - $this->assertEquals(count($tmap->getColumns()), 4, 'A behavior can modify its table by implementing modifyTable()'); - } - - public function testModifyDatabase() - { - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - require_once dirname(__FILE__) . '/../../../../runtime/lib/Propel.php'; - Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php'); - $tmap = Propel::getDatabaseMap(Table3Peer::DATABASE_NAME)->getTable(Table3Peer::TABLE_NAME); - $this->assertTrue(array_key_exists('do_nothing', $tmap->getBehaviors()), 'A database behavior is automatically copied to all its table'); - } - - public function testGetColumnForParameter() - { - $this->xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - $this->appData = $this->xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml'); - - $table = $this->appData->getDatabase("bookstore-behavior")->getTable('table1'); - $behavior = $table->getBehavior('timestampable'); - $this->assertEquals($table->getColumn('created_on'), $behavior->getColumnForParameter('create_column'), 'getColumnForParameter() returns the configured column for behavior based on a parameter name'); - - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/model/ColumnTest.php b/airtime_mvc/library/propel/test/testsuite/generator/model/ColumnTest.php deleted file mode 100644 index dbaf69432..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/model/ColumnTest.php +++ /dev/null @@ -1,81 +0,0 @@ -Martin Poeschl - * @version $Revision: 1612 $ - * @package generator.model - */ -class ColumnTest extends PHPUnit_Framework_TestCase { - - /** - * Tests static Column::makeList() method. - * @deprecated - Column::makeList() is deprecated and set to be removed in 1.3 - */ - public function testMakeList() - { - $expected = "`Column0`, `Column1`, `Column2`, `Column3`, `Column4`"; - $objArray = array(); - for ($i=0; $i<5; $i++) { - $c = new Column(); - $c->setName("Column" . $i); - $objArray[] = $c; - } - - $list = Column::makeList($objArray, new MySQLPlatform()); - $this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true))); - - $strArray = array(); - for ($i=0; $i<5; $i++) { - $strArray[] = "Column" . $i; - } - - $list = Column::makeList($strArray, new MySQLPlatform()); - $this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true))); - - } - - public function testPhpNamingMethod() - { - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php'); - $bookTmap = Propel::getDatabaseMap(BookPeer::DATABASE_NAME)->getTable(BookPeer::TABLE_NAME); - $this->assertEquals('AuthorId', $bookTmap->getColumn('AUTHOR_ID')->getPhpName(), 'setPhpName() uses the default phpNamingMethod'); - $pageTmap = Propel::getDatabaseMap(PagePeer::DATABASE_NAME)->getTable(PagePeer::TABLE_NAME); - $this->assertEquals('LeftChild', $pageTmap->getColumn('LEFTCHILD')->getPhpName(), 'setPhpName() uses the configured phpNamingMethod'); - } - - public function testGetConstantName() - { - $xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - $appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml'); - $column = $appData->getDatabase("bookstore-behavior")->getTable('table1')->getColumn('title'); - $this->assertEquals('Table1Peer::TITLE', $column->getConstantName(), 'getConstantName() returns the complete constant name by default'); - } - - public function testIsLocalColumnsRequired() - { - $xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - $appData = $xmlToAppData->parseFile('fixtures/bookstore/schema.xml'); - $fk = $appData->getDatabase("bookstore")->getTable('book')->getColumnForeignKeys('publisher_id'); - $this->assertFalse($fk[0]->isLocalColumnsRequired()); - $fk = $appData->getDatabase("bookstore")->getTable('review')->getColumnForeignKeys('book_id'); - $this->assertTrue($fk[0]->isLocalColumnsRequired()); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/model/NameFactoryTest.php b/airtime_mvc/library/propel/test/testsuite/generator/model/NameFactoryTest.php deleted file mode 100644 index e65ae05f4..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/model/NameFactoryTest.php +++ /dev/null @@ -1,151 +0,0 @@ -Unit tests for class NameFactory and known - * NameGenerator implementations.

- * - *

To add more tests, add entries to the ALGORITHMS, - * INPUTS, and OUTPUTS arrays, and code to - * the makeInputs() method.

- * - *

This test assumes that it's being run using the MySQL database - * adapter, DBMM. MySQL has a column length limit of 64 - * characters.

- * - * @author Daniel Rall - * @version $Id: NameFactoryTest.php 1612 2010-03-16 22:56:21Z francois $ - * @package generator.model - */ -class NameFactoryTest extends BaseTestCase -{ - /** The database to mimic in generating the SQL. */ - const DATABASE_TYPE = "mysql"; - - /** - * The list of known name generation algorithms, specified as the - * fully qualified class names to NameGenerator - * implementations. - */ - private static $ALGORITHMS = array(NameFactory::CONSTRAINT_GENERATOR, NameFactory::PHP_GENERATOR); - - /** - * Two dimensional arrays of inputs for each algorithm. - */ - private static $INPUTS = array(); - - - /** - * Given the known inputs, the expected name outputs. - */ - private static $OUTPUTS = array(); - - /** - * Used as an input. - */ - private $database; - - /** - * Creates a new instance. - * - */ - public function __construct() { - - self::$INPUTS = array( - array( array(self::makeString(61), "I", 1), - array(self::makeString(61), "I", 2), - array(self::makeString(65), "I", 3), - array(self::makeString(4), "FK", 1), - array(self::makeString(5), "FK", 2) - ), - array( - array("MY_USER", NameGenerator::CONV_METHOD_UNDERSCORE), - array("MY_USER", NameGenerator::CONV_METHOD_PHPNAME), - array("MY_USER", NameGenerator::CONV_METHOD_NOCHANGE) - ) - ); - - - self::$OUTPUTS = array( - array( - self::makeString(60) . "_I_1", - self::makeString(60) . "_I_2", - self::makeString(60) . "_I_3", - self::makeString(4) . "_FK_1", - self::makeString(5) . "_FK_2"), - array("MyUser", "MYUSER", "MY_USER") - ); - - } - - /** - * Creates a string of the specified length consisting entirely of - * the character A. Useful for simulating table - * names, etc. - * - * @param int $len the number of characters to include in the string - * @return a string of length len with every character an 'A' - */ - private static function makeString($len) { - $buf = ""; - for ($i = 0; $i < $len; $i++) { - $buf .= 'A'; - } - return $buf; - } - - /** Sets up the Propel model. */ - public function setUp() - { - $appData = new AppData(new MysqlPlatform()); - $this->database = new Database(); - $appData->addDatabase($this->database); - } - - /** - * @throws Exception on fail - */ - public function testNames() { - for ($algoIndex = 0; $algoIndex < count(self::$ALGORITHMS); $algoIndex++) { - $algo = self::$ALGORITHMS[$algoIndex]; - $algoInputs = self::$INPUTS[$algoIndex]; - for ($i = 0; $i < count($algoInputs); $i++) { - $inputs = $this->makeInputs($algo, $algoInputs[$i]); - $generated = NameFactory::generateName($algo, $inputs); - $expected = self::$OUTPUTS[$algoIndex][$i]; - $this->assertEquals($expected, $generated, 0, "Algorithm " . $algo . " failed to generate an unique name"); - } - } - } - - /** - * Creates the list of arguments to pass to the specified type of - * NameGenerator implementation. - * - * @param algo The class name of the NameGenerator to - * create an argument list for. - * @param inputs The (possibly partial) list inputs from which to - * generate the final list. - * @return the list of arguments to pass to the NameGenerator - */ - private function makeInputs($algo, $inputs) - { - if (NameFactory::CONSTRAINT_GENERATOR == $algo) { - array_unshift($inputs, $this->database); - } - return $inputs; - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/model/PhpNameGeneratorTest.php b/airtime_mvc/library/propel/test/testsuite/generator/model/PhpNameGeneratorTest.php deleted file mode 100644 index ecde25cc6..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/model/PhpNameGeneratorTest.php +++ /dev/null @@ -1,55 +0,0 @@ -Martin Poeschl - * @version $Revision: 1612 $ - * @package generator.model - */ -class PhpNameGeneratorTest extends PHPUnit_Framework_TestCase -{ - public static function testPhpnameMethodDataProvider() - { - return array( - array('foo', 'Foo'), - array('Foo', 'Foo'), - array('FOO', 'FOO'), - array('123', '123'), - array('foo_bar', 'FooBar'), - array('bar_1', 'Bar1'), - array('bar_0', 'Bar0'), - array('my_CLASS_name', 'MyCLASSName'), - ); - } - - /** - * @dataProvider testPhpnameMethodDataProvider - */ - public function testPhpnameMethod($input, $output) - { - $generator = new TestablePhpNameGenerator(); - $this->assertEquals($output, $generator->phpnameMethod($input)); - } - -} - -class TestablePhpNameGenerator extends PhpNameGenerator -{ - public function phpnameMethod($schemaName) - { - return parent::phpnameMethod($schemaName); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/generator/model/TableTest.php b/airtime_mvc/library/propel/test/testsuite/generator/model/TableTest.php deleted file mode 100644 index d77a52f1a..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/model/TableTest.php +++ /dev/null @@ -1,109 +0,0 @@ -xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - - //$this->appData = $this->xmlToAppData->parseFile(dirname(__FILE__) . "/tabletest-schema.xml"); - $this->appData = $this->xmlToAppData->parseFile("etc/schema/tabletest-schema.xml"); - - $db = $this->appData->getDatabase("iddb"); - $expected = IDMethod::NATIVE; - $result = $db->getDefaultIdMethod(); - $this->assertEquals($expected, $result); - - $table2 = $db->getTable("table_native"); - $expected = IDMethod::NATIVE; - $result = $table2->getIdMethod(); - $this->assertEquals($expected, $result); - - $table = $db->getTable("table_none"); - $expected = IDMethod::NO_ID_METHOD; - $result = $table->getIdMethod(); - $this->assertEquals($expected, $result); - } - - public function testGeneratorConfig() - { - $xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null); - $appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml'); - $table = $appData->getDatabase("bookstore-behavior")->getTable('table1'); - $config = new GeneratorConfig(); - $config->setBuildProperties(array('propel.foo.bar.class' => 'bazz')); - $table->getDatabase()->getAppData()->getPlatform()->setGeneratorConfig($config); - $this->assertThat($table->getGeneratorConfig(), $this->isInstanceOf('GeneratorConfig'), 'getGeneratorConfig() returns an instance of the generator configuration'); - $this->assertEquals($table->getGeneratorConfig()->getBuildProperty('fooBarClass'), 'bazz', 'getGeneratorConfig() returns the instance of the generator configuration used in the platform'); - } - - public function testAddBehavior() - { - $platform = new MysqlPlatform(); - $config = new GeneratorConfig(); - $config->setBuildProperties(array( - 'propel.behavior.timestampable.class' => 'behavior.TimestampableBehavior' - )); - $platform->setGeneratorConfig($config); - $xmlToAppData = new XmlToAppData($platform, "defaultpackage", null); - $appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml'); - $table = $appData->getDatabase("bookstore-behavior")->getTable('table1'); - $this->assertThat($table->getBehavior('timestampable'), $this->isInstanceOf('TimestampableBehavior'), 'addBehavior() uses the behavior class defined in build.properties'); - } - - public function testUniqueColumnName() - { - $platform = new MysqlPlatform(); - $config = new GeneratorConfig(); - $platform->setGeneratorConfig($config); - $xmlToAppData = new XmlToAppData($platform, 'defaultpackage', null); - try - { - $appData = $xmlToAppData->parseFile('fixtures/unique-column/column-schema.xml'); - $this->fail('Parsing file with duplicate column names in one table throws exception'); - } catch (EngineException $e) { - $this->assertTrue(true, 'Parsing file with duplicate column names in one table throws exception'); - } - } - - public function testUniqueTableName() - { - $platform = new MysqlPlatform(); - $config = new GeneratorConfig(); - $platform->setGeneratorConfig($config); - $xmlToAppData = new XmlToAppData($platform, 'defaultpackage', null); - try { - $appData = $xmlToAppData->parseFile('fixtures/unique-column/table-schema.xml'); - $this->fail('Parsing file with duplicate table name throws exception'); - } catch (EngineException $e) { - $this->assertTrue(true, 'Parsing file with duplicate table name throws exception'); - } - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/platform/DefaultPlatformTest.php b/airtime_mvc/library/propel/test/testsuite/generator/platform/DefaultPlatformTest.php deleted file mode 100644 index db1c91ef9..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/platform/DefaultPlatformTest.php +++ /dev/null @@ -1,45 +0,0 @@ -getPlatform(); - - $unquoted = "Nice"; - $quoted = $p->quote($unquoted); - - $this->assertEquals("'$unquoted'", $quoted); - - - $unquoted = "Naughty ' string"; - $quoted = $p->quote($unquoted); - $expected = "'Naughty '' string'"; - $this->assertEquals($expected, $quoted); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/platform/PlatformTestBase.php b/airtime_mvc/library/propel/test/testsuite/generator/platform/PlatformTestBase.php deleted file mode 100644 index f384ca8c0..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/platform/PlatformTestBase.php +++ /dev/null @@ -1,55 +0,0 @@ -platform = new $clazz(); - } - - /** - * - */ - protected function tearDown() - { - parent::tearDown(); - } - - /** - * - * @return Platform - */ - protected function getPlatform() - { - return $this->platform; - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/generator/platform/SqlitePlatformTest.php b/airtime_mvc/library/propel/test/testsuite/generator/platform/SqlitePlatformTest.php deleted file mode 100644 index 4380485e3..000000000 --- a/airtime_mvc/library/propel/test/testsuite/generator/platform/SqlitePlatformTest.php +++ /dev/null @@ -1,48 +0,0 @@ -pdo = new PDO("sqlite::memory:"); - - } - - public function tearDown() - { - parent::tearDown(); - } - - public function testQuoteConnected() - { - $p = $this->getPlatform(); - $p->setConnection($this->pdo); - - $unquoted = "Naughty ' string"; - $quoted = $p->quote($unquoted); - - $expected = "'Naughty '' string'"; - $this->assertEquals($expected, $quoted); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/misc/BookstoreTest.php b/airtime_mvc/library/propel/test/testsuite/misc/BookstoreTest.php deleted file mode 100644 index c0f63e28e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/misc/BookstoreTest.php +++ /dev/null @@ -1,870 +0,0 @@ - - * @package misc - */ -class BookstoreTest extends BookstoreEmptyTestBase -{ - public function testScenario() - { - // Add publisher records - // --------------------- - - try { - $scholastic = new Publisher(); - $scholastic->setName("Scholastic"); - // do not save, will do later to test cascade - - $morrow = new Publisher(); - $morrow->setName("William Morrow"); - $morrow->save(); - $morrow_id = $morrow->getId(); - - $penguin = new Publisher(); - $penguin->setName("Penguin"); - $penguin->save(); - $penguin_id = $penguin->getId(); - - $vintage = new Publisher(); - $vintage->setName("Vintage"); - $vintage->save(); - $vintage_id = $vintage->getId(); - $this->assertTrue(true, 'Save Publisher records'); - } catch (Exception $e) { - $this->fail('Save publisher records'); - } - - // Add author records - // ------------------ - - try { - $rowling = new Author(); - $rowling->setFirstName("J.K."); - $rowling->setLastName("Rowling"); - // do not save, will do later to test cascade - - $stephenson = new Author(); - $stephenson->setFirstName("Neal"); - $stephenson->setLastName("Stephenson"); - $stephenson->save(); - $stephenson_id = $stephenson->getId(); - - $byron = new Author(); - $byron->setFirstName("George"); - $byron->setLastName("Byron"); - $byron->save(); - $byron_id = $byron->getId(); - - $grass = new Author(); - $grass->setFirstName("Gunter"); - $grass->setLastName("Grass"); - $grass->save(); - $grass_id = $grass->getId(); - $this->assertTrue(true, 'Save Author records'); - } catch (Exception $e) { - $this->fail('Save Author records'); - } - - // Add book records - // ---------------- - - try { - $phoenix = new Book(); - $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); - $phoenix->setISBN("043935806X"); - $phoenix->setAuthor($rowling); - $phoenix->setPublisher($scholastic); - $phoenix->save(); - $phoenix_id = $phoenix->getId(); - $this->assertFalse($rowling->isNew(), 'saving book also saves related author'); - $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher'); - - $qs = new Book(); - $qs->setISBN("0380977427"); - $qs->setTitle("Quicksilver"); - $qs->setAuthor($stephenson); - $qs->setPublisher($morrow); - $qs->save(); - $qs_id = $qs->getId(); - - $dj = new Book(); - $dj->setISBN("0140422161"); - $dj->setTitle("Don Juan"); - $dj->setAuthor($byron); - $dj->setPublisher($penguin); - $dj->save(); - $dj_id = $qs->getId(); - - $td = new Book(); - $td->setISBN("067972575X"); - $td->setTitle("The Tin Drum"); - $td->setAuthor($grass); - $td->setPublisher($vintage); - $td->save(); - $td_id = $td->getId(); - $this->assertTrue(true, 'Save Book records'); - } catch (Exception $e) { - $this->fail('Save Author records'); - } - - // Add review records - // ------------------ - - try { - $r1 = new Review(); - $r1->setBook($phoenix); - $r1->setReviewedBy("Washington Post"); - $r1->setRecommended(true); - $r1->setReviewDate(time()); - $r1->save(); - $r1_id = $r1->getId(); - - $r2 = new Review(); - $r2->setBook($phoenix); - $r2->setReviewedBy("New York Times"); - $r2->setRecommended(false); - $r2->setReviewDate(time()); - $r2->save(); - $r2_id = $r2->getId(); - $this->assertTrue(true, 'Save Review records'); - } catch (Exception $e) { - $this->fail('Save Review records'); - } - - // Perform a "complex" search - // -------------------------- - - $crit = new Criteria(); - $crit->add(BookPeer::TITLE, 'Harry%', Criteria::LIKE); - $results = BookPeer::doSelect($crit); - $this->assertEquals(1, count($results)); - - $crit2 = new Criteria(); - $crit2->add(BookPeer::ISBN, array("0380977427", "0140422161"), Criteria::IN); - $results = BookPeer::doSelect($crit2); - $this->assertEquals(2, count($results)); - - // Perform a "limit" search - // ------------------------ - - $crit = new Criteria(); - $crit->setLimit(2); - $crit->setOffset(1); - $crit->addAscendingOrderByColumn(BookPeer::TITLE); - - $results = BookPeer::doSelect($crit); - $this->assertEquals(2, count($results)); - - // we ordered on book title, so we expect to get - $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle()); - $this->assertEquals("Quicksilver", $results[1]->getTitle()); - - // Perform a lookup & update! - // -------------------------- - - // Updating just-created book title - // First finding book by PK (=$qs_id) .... - $qs_lookup = BookPeer::retrieveByPk($qs_id); - $this->assertNotNull($qs_lookup, 'just-created book can be found by pk'); - - $new_title = "Quicksilver (".crc32(uniqid(rand())).")"; - // Attempting to update found object - $qs_lookup->setTitle($new_title); - $qs_lookup->save(); - - // Making sure object was correctly updated: "; - $qs_lookup2 = BookPeer::retrieveByPk($qs_id); - $this->assertEquals($new_title, $qs_lookup2->getTitle()); - - // Test some basic DATE / TIME stuff - // --------------------------------- - - // that's the control timestamp. - $control = strtotime('2004-02-29 00:00:00'); - - // should be two in the db - $r = ReviewPeer::doSelectOne(new Criteria()); - $r_id = $r->getId(); - $r->setReviewDate($control); - $r->save(); - - $r2 = ReviewPeer::retrieveByPk($r_id); - - $this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime'); - $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp'); - $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter'); - - // Handle BLOB/CLOB Columns - // ------------------------ - - $blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif'; - $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif'; - $clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt'; - - $m1 = new Media(); - $m1->setBook($phoenix); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - $m1_id = $m1->getId(); - - $m1_lookup = MediaPeer::retrieveByPk($m1_id); - - $this->assertNotNull($m1_lookup, 'Can find just-created media item'); - $this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1_lookup->getCoverImage()), 'BLOB was correctly updated'); - $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated'); - - // now update the BLOB column and save it & check the results - $m1_lookup->setCoverImage(file_get_contents($blob2_path)); - $m1_lookup->save(); - - $m2_lookup = MediaPeer::retrieveByPk($m1_id); - $this->assertNotNull($m2_lookup, 'Can find just-created media item'); - - $this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2_lookup->getCoverImage()), 'BLOB was correctly overwritten'); - - // Test Validators - // --------------- - - require_once 'tools/helpers/bookstore/validator/ISBNValidator.php'; - - $bk1 = new Book(); - $bk1->setTitle("12345"); // min length is 10 - $ret = $bk1->validate(); - - $this->assertFalse($ret, 'validation failed'); - $failures = $bk1->getValidationFailures(); - $this->assertEquals(1, count($failures), '1 validation message was returned'); - - $el = array_shift($failures); - $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned'); - - $bk2 = new Book(); - $bk2->setTitle("Don Juan"); - $ret = $bk2->validate(); - - $this->assertFalse($ret, 'validation failed'); - - $failures = $bk2->getValidationFailures(); - $this->assertEquals(1, count($failures), '1 validation message was returned'); - - $el = array_shift($failures); - $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned'); - - //Now trying some more complex validation. - $auth1 = new Author(); - $auth1->setFirstName("Hans"); - // last name required; will fail - - $bk1->setAuthor($auth1); - - $rev1 = new Review(); - $rev1->setReviewDate("08/09/2001"); - // will fail: reviewed_by column required - - $bk1->addReview($rev1); - - $ret2 = $bk1->validate(); - $this->assertFalse($ret2, 'validation failed'); - - $failures2 = $bk1->getValidationFailures(); - - $this->assertEquals(3, count($failures2), '3 validation messages were returned'); - - $expectedKeys = array( - AuthorPeer::LAST_NAME, - BookPeer::TITLE, - ReviewPeer::REVIEWED_BY, - ); - $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed'); - - $bk2 = new Book(); - $bk2->setTitle("12345678901"); // passes - - $auth2 = new Author(); - $auth2->setLastName("Blah"); //passes - $auth2->setEmail("some@body.com"); //passes - $auth2->setAge(50); //passes - $bk2->setAuthor($auth2); - - $rev2 = new Review(); - $rev2->setReviewedBy("Me!"); // passes - $rev2->setStatus("new"); // passes - $bk2->addReview($rev2); - - $ret3 = $bk2->validate(); - - $this->assertTrue($ret3, 'complex validation can pass'); - - // Testing doCount() functionality - // ------------------------------- - - $c = new Criteria(); - $records = BookPeer::doSelect($c); - $count = BookPeer::doCount($c); - - $this->assertEquals($count, count($records), 'correct number of results'); - - // Test many-to-many relationships - // --------------- - - // init book club list 1 with 2 books - - $blc1 = new BookClubList(); - $blc1->setGroupLeader("Crazyleggs"); - $blc1->setTheme("Happiness"); - - $brel1 = new BookListRel(); - $brel1->setBook($phoenix); - - $brel2 = new BookListRel(); - $brel2->setBook($dj); - - $blc1->addBookListRel($brel1); - $blc1->addBookListRel($brel2); - - $blc1->save(); - - $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved'); - - // init book club list 2 with 1 book - - $blc2 = new BookClubList(); - $blc2->setGroupLeader("John Foo"); - $blc2->setTheme("Default"); - - $brel3 = new BookListRel(); - $brel3->setBook($phoenix); - - $blc2->addBookListRel($brel3); - - $blc2->save(); - - $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved'); - - // re-fetch books and lists from db to be sure that nothing is cached - - $crit = new Criteria(); - $crit->add(BookPeer::ID, $phoenix->getId()); - $phoenix = BookPeer::doSelectOne($crit); - $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db"); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc1->getId()); - $blc1 = BookClubListPeer::doSelectOne($crit); - $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db'); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc2->getId()); - $blc2 = BookClubListPeer::doSelectOne($crit); - $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db'); - - $relCount = $phoenix->countBookListRels(); - $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels"); - - $relCount = $blc1->countBookListRels(); - $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels'); - - $relCount = $blc2->countBookListRels(); - $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel'); - - // Cleanup (tests DELETE) - // ---------------------- - - // Removing books that were just created - // First finding book by PK (=$phoenix_id) .... - $hp = BookPeer::retrieveByPk($phoenix_id); - $this->assertNotNull($hp, 'Could find just-created book'); - - // Attempting to delete [multi-table] by found pk - $c = new Criteria(); - $c->add(BookPeer::ID, $hp->getId()); - // The only way for cascading to work currently - // is to specify the author_id and publisher_id (i.e. the fkeys - // have to be in the criteria). - $c->add(AuthorPeer::ID, $hp->getAuthor()->getId()); - $c->add(PublisherPeer::ID, $hp->getPublisher()->getId()); - $c->setSingleRecord(true); - BookPeer::doDelete($c); - - // Checking to make sure correct records were removed. - $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table'); - $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table'); - $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table'); - - // Attempting to delete books by complex criteria - $c = new Criteria(); - $cn = $c->getNewCriterion(BookPeer::ISBN, "043935806X"); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0380977427")); - $cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0140422161")); - $c->add($cn); - BookPeer::doDelete($c); - - // Attempting to delete book [id = $td_id] - $td->delete(); - - // Attempting to delete authors - AuthorPeer::doDelete($stephenson_id); - AuthorPeer::doDelete($byron_id); - $grass->delete(); - - // Attempting to delete publishers - PublisherPeer::doDelete($morrow_id); - PublisherPeer::doDelete($penguin_id); - $vintage->delete(); - - // These have to be deleted manually also since we have onDelete - // set to SETNULL in the foreign keys in book. Is this correct? - $rowling->delete(); - $scholastic->delete(); - $blc1->delete(); - $blc2->delete(); - - $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table'); - $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table'); - $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table'); - $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table'); - $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table'); - $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table'); - $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table'); - - } - - public function testScenarioUsingQuery() - { - // Add publisher records - // --------------------- - - try { - $scholastic = new Publisher(); - $scholastic->setName("Scholastic"); - // do not save, will do later to test cascade - - $morrow = new Publisher(); - $morrow->setName("William Morrow"); - $morrow->save(); - $morrow_id = $morrow->getId(); - - $penguin = new Publisher(); - $penguin->setName("Penguin"); - $penguin->save(); - $penguin_id = $penguin->getId(); - - $vintage = new Publisher(); - $vintage->setName("Vintage"); - $vintage->save(); - $vintage_id = $vintage->getId(); - $this->assertTrue(true, 'Save Publisher records'); - } catch (Exception $e) { - $this->fail('Save publisher records'); - } - - // Add author records - // ------------------ - - try { - $rowling = new Author(); - $rowling->setFirstName("J.K."); - $rowling->setLastName("Rowling"); - // do not save, will do later to test cascade - - $stephenson = new Author(); - $stephenson->setFirstName("Neal"); - $stephenson->setLastName("Stephenson"); - $stephenson->save(); - $stephenson_id = $stephenson->getId(); - - $byron = new Author(); - $byron->setFirstName("George"); - $byron->setLastName("Byron"); - $byron->save(); - $byron_id = $byron->getId(); - - $grass = new Author(); - $grass->setFirstName("Gunter"); - $grass->setLastName("Grass"); - $grass->save(); - $grass_id = $grass->getId(); - $this->assertTrue(true, 'Save Author records'); - } catch (Exception $e) { - $this->fail('Save Author records'); - } - - // Add book records - // ---------------- - - try { - $phoenix = new Book(); - $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); - $phoenix->setISBN("043935806X"); - $phoenix->setAuthor($rowling); - $phoenix->setPublisher($scholastic); - $phoenix->save(); - $phoenix_id = $phoenix->getId(); - $this->assertFalse($rowling->isNew(), 'saving book also saves related author'); - $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher'); - - $qs = new Book(); - $qs->setISBN("0380977427"); - $qs->setTitle("Quicksilver"); - $qs->setAuthor($stephenson); - $qs->setPublisher($morrow); - $qs->save(); - $qs_id = $qs->getId(); - - $dj = new Book(); - $dj->setISBN("0140422161"); - $dj->setTitle("Don Juan"); - $dj->setAuthor($byron); - $dj->setPublisher($penguin); - $dj->save(); - $dj_id = $qs->getId(); - - $td = new Book(); - $td->setISBN("067972575X"); - $td->setTitle("The Tin Drum"); - $td->setAuthor($grass); - $td->setPublisher($vintage); - $td->save(); - $td_id = $td->getId(); - $this->assertTrue(true, 'Save Book records'); - } catch (Exception $e) { - $this->fail('Save Author records'); - } - - // Add review records - // ------------------ - - try { - $r1 = new Review(); - $r1->setBook($phoenix); - $r1->setReviewedBy("Washington Post"); - $r1->setRecommended(true); - $r1->setReviewDate(time()); - $r1->save(); - $r1_id = $r1->getId(); - - $r2 = new Review(); - $r2->setBook($phoenix); - $r2->setReviewedBy("New York Times"); - $r2->setRecommended(false); - $r2->setReviewDate(time()); - $r2->save(); - $r2_id = $r2->getId(); - $this->assertTrue(true, 'Save Review records'); - } catch (Exception $e) { - $this->fail('Save Review records'); - } - - // Perform a "complex" search - // -------------------------- - - $results = BookQuery::create() - ->filterByTitle('Harry%') - ->find(); - $this->assertEquals(1, count($results)); - - $results = BookQuery::create() - ->where('Book.ISBN IN ?', array("0380977427", "0140422161")) - ->find(); - $this->assertEquals(2, count($results)); - - // Perform a "limit" search - // ------------------------ - - $results = BookQuery::create() - ->limit(2) - ->offset(1) - ->orderByTitle() - ->find(); - $this->assertEquals(2, count($results)); - // we ordered on book title, so we expect to get - $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle()); - $this->assertEquals("Quicksilver", $results[1]->getTitle()); - - // Perform a lookup & update! - // -------------------------- - - // Updating just-created book title - // First finding book by PK (=$qs_id) .... - $qs_lookup = BookQuery::create()->findPk($qs_id); - $this->assertNotNull($qs_lookup, 'just-created book can be found by pk'); - - $new_title = "Quicksilver (".crc32(uniqid(rand())).")"; - // Attempting to update found object - $qs_lookup->setTitle($new_title); - $qs_lookup->save(); - - // Making sure object was correctly updated: "; - $qs_lookup2 = BookQuery::create()->findPk($qs_id); - $this->assertEquals($new_title, $qs_lookup2->getTitle()); - - // Test some basic DATE / TIME stuff - // --------------------------------- - - // that's the control timestamp. - $control = strtotime('2004-02-29 00:00:00'); - - // should be two in the db - $r = ReviewQuery::create()->findOne(); - $r_id = $r->getId(); - $r->setReviewDate($control); - $r->save(); - - $r2 = ReviewQuery::create()->findPk($r_id); - $this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime'); - $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp'); - $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter'); - - // Handle BLOB/CLOB Columns - // ------------------------ - - $blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif'; - $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif'; - $clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt'; - - $m1 = new Media(); - $m1->setBook($phoenix); - $m1->setCoverImage(file_get_contents($blob_path)); - $m1->setExcerpt(file_get_contents($clob_path)); - $m1->save(); - $m1_id = $m1->getId(); - - $m1_lookup = MediaQuery::create()->findPk($m1_id); - - $this->assertNotNull($m1_lookup, 'Can find just-created media item'); - $this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1_lookup->getCoverImage()), 'BLOB was correctly updated'); - $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated'); - - // now update the BLOB column and save it & check the results - $m1_lookup->setCoverImage(file_get_contents($blob2_path)); - $m1_lookup->save(); - - $m2_lookup = MediaQuery::create()->findPk($m1_id); - $this->assertNotNull($m2_lookup, 'Can find just-created media item'); - - $this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2_lookup->getCoverImage()), 'BLOB was correctly overwritten'); - - // Test Validators - // --------------- - - require_once 'tools/helpers/bookstore/validator/ISBNValidator.php'; - - $bk1 = new Book(); - $bk1->setTitle("12345"); // min length is 10 - $ret = $bk1->validate(); - - $this->assertFalse($ret, 'validation failed'); - $failures = $bk1->getValidationFailures(); - $this->assertEquals(1, count($failures), '1 validation message was returned'); - - $el = array_shift($failures); - $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned'); - - $bk2 = new Book(); - $bk2->setTitle("Don Juan"); - $ret = $bk2->validate(); - - $this->assertFalse($ret, 'validation failed'); - - $failures = $bk2->getValidationFailures(); - $this->assertEquals(1, count($failures), '1 validation message was returned'); - - $el = array_shift($failures); - $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned'); - - //Now trying some more complex validation. - $auth1 = new Author(); - $auth1->setFirstName("Hans"); - // last name required; will fail - - $bk1->setAuthor($auth1); - - $rev1 = new Review(); - $rev1->setReviewDate("08/09/2001"); - // will fail: reviewed_by column required - - $bk1->addReview($rev1); - - $ret2 = $bk1->validate(); - $this->assertFalse($ret2, 'validation failed'); - - $failures2 = $bk1->getValidationFailures(); - - $this->assertEquals(3, count($failures2), '3 validation messages were returned'); - - $expectedKeys = array( - AuthorPeer::LAST_NAME, - BookPeer::TITLE, - ReviewPeer::REVIEWED_BY, - ); - $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed'); - - $bk2 = new Book(); - $bk2->setTitle("12345678901"); // passes - - $auth2 = new Author(); - $auth2->setLastName("Blah"); //passes - $auth2->setEmail("some@body.com"); //passes - $auth2->setAge(50); //passes - $bk2->setAuthor($auth2); - - $rev2 = new Review(); - $rev2->setReviewedBy("Me!"); // passes - $rev2->setStatus("new"); // passes - $bk2->addReview($rev2); - - $ret3 = $bk2->validate(); - - $this->assertTrue($ret3, 'complex validation can pass'); - - // Testing doCount() functionality - // ------------------------------- - - // old way - $c = new Criteria(); - $records = BookPeer::doSelect($c); - $count = BookPeer::doCount($c); - $this->assertEquals($count, count($records), 'correct number of results'); - - // new way - $count = BookQuery::create()->count(); - $this->assertEquals($count, count($records), 'correct number of results'); - - // Test many-to-many relationships - // --------------- - - // init book club list 1 with 2 books - - $blc1 = new BookClubList(); - $blc1->setGroupLeader("Crazyleggs"); - $blc1->setTheme("Happiness"); - - $brel1 = new BookListRel(); - $brel1->setBook($phoenix); - - $brel2 = new BookListRel(); - $brel2->setBook($dj); - - $blc1->addBookListRel($brel1); - $blc1->addBookListRel($brel2); - - $blc1->save(); - - $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved'); - - // init book club list 2 with 1 book - - $blc2 = new BookClubList(); - $blc2->setGroupLeader("John Foo"); - $blc2->setTheme("Default"); - - $brel3 = new BookListRel(); - $brel3->setBook($phoenix); - - $blc2->addBookListRel($brel3); - - $blc2->save(); - - $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved'); - - // re-fetch books and lists from db to be sure that nothing is cached - - $crit = new Criteria(); - $crit->add(BookPeer::ID, $phoenix->getId()); - $phoenix = BookPeer::doSelectOne($crit); - $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db"); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc1->getId()); - $blc1 = BookClubListPeer::doSelectOne($crit); - $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db'); - - $crit = new Criteria(); - $crit->add(BookClubListPeer::ID, $blc2->getId()); - $blc2 = BookClubListPeer::doSelectOne($crit); - $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db'); - - $relCount = $phoenix->countBookListRels(); - $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels"); - - $relCount = $blc1->countBookListRels(); - $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels'); - - $relCount = $blc2->countBookListRels(); - $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel'); - - // Cleanup (tests DELETE) - // ---------------------- - - // Removing books that were just created - // First finding book by PK (=$phoenix_id) .... - $hp = BookQuery::create()->findPk($phoenix_id); - $this->assertNotNull($hp, 'Could find just-created book'); - - // Attempting to delete [multi-table] by found pk - $c = new Criteria(); - $c->add(BookPeer::ID, $hp->getId()); - // The only way for cascading to work currently - // is to specify the author_id and publisher_id (i.e. the fkeys - // have to be in the criteria). - $c->add(AuthorPeer::ID, $hp->getAuthor()->getId()); - $c->add(PublisherPeer::ID, $hp->getPublisher()->getId()); - $c->setSingleRecord(true); - BookPeer::doDelete($c); - - // Checking to make sure correct records were removed. - $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table'); - $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table'); - $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table'); - - // Attempting to delete books by complex criteria - BookQuery::create() - ->filterByISBN("043935806X") - ->orWhere('Book.ISBN = ?', "0380977427") - ->orWhere('Book.ISBN = ?', "0140422161") - ->delete(); - - // Attempting to delete book [id = $td_id] - $td->delete(); - - // Attempting to delete authors - AuthorQuery::create()->filterById($stephenson_id)->delete(); - AuthorQuery::create()->filterById($byron_id)->delete(); - $grass->delete(); - - // Attempting to delete publishers - PublisherQuery::create()->filterById($morrow_id)->delete(); - PublisherQuery::create()->filterById($penguin_id)->delete(); - $vintage->delete(); - - // These have to be deleted manually also since we have onDelete - // set to SETNULL in the foreign keys in book. Is this correct? - $rowling->delete(); - $scholastic->delete(); - $blc1->delete(); - $blc2->delete(); - - $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table'); - $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table'); - $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table'); - $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table'); - $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table'); - $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table'); - $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/misc/CharacterEncodingTest.php b/airtime_mvc/library/propel/test/testsuite/misc/CharacterEncodingTest.php deleted file mode 100644 index dfc9c03e7..000000000 --- a/airtime_mvc/library/propel/test/testsuite/misc/CharacterEncodingTest.php +++ /dev/null @@ -1,112 +0,0 @@ - - * @package misc - */ -class CharacterEncodingTest extends BookstoreTestBase -{ - /** - * Database adapter. - * @var DBAdapter - */ - private $adapter; - - public function setUp() - { - parent::setUp(); - if (!extension_loaded('iconv')) { - throw new Exception("Character-encoding tests require iconv extension to be loaded."); - } - } - - public function testUtf8() - { - $this->markTestSkipped(); - - $db = Propel::getDB(BookPeer::DATABASE_NAME); - - $title = "Смерть на брудершафт. Младенец и черт"; - // 1234567890123456789012345678901234567 - // 1 2 3 - - $a = new Author(); - $a->setFirstName("Б."); - $a->setLastName("ÐКУÐИÐ"); - - $p = new Publisher(); - $p->setName("Детектив роÑÑийÑкий, оÑтроÑÑŽÐ¶ÐµÑ‚Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð·Ð°"); - - $b = new Book(); - $b->setTitle($title); - $b->setISBN("B-59246"); - $b->setAuthor($a); - $b->setPublisher($p); - $b->save(); - - $b->reload(); - - $this->assertEquals(37, iconv_strlen($b->getTitle(), 'utf-8'), "Expected 37 characters (not bytes) in title."); - $this->assertTrue(strlen($b->getTitle()) > iconv_strlen($b->getTitle(), 'utf-8'), "Expected more bytes than characters in title."); - - } - - public function testInvalidCharset() - { - $this->markTestSkipped(); - - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if ($db instanceof DBSQLite) { - $this->markTestSkipped(); - } - - $a = new Author(); - $a->setFirstName("Б."); - $a->setLastName("ÐКУÐИÐ"); - $a->save(); - - $authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName()); - $a->setLastName($authorNameWindows1251); - - // Different databases seem to handle invalid data differently (no surprise, I guess...) - if ($db instanceof DBPostgres) { - try { - $a->save(); - $this->fail("Expected an exception when saving non-UTF8 data to database."); - } catch (Exception $x) { - print $x; - } - - } else { - - // No exception is thrown by MySQL ... (others need to be tested still) - $a->save(); - $a->reload(); - - $this->assertEquals("",$a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)"); - } - - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/misc/FieldnameRelatedTest.php b/airtime_mvc/library/propel/test/testsuite/misc/FieldnameRelatedTest.php deleted file mode 100644 index fe43a94bb..000000000 --- a/airtime_mvc/library/propel/test/testsuite/misc/FieldnameRelatedTest.php +++ /dev/null @@ -1,396 +0,0 @@ - - * @package misc - */ -class FieldnameRelatedTest extends PHPUnit_Framework_TestCase -{ - protected function setUp() - { - parent::setUp(); - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - require_once 'bookstore/map/BookTableMap.php'; - require_once 'bookstore/BookPeer.php'; - require_once 'bookstore/Book.php'; - } - - /** - * Tests if fieldname type constants are defined - */ - public function testFieldNameTypeConstants () { - - $result = defined('BasePeer::TYPE_PHPNAME'); - $this->assertTrue($result); - } - - /** - * Tests the Base[Object]Peer::getFieldNames() method - */ - public function testGetFieldNames () - { - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - $expecteds = array ( - BasePeer::TYPE_PHPNAME => array( - 0 => 'Id', - 1 => 'Title', - 2 => 'ISBN', - 3 => 'Price', - 4 => 'PublisherId', - 5 => 'AuthorId' - ), - BasePeer::TYPE_STUDLYPHPNAME => array( - 0 => 'id', - 1 => 'title', - 2 => 'iSBN', - 3 => 'price', - 4 => 'publisherId', - 5 => 'authorId' - ), - BasePeer::TYPE_COLNAME => array( - 0 => 'book.ID', - 1 => 'book.TITLE', - 2 => 'book.ISBN', - 3 => 'book.PRICE', - 4 => 'book.PUBLISHER_ID', - 5 => 'book.AUTHOR_ID' - ), - BasePeer::TYPE_FIELDNAME => array( - 0 => 'id', - 1 => 'title', - 2 => 'isbn', - 3 => 'price', - 4 => 'publisher_id', - 5 => 'author_id' - ), - BasePeer::TYPE_NUM => array( - 0 => 0, - 1 => 1, - 2 => 2, - 3 => 3, - 4 => 4, - 5 => 5 - ) - ); - - foreach ($types as $type) { - $results[$type] = BookPeer::getFieldnames($type); - $this->assertEquals( - $expecteds[$type], - $results[$type], - 'expected was: ' . print_r($expecteds[$type], 1) . - 'but getFieldnames() returned ' . print_r($results[$type], 1) - ); - } - } - - /** - * Tests the Base[Object]Peer::translateFieldName() method - */ - public function testTranslateFieldName () { - - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_STUDLYPHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - $expecteds = array ( - BasePeer::TYPE_PHPNAME => 'AuthorId', - BasePeer::TYPE_STUDLYPHPNAME => 'authorId', - BasePeer::TYPE_COLNAME => 'book.AUTHOR_ID', - BasePeer::TYPE_FIELDNAME => 'author_id', - BasePeer::TYPE_NUM => 5, - ); - foreach ($types as $fromType) { - foreach ($types as $toType) { - $name = $expecteds[$fromType]; - $expected = $expecteds[$toType]; - $result = BookPeer::translateFieldName($name, $fromType, $toType); - $this->assertEquals($expected, $result); - } - } - } - - /** - * Tests the BasePeer::getFieldNames() method - */ - public function testGetFieldNamesStatic () { - - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_STUDLYPHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - $expecteds = array ( - BasePeer::TYPE_PHPNAME => array( - 0 => 'Id', - 1 => 'Title', - 2 => 'ISBN', - 3 => 'Price', - 4 => 'PublisherId', - 5 => 'AuthorId' - ), - BasePeer::TYPE_STUDLYPHPNAME => array( - 0 => 'id', - 1 => 'title', - 2 => 'iSBN', - 3 => 'price', - 4 => 'publisherId', - 5 => 'authorId' - ), - BasePeer::TYPE_COLNAME => array( - 0 => 'book.ID', - 1 => 'book.TITLE', - 2 => 'book.ISBN', - 3 => 'book.PRICE', - 4 => 'book.PUBLISHER_ID', - 5 => 'book.AUTHOR_ID' - ), - BasePeer::TYPE_FIELDNAME => array( - 0 => 'id', - 1 => 'title', - 2 => 'isbn', - 3 => 'price', - 4 => 'publisher_id', - 5 => 'author_id' - ), - BasePeer::TYPE_NUM => array( - 0 => 0, - 1 => 1, - 2 => 2, - 3 => 3, - 4 => 4, - 5 => 5 - ) - ); - - foreach ($types as $type) { - $results[$type] = BasePeer::getFieldnames('Book', $type); - $this->assertEquals( - $expecteds[$type], - $results[$type], - 'expected was: ' . print_r($expecteds[$type], 1) . - 'but getFieldnames() returned ' . print_r($results[$type], 1) - ); - } - } - - /** - * Tests the BasePeer::translateFieldName() method - */ - public function testTranslateFieldNameStatic () { - - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_STUDLYPHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - $expecteds = array ( - BasePeer::TYPE_PHPNAME => 'AuthorId', - BasePeer::TYPE_STUDLYPHPNAME => 'authorId', - BasePeer::TYPE_COLNAME => 'book.AUTHOR_ID', - BasePeer::TYPE_FIELDNAME => 'author_id', - BasePeer::TYPE_NUM => 5, - ); - foreach ($types as $fromType) { - foreach ($types as $toType) { - $name = $expecteds[$fromType]; - $expected = $expecteds[$toType]; - $result = BasePeer::translateFieldName('Book', $name, $fromType, $toType); - $this->assertEquals($expected, $result); - } - } - } - - /** - * Tests the Base[Object]::getByName() method - */ - public function testGetByName() { - - $types = array( - BasePeer::TYPE_PHPNAME => 'Title', - BasePeer::TYPE_STUDLYPHPNAME => 'title', - BasePeer::TYPE_COLNAME => 'book.TITLE', - BasePeer::TYPE_FIELDNAME => 'title', - BasePeer::TYPE_NUM => 1 - ); - - $book = new Book(); - $book->setTitle('Harry Potter and the Order of the Phoenix'); - - $expected = 'Harry Potter and the Order of the Phoenix'; - foreach ($types as $type => $name) { - $result = $book->getByName($name, $type); - $this->assertEquals($expected, $result); - } - } - - /** - * Tests the Base[Object]::setByName() method - */ - public function testSetByName() { - - $book = new Book(); - $types = array( - BasePeer::TYPE_PHPNAME => 'Title', - BasePeer::TYPE_STUDLYPHPNAME => 'title', - BasePeer::TYPE_COLNAME => 'book.TITLE', - BasePeer::TYPE_FIELDNAME => 'title', - BasePeer::TYPE_NUM => 1 - ); - - $title = 'Harry Potter and the Order of the Phoenix'; - foreach ($types as $type => $name) { - $book->setByName($name, $title, $type); - $result = $book->getTitle(); - $this->assertEquals($title, $result); - } - } - - /** - * Tests the Base[Object]::fromArray() method - * - * this also tests populateFromArray() because that's an alias - */ - public function testFromArray(){ - - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_STUDLYPHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - $expecteds = array ( - BasePeer::TYPE_PHPNAME => array ( - 'Title' => 'Harry Potter and the Order of the Phoenix', - 'ISBN' => '043935806X' - ), - BasePeer::TYPE_STUDLYPHPNAME => array ( - 'title' => 'Harry Potter and the Order of the Phoenix', - 'iSBN' => '043935806X' - ), - BasePeer::TYPE_COLNAME => array ( - 'book.TITLE' => 'Harry Potter and the Order of the Phoenix', - 'book.ISBN' => '043935806X' - ), - BasePeer::TYPE_FIELDNAME => array ( - 'title' => 'Harry Potter and the Order of the Phoenix', - 'isbn' => '043935806X' - ), - BasePeer::TYPE_NUM => array ( - '1' => 'Harry Potter and the Order of the Phoenix', - '2' => '043935806X' - ) - ); - - $book = new Book(); - - foreach ($types as $type) { - $expected = $expecteds[$type]; - $book->fromArray($expected, $type); - $result = array(); - foreach (array_keys($expected) as $key) { - $result[$key] = $book->getByName($key, $type); - } - $this->assertEquals( - $expected, - $result, - 'expected was: ' . print_r($expected, 1) . - 'but fromArray() returned ' . print_r($result, 1) - ); - } - } - - /** - * Tests the Base[Object]::toArray() method - */ - public function testToArray(){ - - $types = array( - BasePeer::TYPE_PHPNAME, - BasePeer::TYPE_STUDLYPHPNAME, - BasePeer::TYPE_COLNAME, - BasePeer::TYPE_FIELDNAME, - BasePeer::TYPE_NUM - ); - - $book = new Book(); - $book->fromArray(array ( - 'Title' => 'Harry Potter and the Order of the Phoenix', - 'ISBN' => '043935806X' - )); - - $expecteds = array ( - BasePeer::TYPE_PHPNAME => array ( - 'Title' => 'Harry Potter and the Order of the Phoenix', - 'ISBN' => '043935806X' - ), - BasePeer::TYPE_STUDLYPHPNAME => array ( - 'title' => 'Harry Potter and the Order of the Phoenix', - 'iSBN' => '043935806X' - ), - BasePeer::TYPE_COLNAME => array ( - 'book.TITLE' => 'Harry Potter and the Order of the Phoenix', - 'book.ISBN' => '043935806X' - ), - BasePeer::TYPE_FIELDNAME => array ( - 'title' => 'Harry Potter and the Order of the Phoenix', - 'isbn' => '043935806X' - ), - BasePeer::TYPE_NUM => array ( - '1' => 'Harry Potter and the Order of the Phoenix', - '2' => '043935806X' - ) - ); - - foreach ($types as $type) { - $expected = $expecteds[$type]; - $result = $book->toArray($type); - // remove ID since its autoincremented at each test iteration - $result = array_slice($result, 1, 2, true); - $this->assertEquals( - $expected, - $result, - 'expected was: ' . print_r($expected, 1) . - 'but toArray() returned ' . print_r($result, 1) - ); - } - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/misc/Ticket520Test.php b/airtime_mvc/library/propel/test/testsuite/misc/Ticket520Test.php deleted file mode 100644 index e95390b05..000000000 --- a/airtime_mvc/library/propel/test/testsuite/misc/Ticket520Test.php +++ /dev/null @@ -1,250 +0,0 @@ -setFirstName("Douglas"); - $a->setLastName("Adams"); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $a->addBook($b2); - - // Passing no Criteria means "use the internal collection or query the database" - // in that case two objects are added, so it should return 2 - $books = $a->getBooks(); - $this->assertEquals(2, count($books)); - } - - public function testNewObjectsNotAvailableWithCriteria() - { - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $a->addBook($b2); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE); - - $guides = $a->getBooks($c); - $this->assertEquals(0, count($guides), 'Passing a Criteria means "force a database query"'); - } - - public function testNewObjectsAvailableAfterCriteria() - { - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $a->addBook($b2); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE); - - $guides = $a->getBooks($c); - - $books = $a->getBooks(); - $this->assertEquals(2, count($books), 'A previous query with a Criteria does not erase the internal collection'); - } - - public function testSavedObjectsWithCriteria() - { - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $a->addBook($b2); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE); - - $guides = $a->getBooks($c); - - $a->save(); - $booksAfterSave = $a->getBooks($c); - $this->assertEquals(1, count($booksAfterSave), 'A previous query with a Criteria is not cached'); - } - - public function testAddNewObjectAfterSave() - { - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $a->save(); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $books = $a->getBooks(); - $this->assertEquals(1, count($books)); - $this->assertTrue($books->contains($b1)); - - /* Now this is the initial ticket 520: If we have a saved author, - add a new book but happen to call getBooks() before we call save() again, - the book used to be lost. */ - $a->save(); - $this->assertFalse($b1->isNew(), 'related objects are also saved after fetching them'); - } - - public function testAddNewObjectAfterSaveWithPoisonedCache() - { - /* This is like testAddNewObjectAfterSave(), - but this time we "poison" the author's $colBooks cache - before adding the book by calling getBooks(). */ - - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $a->save(); - $a->getBooks(); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $books = $a->getBooks(); - $this->assertEquals(1, count($books)); - $this->assertTrue($books->contains($b1), 'new related objects not deleted after fetching them'); - } - - public function testCachePoisoning() - { - /* Like testAddNewObjectAfterSaveWithPoisonedCache, emphasizing - cache poisoning. */ - - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $a->save(); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, "%Restaurant%", Criteria::LIKE); - - $this->assertEquals(0, count($a->getBooks($c))); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - /* Like testAddNewObjectAfterSaveWithPoisonedCache, but this time - with a real criteria. */ - $this->assertEquals(0, count($a->getBooks($c))); - - $a->save(); - $this->assertFalse($b1->isNew()); - $this->assertEquals(0, count($a->getBooks($c))); - } - - public function testDeletedBookDisappears() - { - $this->markTestSkipped(); - - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $a->addBook($b2); - - /* As you cannot write $a->remove($b2), you have to delete $b2 - directly. */ - - /* All objects unsaved. As of revision 851, this circumvents the - $colBooks cache. Anyway, fails because getBooks() never checks if - a colBooks entry has been deleted. */ - $this->assertEquals(2, count($a->getBooks())); - $b2->delete(); - $this->assertEquals(1, count($a->getBooks())); - - /* Even if we had saved everything before and the delete() had - actually updated the DB, the $b2 would still be a "zombie" in - $a's $colBooks field. */ - } - - public function testNewObjectsGetLostOnJoin() { - /* While testNewObjectsAvailableWhenSaveNotCalled passed as of - revision 851, in this case we call getBooksJoinPublisher() instead - of just getBooks(). get...Join...() does not contain the check whether - the current object is new, it will always consult the DB and lose the - new objects entirely. Thus the test fails. (At least for Propel 1.2 ?!?) */ - $this->markTestSkipped(); - - $a = new Author(); - $a->setFirstName("Douglas"); - $a->setLastName("Adams"); - - $p = new Publisher(); - $p->setName('Pan Books Ltd.'); - - $b1 = new Book(); - $b1->setTitle("The Hitchhikers Guide To The Galaxy"); - $b1->setPublisher($p); // uh... did not check that :^) - $a->addBook($b1); - - $b2 = new Book(); - $b2->setTitle("The Restaurant At The End Of The Universe"); - $b2->setPublisher($p); - $a->addBook($b2); - - $books = $a->getBooksJoinPublisher(); - $this->assertEquals(2, count($books)); - $this->assertContains($b1, $books); - $this->assertContains($b2, $books); - - $a->save(); - $this->assertFalse($b1->isNew()); - $this->assertFalse($b2->isNew()); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/adapter/DBOracleTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/adapter/DBOracleTest.php deleted file mode 100644 index 25f1f1d17..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/adapter/DBOracleTest.php +++ /dev/null @@ -1,47 +0,0 @@ -setDbName('oracle'); - BookPeer::addSelectColumns($c); - $c->setLimit(1); - $params = array(); - $sql = BasePeer::createSelectSql($c, $params); - $this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM book) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with the original column names by default'); - } - - public function testApplyLimitDuplicateColumnName() - { - Propel::setDb('oracle', new DBOracle()); - $c = new Criteria(); - $c->setDbName('oracle'); - BookPeer::addSelectColumns($c); - AuthorPeer::addSelectColumns($c); - $c->setLimit(1); - $params = array(); - $sql = BasePeer::createSelectSql($c, $params); - $this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS book_ID, book.TITLE AS book_TITLE, book.ISBN AS book_ISBN, book.PRICE AS book_PRICE, book.PUBLISHER_ID AS book_PUBLISHER_ID, book.AUTHOR_ID AS book_AUTHOR_ID, author.ID AS author_ID, author.FIRST_NAME AS author_FIRST_NAME, author.LAST_NAME AS author_LAST_NAME, author.EMAIL AS author_EMAIL, author.AGE AS author_AGESELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, author.ID, author.FIRST_NAME, author.LAST_NAME, author.EMAIL, author.AGE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found'); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelArrayCollectionTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelArrayCollectionTest.php deleted file mode 100644 index a6a374936..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelArrayCollectionTest.php +++ /dev/null @@ -1,152 +0,0 @@ -con); - } - - public function testSave() - { - $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find(); - foreach ($books as &$book) { - $book['Title'] = 'foo'; - } - $books->save(); - // check that the modifications are persisted - BookPeer::clearInstancePool(); - $books = PropelQuery::from('Book')->find(); - foreach ($books as $book) { - $this->assertEquals('foo', $book->getTitle('foo')); - } - } - - public function testDelete() - { - $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find(); - $books->delete(); - // check that the modifications are persisted - BookPeer::clearInstancePool(); - $books = PropelQuery::from('Book')->find(); - $this->assertEquals(0, count($books)); - } - - public function testGetPrimaryKeys() - { - $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find(); - $pks = $books->getPrimaryKeys(); - $this->assertEquals(4, count($pks)); - - $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3'); - $this->assertEquals($keys, array_keys($pks)); - - $pks = $books->getPrimaryKeys(false); - $keys = array(0, 1, 2, 3); - $this->assertEquals($keys, array_keys($pks)); - - $bookObjects = PropelQuery::from('Book')->find(); - foreach ($pks as $key => $value) { - $this->assertEquals($bookObjects[$key]->getPrimaryKey(), $value); - } - } - - public function testFromArray() - { - $author = new Author(); - $author->setFirstName('Jane'); - $author->setLastName('Austen'); - $author->save(); - $books = array( - array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()), - array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId()) - ); - $col = new PropelArrayCollection(); - $col->setModel('Book'); - $col->fromArray($books); - $col->save(); - - $nbBooks = PropelQuery::from('Book')->count(); - $this->assertEquals(6, $nbBooks); - - $booksByJane = PropelQuery::from('Book b') - ->join('b.Author a') - ->where('a.LastName = ?', 'Austen') - ->count(); - $this->assertEquals(2, $booksByJane); - } - - public function testToArray() - { - $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find(); - $booksArray = $books->toArray(); - $this->assertEquals(4, count($booksArray)); - - $bookObjects = PropelQuery::from('Book')->find(); - foreach ($booksArray as $key => $book) { - $this->assertEquals($bookObjects[$key]->toArray(), $book); - } - - $booksArray = $books->toArray(); - $keys = array(0, 1, 2, 3); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray(null, true); - $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray('Title'); - $keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray('Title', true); - $keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - } - - public function getWorkerObject() - { - $col = new TestablePropelArrayCollection(); - $col->setModel('Book'); - $book = $col->getWorkerObject(); - $this->assertTrue($book instanceof Book, 'getWorkerObject() returns an object of the collection model'); - $book->foo = 'bar'; - $this->assertEqual('bar', $col->getWorkerObject()->foo, 'getWorkerObject() returns always the same object'); - } - - /** - * @expectedException PropelException - */ - public function testGetWorkerObjectNoModel() - { - $col = new TestablePropelArrayCollection(); - $col->getWorkerObject(); - } - -} - -class TestablePropelArrayCollection extends PropelArrayCollection -{ - public function getWorkerObject() - { - return parent::getWorkerObject(); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelCollectionTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelCollectionTest.php deleted file mode 100644 index fa76def29..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelCollectionTest.php +++ /dev/null @@ -1,353 +0,0 @@ -assertEquals('bar1', $col[0], 'PropelCollection allows access via $foo[$index]'); - $this->assertEquals('bar2', $col[1], 'PropelCollection allows access via $foo[$index]'); - $this->assertEquals('bar3', $col[2], 'PropelCollection allows access via $foo[$index]'); - } - - public function testGetData() - { - $col = new PropelCollection(); - $this->assertEquals(array(), $col->getData(), 'getData() returns an empty array for empty collections'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals($data, $col->getData(), 'getData() returns the collection data'); - $col[0] = 'bar4'; - $this->assertEquals('bar1', $data[0], 'getData() returns a copy of the collection data'); - } - - public function testSetData() - { - $col = new PropelCollection(); - $col->setData(array()); - $this->assertEquals(array(), $col->getArrayCopy(), 'setData() can set data to an empty array'); - - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection(); - $col->setData($data); - $this->assertEquals($data, $col->getArrayCopy(), 'setData() sets the collection data'); - } - - public function testGetPosition() - { - $col = new PropelCollection(); - $this->assertEquals(0, $col->getPosition(), 'getPosition() returns 0 on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $expectedPositions = array(0, 1, 2); - foreach ($col as $element) { - $this->assertEquals(array_shift($expectedPositions), $col->getPosition(), 'getPosition() returns the current position'); - $this->assertEquals($element, $col->getCurrent(), 'getPosition() does not change the current position'); - } - } - - public function testGetFirst() - { - $col = new PropelCollection(); - $this->assertNull($col->getFirst(), 'getFirst() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar1', $col->getFirst(), 'getFirst() returns value of the first element in the collection'); - } - - public function testIsFirst() - { - $col = new PropelCollection(); - $this->assertTrue($col->isFirst(), 'isFirst() returns true on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $expectedRes = array(true, false, false); - foreach ($col as $element) { - $this->assertEquals(array_shift($expectedRes), $col->isFirst(), 'isFirst() returns true only for the first element'); - $this->assertEquals($element, $col->getCurrent(), 'isFirst() does not change the current position'); - } - } - - public function testGetPrevious() - { - $col = new PropelCollection(); - $this->assertNull($col->getPrevious(), 'getPrevious() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertNull($col->getPrevious(), 'getPrevious() returns null when the internal pointer is at the beginning of the list'); - $col->getNext(); - $this->assertEquals('bar1', $col->getPrevious(), 'getPrevious() returns the previous element'); - $this->assertEquals('bar1', $col->getCurrent(), 'getPrevious() decrements the internal pointer'); - } - - public function testGetCurrent() - { - $col = new PropelCollection(); - $this->assertNull($col->getCurrent(), 'getCurrent() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar1', $col->getCurrent(), 'getCurrent() returns the value of the first element when the internal pointer is at the beginning of the list'); - foreach ($col as $key => $value) { - $this->assertEquals($value, $col->getCurrent(), 'getCurrent() returns the value of the current element in the collection'); - } - } - - public function testGetNext() - { - $col = new PropelCollection(); - $this->assertNull($col->getNext(), 'getNext() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar2', $col->getNext(), 'getNext() returns the second element when the internal pointer is at the beginning of the list'); - $this->assertEquals('bar2', $col->getCurrent(), 'getNext() increments the internal pointer'); - $col->getNext(); - $this->assertNull($col->getNext(), 'getNext() returns null when the internal pointer is at the end of the list'); - } - - public function testGetLast() - { - $col = new PropelCollection(); - $this->assertNull($col->getLast(), 'getLast() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar3', $col->getLast(), 'getLast() returns the last element'); - $this->assertEquals('bar3', $col->getCurrent(), 'getLast() moves the internal pointer to the last element'); - } - - public function testIsLAst() - { - $col = new PropelCollection(); - $this->assertTrue($col->isLast(), 'isLast() returns true on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $expectedRes = array(false, false, true); - foreach ($col as $element) { - $this->assertEquals(array_shift($expectedRes), $col->isLast(), 'isLast() returns true only for the last element'); - $this->assertEquals($element, $col->getCurrent(), 'isLast() does not change the current position'); - } - } - - public function testIsEmpty() - { - $col = new PropelCollection(); - $this->assertTrue($col->isEmpty(), 'isEmpty() returns true on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertFalse($col->isEmpty(), 'isEmpty() returns false on a non empty collection'); - } - - public function testIsOdd() - { - $col = new PropelCollection(); - $this->assertFalse($col->isOdd(), 'isOdd() returns false on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection(); - $col->setData($data); - foreach ($col as $key => $value) { - $this->assertEquals((boolean) ($key % 2), $col->isOdd(), 'isOdd() returns true only when the key is odd'); - } - } - - public function testIsEven() - { - $col = new PropelCollection(); - $this->assertTrue($col->isEven(), 'isEven() returns true on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection(); - $col->setData($data); - foreach ($col as $key => $value) { - $this->assertEquals(!(boolean) ($key % 2), $col->isEven(), 'isEven() returns true only when the key is even'); - } - } - - public function testGet() - { - $col = new PropelCollection(array('foo', 'bar')); - $this->assertEquals('foo', $col->get(0), 'get() returns an element from its key'); - } - - /** - * @expectedException PropelException - */ - public function testGetUnknownOffset() - { - $col = new PropelCollection(); - $bar = $col->get('foo'); - } - - public function testPop() - { - $col = new PropelCollection(); - $this->assertNull($col->pop(), 'pop() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar3', $col->pop(), 'pop() returns the last element of the collection'); - $this->assertEquals(array('bar1', 'bar2'), $col->getData(), 'pop() removes the last element of the collection'); - } - - public function testShift() - { - $col = new PropelCollection(); - $this->assertNull($col->shift(), 'shift() returns null on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals('bar1', $col->shift(), 'shift() returns the first element of the collection'); - $this->assertEquals(array('bar2', 'bar3'), $col->getData(), 'shift() removes the first element of the collection'); - } - - public function testPrepend() - { - $col = new PropelCollection(); - $this->assertEquals(1, $col->prepend('a'), 'prepend() returns 1 on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals(4, $col->prepend('bar4'), 'prepend() returns the new number of elements in the collection when adding a variable'); - $this->assertEquals(array('bar4', 'bar1', 'bar2', 'bar3'), $col->getData(), 'prepend() adds new element to the beginning of the collection'); - } - - public function testSet() - { - $col = new PropelCollection(); - $col->set(4, 'bar'); - $this->assertEquals(array(4 => 'bar'), $col->getData(), 'set() adds an element to the collection with a key'); - - $col = new PropelCollection(); - $col->set(null, 'foo'); - $col->set(null, 'bar'); - $this->assertEquals(array('foo', 'bar'), $col->getData(), 'set() adds an element to the collection without a key'); - } - - public function testRemove() - { - $col = new PropelCollection(); - $col[0] = 'bar'; - $col[1] = 'baz'; - $col->remove(1); - $this->assertEquals(array('bar'), $col->getData(), 'remove() removes an element from its key'); - } - - /** - * @expectedException PropelException - */ - public function testRemoveUnknownOffset() - { - $col = new PropelCollection(); - $col->remove(2); - } - - public function testClear() - { - $col = new PropelCollection(); - $col->clear(); - $this->assertEquals(array(), $col->getData(), 'clear() empties the collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $col->clear(); - $this->assertEquals(array(), $col->getData(), 'clear() empties the collection'); - } - - public function testContains() - { - $col = new PropelCollection(); - $this->assertFalse($col->contains('foo_1'), 'contains() returns false on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertTrue($col->contains('bar1'), 'contains() returns true when the key exists'); - $this->assertFalse($col->contains('bar4'), 'contains() returns false when the key does not exist'); - } - - public function testSearch() - { - $col = new PropelCollection(); - $this->assertFalse($col->search('bar1'), 'search() returns false on an empty collection'); - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $this->assertEquals(1, $col->search('bar2'), 'search() returns the key when the element exists'); - $this->assertFalse($col->search('bar4'), 'search() returns false when the element does not exist'); - } - - public function testSerializable() - { - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $col->setModel('Foo'); - $serializedCol = serialize($col); - - $col2 = unserialize($serializedCol); - $this->assertEquals($col, $col2, 'PropelCollection is serializable'); - } - - public function testGetIterator() - { - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $it1 = $col->getIterator(); - $it2 = $col->getIterator(); - $this->assertNotSame($it1, $it2, 'getIterator() returns always a new iterator'); - } - - public function testGetInternalIterator() - { - $data = array('bar1', 'bar2', 'bar3'); - $col = new PropelCollection($data); - $it1 = $col->getInternalIterator(); - $it2 = $col->getINternalIterator(); - $this->assertSame($it1, $it2, 'getInternalIterator() returns always the same iterator'); - $col->getInternalIterator()->next(); - $this->assertEquals('bar2', $col->getInternalIterator()->current(), 'getInternalIterator() returns always the same iterator'); - } - - public function testGetPeerClass() - { - $col = new PropelCollection(); - $col->setModel('Book'); - $this->assertEquals('BookPeer', $col->getPeerClass(), 'getPeerClass() returns the Peer class for the collection model'); - } - - /** - * @expectedException PropelException - */ - public function testGetPeerClassNoModel() - { - $col = new PropelCollection(); - $col->getPeerClass(); - } - - public function testGetConnection() - { - $col = new PropelCollection(); - $col->setModel('Book'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $this->assertEquals($con, $col->getConnection(), 'getConnection() returns a connection for the collection model'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); - $this->assertEquals($con, $col->getConnection(Propel::CONNECTION_WRITE), 'getConnection() accepts a connection type parameter'); - } - - /** - * @expectedException PropelException - */ - public function testGetConnectionNoModel() - { - $col = new PropelCollection(); - $col->getConnection(); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelObjectCollectionTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelObjectCollectionTest.php deleted file mode 100644 index 55c14f2a9..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelObjectCollectionTest.php +++ /dev/null @@ -1,236 +0,0 @@ -con); - } - - public function testSave() - { - $books = PropelQuery::from('Book')->find(); - foreach ($books as $book) { - $book->setTitle('foo'); - } - $books->save(); - // check that all the books are saved - foreach ($books as $book) { - $this->assertFalse($book->isModified()); - } - // check that the modifications are persisted - BookPeer::clearInstancePool(); - $books = PropelQuery::from('Book')->find(); - foreach ($books as $book) { - $this->assertEquals('foo', $book->getTitle('foo')); - } - } - - public function testDelete() - { - $books = PropelQuery::from('Book')->find(); - $books->delete(); - // check that all the books are deleted - foreach ($books as $book) { - $this->assertTrue($book->isDeleted()); - } - // check that the modifications are persisted - BookPeer::clearInstancePool(); - $books = PropelQuery::from('Book')->find(); - $this->assertEquals(0, count($books)); - } - - public function testGetPrimaryKeys() - { - $books = PropelQuery::from('Book')->find(); - $pks = $books->getPrimaryKeys(); - $this->assertEquals(4, count($pks)); - - $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3'); - $this->assertEquals($keys, array_keys($pks)); - - $pks = $books->getPrimaryKeys(false); - $keys = array(0, 1, 2, 3); - $this->assertEquals($keys, array_keys($pks)); - - foreach ($pks as $key => $value) { - $this->assertEquals($books[$key]->getPrimaryKey(), $value); - } - } - - public function testFromArray() - { - $author = new Author(); - $author->setFirstName('Jane'); - $author->setLastName('Austen'); - $author->save(); - $books = array( - array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()), - array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId()) - ); - $col = new PropelObjectCollection(); - $col->setModel('Book'); - $col->fromArray($books); - $col->save(); - - $nbBooks = PropelQuery::from('Book')->count(); - $this->assertEquals(6, $nbBooks); - - $booksByJane = PropelQuery::from('Book b') - ->join('b.Author a') - ->where('a.LastName = ?', 'Austen') - ->count(); - $this->assertEquals(2, $booksByJane); - } - - public function testToArray() - { - $books = PropelQuery::from('Book')->find(); - $booksArray = $books->toArray(); - $this->assertEquals(4, count($booksArray)); - - foreach ($booksArray as $key => $book) { - $this->assertEquals($books[$key]->toArray(), $book); - } - - $booksArray = $books->toArray(); - $keys = array(0, 1, 2, 3); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray(null, true); - $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray('Title'); - $keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->toArray('Title', true); - $keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - } - - public function testGetArrayCopy() - { - $books = PropelQuery::from('Book')->find(); - $booksArray = $books->getArrayCopy(); - $this->assertEquals(4, count($booksArray)); - - foreach ($booksArray as $key => $book) { - $this->assertEquals($books[$key], $book); - } - - $booksArray = $books->getArrayCopy(); - $keys = array(0, 1, 2, 3); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->getArrayCopy(null, true); - $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->getArrayCopy('Title'); - $keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - - $booksArray = $books->getArrayCopy('Title', true); - $keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum'); - $this->assertEquals($keys, array_keys($booksArray)); - } - - public function testToKeyValue() - { - $books = PropelQuery::from('Book')->find(); - - $expected = array(); - foreach ($books as $book) { - $expected[$book->getTitle()] = $book->getISBN(); - } - $booksArray = $books->toKeyValue('Title', 'ISBN'); - $this->assertEquals(4, count($booksArray)); - $this->assertEquals($expected, $booksArray, 'toKeyValue() turns the collection to an associative array'); - - $expected = array(); - foreach ($books as $book) { - $expected[$book->getISBN()] = $book->getTitle(); - } - $booksArray = $books->toKeyValue('ISBN'); - $this->assertEquals($expected, $booksArray, 'toKeyValue() uses __toString() for the value if no second field name is passed'); - - $expected = array(); - foreach ($books as $book) { - $expected[$book->getId()] = $book->getTitle(); - } - $booksArray = $books->toKeyValue(); - $this->assertEquals($expected, $booksArray, 'toKeyValue() uses primary key for the key and __toString() for the value if no field name is passed'); - } - - public function testPopulateRelation() - { - AuthorPeer::clearInstancePool(); - BookPeer::clearInstancePool(); - $authors = AuthorQuery::create()->find(); - $books = $authors->populateRelation('Book'); - $this->assertTrue($books instanceof PropelObjectCollection, 'populateRelation() returns a PropelCollection instance'); - $this->assertEquals('Book', $books->getModel(), 'populateRelation() returns a collection of the related objects'); - $this->assertEquals(4, count($books), 'populateRelation() the list of related objects'); - } - - public function testPopulateRelationCriteria() - { - AuthorPeer::clearInstancePool(); - BookPeer::clearInstancePool(); - $authors = AuthorQuery::create()->find(); - $c = new Criteria(); - $c->setLimit(3); - $books = $authors->populateRelation('Book', $c); - $this->assertEquals(3, count($books), 'populateRelation() accepts an optional criteria object to filter the query'); - } - - public function testPopulateRelationOneToMany() - { - $con = Propel::getConnection(); - AuthorPeer::clearInstancePool(); - BookPeer::clearInstancePool(); - $authors = AuthorQuery::create()->find($con); - $count = $con->getQueryCount(); - $books = $authors->populateRelation('Book', null, $con); - foreach ($authors as $author) { - foreach ($author->getBooks() as $book) { - $this->assertEquals($author, $book->getAuthor()); - } - } - $this->assertEquals($count + 1, $con->getQueryCount(), 'populateRelation() populates a one-to-many relationship with a single supplementary query'); - } - - public function testPopulateRelationManyToOne() - { - $con = Propel::getConnection(); - AuthorPeer::clearInstancePool(); - BookPeer::clearInstancePool(); - $books = BookQuery::create()->find($con); - $count = $con->getQueryCount(); - $books->populateRelation('Author', null, $con); - foreach ($books as $book) { - $author = $book->getAuthor(); - } - $this->assertEquals($count + 1, $con->getQueryCount(), 'populateRelation() populates a many-to-one relationship with a single supplementary query'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandCollectionTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandCollectionTest.php deleted file mode 100644 index 8ceddb22e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandCollectionTest.php +++ /dev/null @@ -1,76 +0,0 @@ -con); - $this->books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find(); - } - - public function testSetFormatter() - { - $this->assertTrue($this->books instanceof PropelOnDemandCollection); - $this->assertEquals(4, count($this->books)); - } - - public function testKeys() - { - $i = 0; - foreach ($this->books as $key => $book) { - $this->assertEquals($i, $key); - $i++; - } - } - - /** - * @expectedException PropelException - */ - public function testoffsetExists() - { - $this->books->offsetExists(2); - } - - /** - * @expectedException PropelException - */ - public function testoffsetGet() - { - $this->books->offsetGet(2); - } - - /** - * @expectedException PropelException - */ - public function testoffsetSet() - { - $this->books->offsetSet(2, 'foo'); - } - - /** - * @expectedException PropelException - */ - public function testoffsetUnset() - { - $this->books->offsetUnset(2); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandIteratorTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandIteratorTest.php deleted file mode 100644 index 587f4602e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/collection/PropelOnDemandIteratorTest.php +++ /dev/null @@ -1,59 +0,0 @@ -con); - } - - public function testInstancePoolingDisabled() - { - Propel::enableInstancePooling(); - $books = PropelQuery::from('Book') - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) - ->find($this->con); - foreach ($books as $book) { - $this->assertFalse(Propel::isInstancePoolingEnabled()); - } - } - - public function testInstancePoolingReenabled() - { - Propel::enableInstancePooling(); - $books = PropelQuery::from('Book') - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) - ->find($this->con); - foreach ($books as $book) { - } - $this->assertTrue(Propel::isInstancePoolingEnabled()); - - Propel::disableInstancePooling(); - $books = PropelQuery::from('Book') - ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) - ->find($this->con); - foreach ($books as $book) { - } - $this->assertFalse(Propel::isInstancePoolingEnabled()); - Propel::enableInstancePooling(); - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/connection/PropelPDOTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/connection/PropelPDOTest.php deleted file mode 100644 index 0befc1d1d..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/connection/PropelPDOTest.php +++ /dev/null @@ -1,425 +0,0 @@ -assertFalse($con->getAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES)); - $con->setAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES, true); - $this->assertTrue($con->getAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES)); - - $con->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); - $this->assertEquals(PDO::CASE_LOWER, $con->getAttribute(PDO::ATTR_CASE)); - } - - public function testNestedTransactionCommit() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME); - - $this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is equal to 0 before transaction'); - $this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction by default'); - - $con->beginTransaction(); - - $this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction is incremented after main transaction begin'); - $this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction begin'); - - try { - - $a = new Author(); - $a->setFirstName('Test'); - $a->setLastName('User'); - $a->save($con); - $authorId = $a->getId(); - $this->assertNotNull($authorId, "Expected valid new author ID"); - - $con->beginTransaction(); - - $this->assertEquals(2, $con->getNestedTransactionCount(), 'nested transaction is incremented after nested transaction begin'); - $this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after nested transaction begin'); - - try { - - $a2 = new Author(); - $a2->setFirstName('Test2'); - $a2->setLastName('User2'); - $a2->save($con); - $authorId2 = $a2->getId(); - $this->assertNotNull($authorId2, "Expected valid new author ID"); - - $con->commit(); - - $this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction decremented after nested transaction commit'); - $this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction commit'); - - } catch (Exception $e) { - $con->rollBack(); - throw $e; - } - - $con->commit(); - - $this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction decremented after main transaction commit'); - $this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after main transaction commit'); - - } catch (Exception $e) { - $con->rollBack(); - } - - AuthorPeer::clearInstancePool(); - $at = AuthorPeer::retrieveByPK($authorId); - $this->assertNotNull($at, "Committed transaction is persisted in database"); - $at2 = AuthorPeer::retrieveByPK($authorId2); - $this->assertNotNull($at2, "Committed transaction is persisted in database"); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/699 - */ - public function testNestedTransactionRollBackRethrow() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME); - - $con->beginTransaction(); - try { - - $a = new Author(); - $a->setFirstName('Test'); - $a->setLastName('User'); - $a->save($con); - $authorId = $a->getId(); - - $this->assertNotNull($authorId, "Expected valid new author ID"); - - $con->beginTransaction(); - - $this->assertEquals(2, $con->getNestedTransactionCount(), 'nested transaction is incremented after nested transaction begin'); - $this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after nested transaction begin'); - - try { - $con->exec('INVALID SQL'); - $this->fail("Expected exception on invalid SQL"); - } catch (PDOException $x) { - $con->rollBack(); - - $this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction decremented after nested transaction rollback'); - $this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction rollback'); - - throw $x; - } - - $con->commit(); - } catch (Exception $x) { - $con->rollBack(); - } - - AuthorPeer::clearInstancePool(); - $at = AuthorPeer::retrieveByPK($authorId); - $this->assertNull($at, "Rolled back transaction is not persisted in database"); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/699 - */ - public function testNestedTransactionRollBackSwallow() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME); - - $con->beginTransaction(); - try { - - $a = new Author(); - $a->setFirstName('Test'); - $a->setLastName('User'); - $a->save($con); - - $authorId = $a->getId(); - $this->assertNotNull($authorId, "Expected valid new author ID"); - - $con->beginTransaction(); - try { - - $a2 = new Author(); - $a2->setFirstName('Test2'); - $a2->setLastName('User2'); - $a2->save($con); - $authorId2 = $a2->getId(); - $this->assertNotNull($authorId2, "Expected valid new author ID"); - - $con->exec('INVALID SQL'); - $this->fail("Expected exception on invalid SQL"); - } catch (PDOException $e) { - $con->rollBack(); - // NO RETHROW - } - - $a3 = new Author(); - $a3->setFirstName('Test2'); - $a3->setLastName('User2'); - $a3->save($con); - - $authorId3 = $a3->getId(); - $this->assertNotNull($authorId3, "Expected valid new author ID"); - - $con->commit(); - $this->fail("Commit fails after a nested rollback"); - } catch (PropelException $e) { - $this->assertTrue(true, "Commit fails after a nested rollback"); - $con->rollback(); - } - - AuthorPeer::clearInstancePool(); - $at = AuthorPeer::retrieveByPK($authorId); - $this->assertNull($at, "Rolled back transaction is not persisted in database"); - $at2 = AuthorPeer::retrieveByPK($authorId2); - $this->assertNull($at2, "Rolled back transaction is not persisted in database"); - $at3 = AuthorPeer::retrieveByPK($authorId3); - $this->assertNull($at3, "Rolled back nested transaction is not persisted in database"); - } - - public function testNestedTransactionForceRollBack() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME); - - // main transaction - $con->beginTransaction(); - - $a = new Author(); - $a->setFirstName('Test'); - $a->setLastName('User'); - $a->save($con); - $authorId = $a->getId(); - - // nested transaction - $con->beginTransaction(); - - $a2 = new Author(); - $a2->setFirstName('Test2'); - $a2->setLastName('User2'); - $a2->save($con); - $authorId2 = $a2->getId(); - - // force rollback - $con->forceRollback(); - - $this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is null after nested transaction forced rollback'); - $this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after nested transaction force rollback'); - - AuthorPeer::clearInstancePool(); - $at = AuthorPeer::retrieveByPK($authorId); - $this->assertNull($at, "Rolled back transaction is not persisted in database"); - $at2 = AuthorPeer::retrieveByPK($authorId2); - $this->assertNull($at2, "Forced Rolled back nested transaction is not persisted in database"); - } - - public function testLatestQuery() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $con->setLastExecutedQuery(123); - $this->assertEquals(123, $con->getLastExecutedQuery(), 'PropelPDO has getter and setter for last executed query'); - } - - public function testLatestQueryMoreThanTenArgs() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new Criteria(); - $c->add(BookPeer::ID, array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Criteria::IN); - $books = BookPeer::doSelect($c, $con); - $expected = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.ID IN (1,1,1,1,1,1,1,1,1,1,1,1)"; - $this->assertEquals($expected, $con->getLastExecutedQuery(), 'PropelPDO correctly replaces arguments in queries'); - } - - public function testQueryCount() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $count = $con->getQueryCount(); - $con->incrementQueryCount(); - $this->assertEquals($count + 1, $con->getQueryCount(), 'PropelPDO has getter and incrementer for query count'); - } - - public function testUseDebug() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $con->useDebug(false); - $this->assertEquals(array('PDOStatement'), $con->getAttribute(PDO::ATTR_STATEMENT_CLASS), 'Statement is PDOStatement when debug is false'); - $con->useDebug(true); - $this->assertEquals(array('DebugPDOStatement', array($con)), $con->getAttribute(PDO::ATTR_STATEMENT_CLASS), 'statement is DebugPDOStament when debug is true'); - } - - public function testDebugLatestQuery() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE); - - $con->useDebug(false); - $this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO reinitializes the latest query when debug is set to false'); - - $books = BookPeer::doSelect($c, $con); - $this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO does not update the last executed query when useLogging is false'); - - $con->useDebug(true); - $books = BookPeer::doSelect($c, $con); - $latestExecutedQuery = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE LIKE 'Harry%s'"; - if (!Propel::getDB(BookPeer::DATABASE_NAME)->useQuoteIdentifier()) { - $latestExecutedQuery = str_replace('`', '', $latestExecutedQuery); - } - $this->assertEquals($latestExecutedQuery, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query when useLogging is true'); - - BookPeer::doDeleteAll($con); - $latestExecutedQuery = "DELETE FROM `book`"; - $this->assertEquals($latestExecutedQuery, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on delete operations'); - - $sql = 'DELETE FROM book WHERE 1=1'; - $con->exec($sql); - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on exec operations'); - - $sql = 'DELETE FROM book WHERE 2=2'; - $con->query($sql); - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on query operations'); - - $stmt = $con->prepare('DELETE FROM book WHERE 1=:p1'); - $stmt->bindValue(':p1', '2'); - $stmt->execute(); - $this->assertEquals("DELETE FROM book WHERE 1='2'", $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on prapared statements'); - - $con->useDebug(false); - $this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO reinitializes the latest query when debug is set to false'); - - $con->useDebug(true); - } - - public function testDebugQueryCount() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE); - - $con->useDebug(false); - $this->assertEquals(0, $con->getQueryCount(), 'PropelPDO does not update the query count when useLogging is false'); - - $books = BookPeer::doSelect($c, $con); - $this->assertEquals(0, $con->getQueryCount(), 'PropelPDO does not update the query count when useLogging is false'); - - $con->useDebug(true); - $books = BookPeer::doSelect($c, $con); - $this->assertEquals(1, $con->getQueryCount(), 'PropelPDO updates the query count when useLogging is true'); - - BookPeer::doDeleteAll($con); - $this->assertEquals(2, $con->getQueryCount(), 'PropelPDO updates the query count on delete operations'); - - $sql = 'DELETE FROM book WHERE 1=1'; - $con->exec($sql); - $this->assertEquals(3, $con->getQueryCount(), 'PropelPDO updates the query count on exec operations'); - - $sql = 'DELETE FROM book WHERE 2=2'; - $con->query($sql); - $this->assertEquals(4, $con->getQueryCount(), 'PropelPDO updates the query count on query operations'); - - $stmt = $con->prepare('DELETE FROM book WHERE 1=:p1'); - $stmt->bindValue(':p1', '2'); - $stmt->execute(); - $this->assertEquals(5, $con->getQueryCount(), 'PropelPDO updates the query count on prapared statements'); - - $con->useDebug(false); - $this->assertEquals(0, $con->getQueryCount(), 'PropelPDO reinitializes the query count when debug is set to false'); - - $con->useDebug(true); - } - - public function testDebugLog() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT); - - // save data to return to normal state after test - $logger = $con->getLogger(); - - $testLog = new myLogger(); - $con->setLogger($testLog); - - $logEverything = array('PropelPDO::exec', 'PropelPDO::query', 'PropelPDO::beginTransaction', 'PropelPDO::commit', 'PropelPDO::rollBack', 'DebugPDOStatement::execute'); - Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->setParameter("debugpdo.logging.methods", $logEverything); - $con->useDebug(true); - - // test transaction log - $con->beginTransaction(); - $this->assertEquals('log: Begin transaction', $testLog->latestMessage, 'PropelPDO logs begin transation in debug mode'); - - $con->commit(); - $this->assertEquals('log: Commit transaction', $testLog->latestMessage, 'PropelPDO logs commit transation in debug mode'); - - $con->beginTransaction(); - $con->rollBack(); - $this->assertEquals('log: Rollback transaction', $testLog->latestMessage, 'PropelPDO logs rollback transation in debug mode'); - - $con->beginTransaction(); - $testLog->latestMessage = ''; - $con->beginTransaction(); - $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested begin transation in debug mode'); - $con->commit(); - $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested commit transation in debug mode'); - $con->beginTransaction(); - $con->rollBack(); - $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested rollback transation in debug mode'); - $con->rollback(); - - // test query log - $con->beginTransaction(); - - $c = new Criteria(); - $c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE); - - $books = BookPeer::doSelect($c, $con); - $latestExecutedQuery = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE LIKE 'Harry%s'"; - $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs queries and populates bound parameters in debug mode'); - - BookPeer::doDeleteAll($con); - $latestExecutedQuery = "DELETE FROM `book`"; - $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs deletion queries in debug mode'); - - $latestExecutedQuery = 'DELETE FROM book WHERE 1=1'; - $con->exec($latestExecutedQuery); - $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs exec queries in debug mode'); - - $con->commit(); - - // return to normal state after test - $con->setLogger($logger); - $config->setParameter("debugpdo.logging.methods", array('PropelPDO::exec', 'PropelPDO::query', 'DebugPDOStatement::execute')); - } -} - -class myLogger -{ - public $latestMessage = ''; - - public function __call($method, $arguments) - { - $this->latestMessage = $method . ': ' . array_shift($arguments); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterTest.php deleted file mode 100644 index b1bcde670..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterTest.php +++ /dev/null @@ -1,129 +0,0 @@ -query('SELECT * FROM book'); - $formatter = new PropelArrayFormatter(); - try { - $books = $formatter->format($stmt); - $this->fail('PropelArrayFormatter::format() throws an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->assertTrue(true,'PropelArrayFormatter::format() throws an exception when called with no valid criteria'); - } - } - - public function testFormatManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelArrayFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection'); - $this->assertEquals(4, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query'); - foreach ($books as $book) { - $this->assertTrue(is_array($book), 'PropelArrayFormatter::format() returns an array of arrays'); - } - } - - public function testFormatOneResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"'); - $formatter = new PropelArrayFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection'); - $this->assertEquals(1, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query'); - $book = $books->shift(); - $this->assertTrue(is_array($book), 'PropelArrayFormatter::format() returns an array of arrays'); - $this->assertEquals('Quicksilver', $book['Title'], 'PropelArrayFormatter::format() returns the arrays matching the query'); - $expected = array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId'); - $this->assertEquals($expected, array_keys($book), 'PropelArrayFormatter::format() returns an associative array with column phpNames as keys'); - } - - public function testFormatNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelArrayFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection'); - $this->assertEquals(0, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query'); - } - - public function testFormatOneNoCriteria() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelArrayFormatter(); - try { - $book = $formatter->formatOne($stmt); - $this->fail('PropelArrayFormatter::formatOne() throws an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->assertTrue(true,'PropelArrayFormatter::formatOne() throws an exception when called with no valid criteria'); - } - } - - public function testFormatOneManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelArrayFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertTrue(is_array($book), 'PropelArrayFormatter::formatOne() returns an array'); - $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId'), array_keys($book), 'PropelArrayFormatter::formatOne() returns a single row even if the query has many results'); - } - - public function testFormatOneNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelArrayFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertNull($book, 'PropelArrayFormatter::formatOne() returns null when no result'); - } - - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterWithTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterWithTest.php deleted file mode 100644 index e0addfc46..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelArrayFormatterWithTest.php +++ /dev/null @@ -1,383 +0,0 @@ -findOne($con); - $count = $con->getQueryCount(); - $this->assertEquals($book['Title'], 'Don Juan', 'Main object is correctly hydrated ' . $msg); - $author = $book['Author']; - $this->assertEquals($author['LastName'], 'Byron', 'Related object is correctly hydrated ' . $msg); - $publisher = $book['Publisher']; - $this->assertEquals($publisher['Name'], 'Penguin', 'Related object is correctly hydrated ' . $msg); - } - - public function testFindOneWith() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'without instance pool'); - } - - public function testFindOneWithAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->orderBy('Book.Title'); - $c->join('Book.Author a'); - $c->with('a'); - $c->join('Book.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with alias'); - } - - public function testFindOneWithMainAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->setModelAlias('b', true); - $c->orderBy('b.Title'); - $c->join('b.Author a'); - $c->with('a'); - $c->join('b.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with main alias'); - } - - public function testFindOneWithUsingInstancePool() - { - BookstoreDataPopulator::populate(); - // instance pool contains all objects by default, since they were just populated - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'with instance pool'); - } - - public function testFindOneWithEmptyLeftJoin() - { - // save a book with no author - $b = new Book(); - $b->setTitle('Foo'); - $b->save(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->where('Book.Title = ?', 'Foo'); - $c->leftJoin('Book.Author'); - $c->with('Author'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $count = $con->getQueryCount(); - $author = $book['Author']; - $this->assertEquals(array(), $author, 'Related object is not hydrated if empty'); - } - - public function testFindOneWithRelationName() - { - BookstoreDataPopulator::populate(); - BookstoreEmployeePeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'BookstoreEmployee'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->join('BookstoreEmployee.Supervisor s'); - $c->with('s'); - $c->where('s.Name = ?', 'John'); - $emp = $c->findOne(); - $this->assertEquals($emp['Name'], 'Pieter', 'Main object is correctly hydrated'); - $sup = $emp['Supervisor']; - $this->assertEquals($sup['Name'], 'John', 'Related object is correctly hydrated'); - } - - /** - * @see http://www.propelorm.org/ticket/959 - */ - public function testFindOneWithSameRelatedObject() - { - BookPeer::doDeleteAll(); - AuthorPeer::doDeleteAll(); - $auth = new Author(); - $auth->setFirstName('John'); - $auth->save(); - $book1 = new Book(); - $book1->setTitle('Hello'); - $book1->setAuthor($auth); - $book1->save(); - $book2 = new Book(); - $book2->setTitle('World'); - $book2->setAuthor($auth); - $book2->save(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->join('Book.Author'); - $c->with('Author'); - $books = $c->find(); - - $this->assertEquals(2, count($books)); - $firstBook = $books[0]; - $this->assertTrue(isset($firstBook['Author'])); - $secondBook = $books[1]; - $this->assertTrue(isset($secondBook['Author'])); - } - - public function testFindOneWithDuplicateRelation() - { - EssayPeer::doDeleteAll(); - $auth1 = new Author(); - $auth1->setFirstName('John'); - $auth1->save(); - $auth2 = new Author(); - $auth2->setFirstName('Jack'); - $auth2->save(); - $essay = new Essay(); - $essay->setTitle('Foo'); - $essay->setFirstAuthor($auth1->getId()); - $essay->setSecondAuthor($auth2->getId()); - $essay->save(); - AuthorPeer::clearInstancePool(); - EssayPeer::clearInstancePool(); - - $c = new ModelCriteria('bookstore', 'Essay'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->join('Essay.AuthorRelatedByFirstAuthor'); - $c->with('AuthorRelatedByFirstAuthor'); - $c->where('Essay.Title = ?', 'Foo'); - $essay = $c->findOne(); - $this->assertEquals($essay['Title'], 'Foo', 'Main object is correctly hydrated'); - $firstAuthor = $essay['AuthorRelatedByFirstAuthor']; - $this->assertEquals($firstAuthor['FirstName'], 'John', 'Related object is correctly hydrated'); - $this->assertFalse(array_key_exists('AuthorRelatedBySecondAuthor', $essay), 'Only related object specified in with() is hydrated'); - } - - public function testFindOneWithDistantClass() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Review'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->where('Review.Recommended = ?', true); - $c->join('Review.Book'); - $c->with('Book'); - $c->join('Book.Author'); - $c->with('Author'); - $review = $c->findOne(); - $this->assertEquals($review['ReviewedBy'], 'Washington Post', 'Main object is correctly hydrated'); - $book = $review['Book']; - $this->assertEquals('Harry Potter and the Order of the Phoenix', $book['Title'], 'Related object is correctly hydrated'); - $author = $book['Author']; - $this->assertEquals('J.K.', $author['FirstName'], 'Related object is correctly hydrated'); - } - - /** - * @expectedException PropelException - */ - public function testFindOneWithOneToManyAndLimit() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->add(BookPeer::ISBN, '043935806X'); - $c->leftJoin('Book.Review'); - $c->with('Review'); - $c->limit(5); - $books = $c->find(); - } - - public function testFindOneWithOneToMany() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->add(BookPeer::ISBN, '043935806X'); - $c->leftJoin('Book.Review'); - $c->with('Review'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $books = $c->find($con); - $this->assertEquals(1, count($books), 'with() does not duplicate the main object'); - $book = $books[0]; - $this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Main object is correctly hydrated'); - $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Reviews'), array_keys($book), 'with() adds a plural index for the one to many relationship'); - $reviews = $book['Reviews']; - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - $review1 = $reviews[0]; - $this->assertEquals(array('Id', 'ReviewedBy', 'ReviewDate', 'Recommended', 'Status', 'BookId'), array_keys($review1), 'with() Related objects are correctly hydrated'); - } - - public function testFindOneWithOneToManyCustomOrder() - { - $author1 = new Author(); - $author1->setFirstName('AA'); - $author2 = new Author(); - $author2->setFirstName('BB'); - $book1 = new Book(); - $book1->setTitle('Aaa'); - $book1->setAuthor($author1); - $book1->save(); - $book2 = new Book(); - $book2->setTitle('Bbb'); - $book2->setAuthor($author2); - $book2->save(); - $book3 = new Book(); - $book3->setTitle('Ccc'); - $book3->setAuthor($author1); - $book3->save(); - $authors = AuthorQuery::create() - ->setFormatter(ModelCriteria::FORMAT_ARRAY) - ->leftJoin('Author.Book') - ->orderBy('Book.Title') - ->with('Book') - ->find(); - $this->assertEquals(2, count($authors), 'with() used on a many-to-many doesn\'t change the main object count'); - } - - public function testFindOneWithOneToManyThenManyToOne() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Author'); - $c->add(AuthorPeer::LAST_NAME, 'Rowling'); - $c->leftJoinWith('Author.Book'); - $c->leftJoinWith('Book.Review'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $authors = $c->find($con); - $this->assertEquals(1, count($authors), 'with() does not duplicate the main object'); - $rowling = $authors[0]; - $this->assertEquals($rowling['FirstName'], 'J.K.', 'Main object is correctly hydrated'); - $books = $rowling['Books']; - $this->assertEquals(1, count($books), 'Related objects are correctly hydrated'); - $book = $books[0]; - $this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated'); - $reviews = $book['Reviews']; - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } - - public function testFindOneWithOneToManyThenManyToOneUsingAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Author'); - $c->add(AuthorPeer::LAST_NAME, 'Rowling'); - $c->leftJoinWith('Author.Book b'); - $c->leftJoinWith('b.Review r'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $authors = $c->find($con); - $this->assertEquals(1, count($authors), 'with() does not duplicate the main object'); - $rowling = $authors[0]; - $this->assertEquals($rowling['FirstName'], 'J.K.', 'Main object is correctly hydrated'); - $books = $rowling['Books']; - $this->assertEquals(1, count($books), 'Related objects are correctly hydrated'); - $book = $books[0]; - $this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated'); - $reviews = $book['Reviews']; - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } - - public function testFindOneWithColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'AuthorName', 'AuthorName2'), array_keys($book), 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book['Title']); - $this->assertEquals('Gunter', $book['AuthorName'], 'PropelArrayFormatter adds withColumns as columns'); - $this->assertEquals('Grass', $book['AuthorName2'], 'PropelArrayFormatter correctly hydrates all as columns'); - } - - public function testFindOneWithClassAndColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ARRAY); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $c->with('Author'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Author', 'AuthorName', 'AuthorName2'), array_keys($book), 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book['Title']); - $this->assertEquals('Gunter', $book['Author']['FirstName'], 'PropelArrayFormatter correctly hydrates withclass and columns'); - $this->assertEquals('Gunter', $book['AuthorName'], 'PropelArrayFormatter adds withColumns as columns'); - $this->assertEquals('Grass', $book['AuthorName2'], 'PropelArrayFormatter correctly hydrates all as columns'); - } - - public function testFindPkWithOneToMany() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = BookQuery::create() - ->findOneByTitle('Harry Potter and the Order of the Phoenix', $con); - $pk = $book->getPrimaryKey(); - BookPeer::clearInstancePool(); - $book = BookQuery::create() - ->setFormatter(ModelCriteria::FORMAT_ARRAY) - ->joinWith('Review') - ->findPk($pk, $con); - $reviews = $book['Reviews']; - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterInheritanceTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterInheritanceTest.php deleted file mode 100644 index 95ea1cce3..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterInheritanceTest.php +++ /dev/null @@ -1,55 +0,0 @@ -setName('b1'); - $b1->save(); - $b2 = new BookstoreManager(); - $b2->setName('b2'); - $b2->save(); - $b3 = new BookstoreCashier(); - $b3->setName('b3'); - $b3->save(); - } - - public function testFormat() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreEmployeePeer::clearInstancePool(); - - $stmt = $con->query('SELECT * FROM bookstore_employee'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'BookstoreEmployee')); - $emps = $formatter->format($stmt); - $expectedClass = array( - 'b1' =>'BookstoreEmployee', - 'b2' =>'BookstoreManager', - 'b3' =>'BookstoreCashier' - ); - foreach ($emps as $emp) { - $this->assertEquals($expectedClass[$emp->getName()], get_class($emp), 'format() creates objects of the correct class when using inheritance'); - } - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterTest.php deleted file mode 100644 index 7321a2fbf..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterTest.php +++ /dev/null @@ -1,125 +0,0 @@ -query('SELECT * FROM book'); - $formatter = new PropelObjectFormatter(); - try { - $books = $formatter->format($stmt); - $this->fail('PropelObjectFormatter::format() trows an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->assertTrue(true,'PropelObjectFormatter::format() trows an exception when called with no valid criteria'); - } - } - - public function testFormatManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection'); - $this->assertEquals(4, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query'); - foreach ($books as $book) { - $this->assertTrue($book instanceof Book, 'PropelObjectFormatter::format() returns an array of Model objects'); - } - } - - public function testFormatOneResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection'); - $this->assertEquals(1, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query'); - $book = $books->shift(); - $this->assertTrue($book instanceof Book, 'PropelObjectFormatter::format() returns an array of Model objects'); - $this->assertEquals('Quicksilver', $book->getTitle(), 'PropelObjectFormatter::format() returns the model objects matching the query'); - } - - public function testFormatNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection'); - $this->assertEquals(0, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query'); - } - - public function testFormatOneNoCriteria() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelObjectFormatter(); - try { - $book = $formatter->formatOne($stmt); - $this->fail('PropelObjectFormatter::formatOne() throws an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->assertTrue(true,'PropelObjectFormatter::formatOne() throws an exception when called with no valid criteria'); - } - } - - public function testFormatOneManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertTrue($book instanceof Book, 'PropelObjectFormatter::formatOne() returns a model object'); - } - - public function testFormatOneNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelObjectFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertNull($book, 'PropelObjectFormatter::formatOne() returns null when no result'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterWithTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterWithTest.php deleted file mode 100644 index 14279d9a3..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelObjectFormatterWithTest.php +++ /dev/null @@ -1,406 +0,0 @@ -findOne($con); - $count = $con->getQueryCount(); - $this->assertEquals($book->getTitle(), 'Don Juan', 'Main object is correctly hydrated ' . $msg); - $author = $book->getAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg); - $this->assertEquals($author->getLastName(), 'Byron', 'Related object is correctly hydrated ' . $msg); - $publisher = $book->getPublisher(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg); - $this->assertEquals($publisher->getName(), 'Penguin', 'Related object is correctly hydrated ' . $msg); - } - - public function testFindOneWith() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'without instance pool'); - } - - public function testFindOneWithAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title'); - $c->join('Book.Author a'); - $c->with('a'); - $c->join('Book.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with alias'); - } - - public function testFindOneWithMainAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->orderBy('b.Title'); - $c->join('b.Author a'); - $c->with('a'); - $c->join('b.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with main alias'); - } - - public function testFindOneWithUsingInstancePool() - { - BookstoreDataPopulator::populate(); - // instance pool contains all objects by default, since they were just populated - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'with instance pool'); - } - - public function testFindOneWithoutUsingInstancePool() - { - BookstoreDataPopulator::populate(); - Propel::disableInstancePooling(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'without instance pool'); - Propel::enableInstancePooling(); - } - - public function testFindOneWithEmptyLeftJoin() - { - // save a book with no author - $b = new Book(); - $b->setTitle('Foo'); - $b->save(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Title = ?', 'Foo'); - $c->leftJoin('Book.Author'); - $c->with('Author'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $count = $con->getQueryCount(); - $author = $book->getAuthor(); - $this->assertNull($author, 'Related object is not hydrated if empty'); - } - - public function testFindOneWithRelationName() - { - BookstoreDataPopulator::populate(); - BookstoreEmployeePeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'BookstoreEmployee'); - $c->join('BookstoreEmployee.Supervisor s'); - $c->with('s'); - $c->where('s.Name = ?', 'John'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $emp = $c->findOne($con); - $count = $con->getQueryCount(); - $this->assertEquals($emp->getName(), 'Pieter', 'Main object is correctly hydrated'); - $sup = $emp->getSupervisor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals($sup->getName(), 'John', 'Related object is correctly hydrated'); - } - - public function testFindOneWithDuplicateRelation() - { - EssayPeer::doDeleteAll(); - $auth1 = new Author(); - $auth1->setFirstName('John'); - $auth1->save(); - $auth2 = new Author(); - $auth2->setFirstName('Jack'); - $auth2->save(); - $essay = new Essay(); - $essay->setTitle('Foo'); - $essay->setFirstAuthor($auth1->getId()); - $essay->setSecondAuthor($auth2->getId()); - $essay->save(); - AuthorPeer::clearInstancePool(); - EssayPeer::clearInstancePool(); - - $c = new ModelCriteria('bookstore', 'Essay'); - $c->join('Essay.AuthorRelatedByFirstAuthor'); - $c->with('AuthorRelatedByFirstAuthor'); - $c->where('Essay.Title = ?', 'Foo'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $essay = $c->findOne($con); - $count = $con->getQueryCount(); - $this->assertEquals($essay->getTitle(), 'Foo', 'Main object is correctly hydrated'); - $firstAuthor = $essay->getAuthorRelatedByFirstAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals($firstAuthor->getFirstName(), 'John', 'Related object is correctly hydrated'); - $secondAuthor = $essay->getAuthorRelatedBySecondAuthor(); - $this->assertEquals($count + 1, $con->getQueryCount(), 'with() does not hydrate objects not in with'); - } - - public function testFindOneWithDistantClass() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - Propel::enableInstancePooling(); - $c = new ModelCriteria('bookstore', 'Review'); - $c->where('Review.Recommended = ?', true); - $c->join('Review.Book'); - $c->with('Book'); - $c->join('Book.Author'); - $c->with('Author'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $review = $c->findOne($con); - $count = $con->getQueryCount(); - $this->assertEquals($review->getReviewedBy(), 'Washington Post', 'Main object is correctly hydrated'); - $book = $review->getBook(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals('Harry Potter and the Order of the Phoenix', $book->getTitle(), 'Related object is correctly hydrated'); - $author = $book->getAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals('J.K.', $author->getFirstName(), 'Related object is correctly hydrated'); - } - - /** - * @expectedException PropelException - */ - public function testFindOneWithOneToManyAndLimit() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->add(BookPeer::ISBN, '043935806X'); - $c->leftJoin('Book.Review'); - $c->with('Review'); - $c->limit(5); - $books = $c->find(); - } - - public function testFindOneWithOneToMany() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->add(BookPeer::ISBN, '043935806X'); - $c->leftJoin('Book.Review'); - $c->with('Review'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $books = $c->find($con); - $this->assertEquals(1, count($books), 'with() does not duplicate the main object'); - $book = $books[0]; - $count = $con->getQueryCount(); - $this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Main object is correctly hydrated'); - $reviews = $book->getReviews(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - try { - $book->save(); - } catch (Exception $e) { - $this->fail('with() does not force objects to be new'); - } - } - - public function testFindOneWithOneToManyCustomOrder() - { - $author1 = new Author(); - $author1->setFirstName('AA'); - $author2 = new Author(); - $author2->setFirstName('BB'); - $book1 = new Book(); - $book1->setTitle('Aaa'); - $book1->setAuthor($author1); - $book1->save(); - $book2 = new Book(); - $book2->setTitle('Bbb'); - $book2->setAuthor($author2); - $book2->save(); - $book3 = new Book(); - $book3->setTitle('Ccc'); - $book3->setAuthor($author1); - $book3->save(); - $authors = AuthorQuery::create() - ->leftJoin('Author.Book') - ->orderBy('Book.Title') - ->with('Book') - ->find(); - $this->assertEquals(2, count($authors), 'with() used on a many-to-many doesn\'t change the main object count'); - } - - public function testFindOneWithOneToManyThenManyToOne() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Author'); - $c->add(AuthorPeer::LAST_NAME, 'Rowling'); - $c->leftJoinWith('Author.Book'); - $c->leftJoinWith('Book.Review'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $authors = $c->find($con); - $this->assertEquals(1, count($authors), 'with() does not duplicate the main object'); - $rowling = $authors[0]; - $count = $con->getQueryCount(); - $this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated'); - $books = $rowling->getBooks(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(1, count($books), 'Related objects are correctly hydrated'); - $book = $books[0]; - $this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated'); - $reviews = $book->getReviews(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } - - public function testFindOneWithOneToManyThenManyToOneUsingJoinRelated() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - - $con = Propel::getConnection(AuthorPeer::DATABASE_NAME); - $authors = AuthorQuery::create() - ->filterByLastName('Rowling') - ->joinBook('book') - ->with('book') - ->useQuery('book') - ->joinReview('review') - ->with('review') - ->endUse() - ->find($con); - $this->assertEquals(1, count($authors), 'with() does not duplicate the main object'); - $rowling = $authors[0]; - $count = $con->getQueryCount(); - $this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated'); - $books = $rowling->getBooks(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(1, count($books), 'Related objects are correctly hydrated'); - $book = $books[0]; - $this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated'); - $reviews = $book->getReviews(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } - - public function testFindOneWithOneToManyThenManyToOneUsingAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Author'); - $c->add(AuthorPeer::LAST_NAME, 'Rowling'); - $c->leftJoinWith('Author.Book b'); - $c->leftJoinWith('b.Review r'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $authors = $c->find($con); - $this->assertEquals(1, count($authors), 'with() does not duplicate the main object'); - $rowling = $authors[0]; - $count = $con->getQueryCount(); - $this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated'); - $books = $rowling->getBooks(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(1, count($books), 'Related objects are correctly hydrated'); - $book = $books[0]; - $this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated'); - $reviews = $book->getReviews(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } - - public function testFindOneWithColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book->getTitle()); - $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns'); - $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns'); - $this->assertEquals('Gunter', $book->getAuthorName(), 'PropelObjectFormatter adds withColumns as virtual columns'); - } - - public function testFindOneWithClassAndColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $c->with('Author'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = $c->findOne($con); - $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book->getTitle()); - $this->assertTrue($book->getAuthor() instanceof Author, 'PropelObjectFormatter correctly hydrates with class'); - $this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'PropelObjectFormatter correctly hydrates with class'); - $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns'); - $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns'); - } - - public function testFindPkWithOneToMany() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $book = BookQuery::create() - ->findOneByTitle('Harry Potter and the Order of the Phoenix', $con); - $pk = $book->getPrimaryKey(); - BookPeer::clearInstancePool(); - $book = BookQuery::create() - ->joinWith('Review') - ->findPk($pk, $con); - $count = $con->getQueryCount(); - $reviews = $book->getReviews(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); - $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterTest.php deleted file mode 100644 index a4c29bb38..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterTest.php +++ /dev/null @@ -1,151 +0,0 @@ -query('SELECT * FROM book'); - $formatter = new PropelOnDemandFormatter(); - try { - $books = $formatter->format($stmt); - $this->fail('PropelOnDemandFormatter::format() trows an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->assertTrue(true,'PropelOnDemandFormatter::format() trows an exception when called with no valid criteria'); - } - } - - public function testFormatManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::populate($con); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection'); - $this->assertEquals(4, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query'); - foreach ($books as $book) { - $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns an traversable collection of Model objects'); - } - } - - /** - * @expectedException PropelException - */ - public function testFormatManyResultsIteratedTwice() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::populate($con); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - foreach ($books as $book) { - // do nothing - } - foreach ($books as $book) { - // this should throw a PropelException since we're iterating a second time over a stream - } - } - - public function testFormatALotOfResults() - { - $nbBooks = 50; - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - Propel::disableInstancePooling(); - $book = new Book(); - for ($i=0; $i < $nbBooks; $i++) { - $book->clear(); - $book->setTitle('BookTest' . $i); - $book->save($con); - } - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection'); - $this->assertEquals($nbBooks, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query'); - $i = 0; - foreach ($books as $book) { - $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects'); - $this->assertEquals('BookTest' . $i, $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query'); - $i++; - } - Propel::enableInstancePooling(); - } - - - public function testFormatOneResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::populate($con); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection'); - $this->assertEquals(1, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query'); - foreach ($books as $book) { - $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects'); - $this->assertEquals('Quicksilver', $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query'); - } - } - - public function testFormatNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelCollection'); - $this->assertEquals(0, count($books), 'PropelOnDemandFormatter::format() returns an empty collection when no record match the query'); - foreach ($books as $book) { - $this->fail('PropelOnDemandFormatter returns an empty iterator when no record match the query'); - } - } - - public function testFormatOneManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::populate($con); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelOnDemandFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::formatOne() returns a model object'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterWithTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterWithTest.php deleted file mode 100644 index 264d7b25e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelOnDemandFormatterWithTest.php +++ /dev/null @@ -1,277 +0,0 @@ -limit(1); - $books = $c->find($con); - foreach ($books as $book) { - break; - } - $count = $con->getQueryCount(); - $this->assertEquals($book->getTitle(), 'Don Juan', 'Main object is correctly hydrated ' . $msg); - $author = $book->getAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg); - $this->assertEquals($author->getLastName(), 'Byron', 'Related object is correctly hydrated ' . $msg); - $publisher = $book->getPublisher(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg); - $this->assertEquals($publisher->getName(), 'Penguin', 'Related object is correctly hydrated ' . $msg); - } - - public function testFindOneWith() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'without instance pool'); - } - - public function testFindOneWithAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->orderBy('Book.Title'); - $c->join('Book.Author a'); - $c->with('a'); - $c->join('Book.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with alias'); - } - - public function testFindOneWithMainAlias() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->setModelAlias('b', true); - $c->orderBy('b.Title'); - $c->join('b.Author a'); - $c->with('a'); - $c->join('b.Publisher p'); - $c->with('p'); - $this->assertCorrectHydration1($c, 'with main alias'); - } - - public function testFindOneWithUsingInstancePool() - { - BookstoreDataPopulator::populate(); - // instance pool contains all objects by default, since they were just populated - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->orderBy('Book.Title'); - $c->join('Book.Author'); - $c->with('Author'); - $c->join('Book.Publisher'); - $c->with('Publisher'); - $this->assertCorrectHydration1($c, 'with instance pool'); - } - - public function testFindOneWithEmptyLeftJoin() - { - // save a book with no author - $b = new Book(); - $b->setTitle('Foo'); - $b->save(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->where('Book.Title = ?', 'Foo'); - $c->leftJoin('Book.Author'); - $c->with('Author'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $books = $c->find($con); - foreach ($books as $book) { - break; - } - $count = $con->getQueryCount(); - $author = $book->getAuthor(); - $this->assertNull($author, 'Related object is not hydrated if empty'); - } - - public function testFindOneWithRelationName() - { - BookstoreDataPopulator::populate(); - BookstoreEmployeePeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'BookstoreEmployee'); - $c->join('BookstoreEmployee.Supervisor s'); - $c->with('s'); - $c->where('s.Name = ?', 'John'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $emps = $c->find($con); - foreach ($emps as $emp) { - break; - } - $count = $con->getQueryCount(); - $this->assertEquals($emp->getName(), 'Pieter', 'Main object is correctly hydrated'); - $sup = $emp->getSupervisor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals($sup->getName(), 'John', 'Related object is correctly hydrated'); - } - - public function testFindOneWithDuplicateRelation() - { - EssayPeer::doDeleteAll(); - $auth1 = new Author(); - $auth1->setFirstName('John'); - $auth1->save(); - $auth2 = new Author(); - $auth2->setFirstName('Jack'); - $auth2->save(); - $essay = new Essay(); - $essay->setTitle('Foo'); - $essay->setFirstAuthor($auth1->getId()); - $essay->setSecondAuthor($auth2->getId()); - $essay->save(); - AuthorPeer::clearInstancePool(); - EssayPeer::clearInstancePool(); - - $c = new ModelCriteria('bookstore', 'Essay'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->join('Essay.AuthorRelatedByFirstAuthor'); - $c->with('AuthorRelatedByFirstAuthor'); - $c->where('Essay.Title = ?', 'Foo'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $essays = $c->find($con); - foreach ($essays as $essay) { - break; - } - $count = $con->getQueryCount(); - $this->assertEquals($essay->getTitle(), 'Foo', 'Main object is correctly hydrated'); - $firstAuthor = $essay->getAuthorRelatedByFirstAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals($firstAuthor->getFirstName(), 'John', 'Related object is correctly hydrated'); - $secondAuthor = $essay->getAuthorRelatedBySecondAuthor(); - $this->assertEquals($count + 1, $con->getQueryCount(), 'with() does not hydrate objects not in with'); - } - - public function testFindOneWithDistantClass() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Review'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->where('Review.Recommended = ?', true); - $c->join('Review.Book'); - $c->with('Book'); - $c->join('Book.Author'); - $c->with('Author'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $reviews = $c->find($con); - foreach ($reviews as $review) { - break; - } - $count = $con->getQueryCount(); - $this->assertEquals($review->getReviewedBy(), 'Washington Post', 'Main object is correctly hydrated'); - $book = $review->getBook(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals('Harry Potter and the Order of the Phoenix', $book->getTitle(), 'Related object is correctly hydrated'); - $author = $book->getAuthor(); - $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query'); - $this->assertEquals('J.K.', $author->getFirstName(), 'Related object is correctly hydrated'); - } - - /** - * @expectedException PropelException - */ - public function testFindOneWithOneToMany() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->add(BookPeer::ISBN, '043935806X'); - $c->leftJoin('Book.Review'); - $c->with('Review'); - $books = $c->find(); - } - - public function testFindOneWithColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $books = $c->find($con); - foreach ($books as $book) { - break; - } - $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book->getTitle()); - $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns'); - $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns'); - $this->assertEquals('Gunter', $book->getAuthorName(), 'PropelObjectFormatter adds withColumns as virtual columns'); - } - - public function testFindOneWithClassAndColumn() - { - BookstoreDataPopulator::populate(); - BookPeer::clearInstancePool(); - AuthorPeer::clearInstancePool(); - ReviewPeer::clearInstancePool(); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); - $c->filterByTitle('The Tin Drum'); - $c->join('Book.Author'); - $c->withColumn('Author.FirstName', 'AuthorName'); - $c->withColumn('Author.LastName', 'AuthorName2'); - $c->with('Author'); - $c->limit(1); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $books = $c->find($con); - foreach ($books as $book) { - break; - } - $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); - $this->assertEquals('The Tin Drum', $book->getTitle()); - $this->assertTrue($book->getAuthor() instanceof Author, 'PropelObjectFormatter correctly hydrates with class'); - $this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'PropelObjectFormatter correctly hydrates with class'); - $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns'); - $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelStatementFormatterTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelStatementFormatterTest.php deleted file mode 100644 index c2ea8077e..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/formatter/PropelStatementFormatterTest.php +++ /dev/null @@ -1,124 +0,0 @@ -query('SELECT * FROM book'); - $formatter = new PropelStatementFormatter(); - try { - $books = $formatter->format($stmt); - $this->assertTrue(true, 'PropelStatementFormatter::format() does not trow an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->fail('PropelStatementFormatter::format() does not trow an exception when called with no valid criteria'); - } - } - - public function testFormatManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelStatementFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement'); - $this->assertEquals(4, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query'); - while ($book = $books->fetch()) { - $this->assertTrue(is_array($book), 'PropelStatementFormatter::format() returns a statement that can be fetched'); - } - } - - public function testFormatOneResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"'); - $formatter = new PropelStatementFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement'); - $this->assertEquals(1, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query'); - $book = $books->fetch(PDO::FETCH_ASSOC); - $this->assertEquals('Quicksilver', $book['title'], 'PropelStatementFormatter::format() returns the rows matching the query'); - } - - public function testFormatNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelStatementFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $books = $formatter->format($stmt); - - $this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement'); - $this->assertEquals(0, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query'); - } - - public function testFormatoneNoCriteria() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelStatementFormatter(); - try { - $books = $formatter->formatOne($stmt); - $this->assertTrue(true, 'PropelStatementFormatter::formatOne() does not trow an exception when called with no valid criteria'); - } catch (PropelException $e) { - $this->fail('PropelStatementFormatter::formatOne() does not trow an exception when called with no valid criteria'); - } - } - - public function testFormatOneManyResults() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book'); - $formatter = new PropelStatementFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertTrue($book instanceof PDOStatement, 'PropelStatementFormatter::formatOne() returns a PDO Statement'); - } - - public function testFormatOneNoResult() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"'); - $formatter = new PropelStatementFormatter(); - $formatter->init(new ModelCriteria('bookstore', 'Book')); - $book = $formatter->formatOne($stmt); - - $this->assertNull($book, 'PropelStatementFormatter::formatOne() returns null when no result'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/ColumnMapTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/ColumnMapTest.php deleted file mode 100644 index f3225848f..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/ColumnMapTest.php +++ /dev/null @@ -1,141 +0,0 @@ -dmap = new DatabaseMap('foodb'); - $this->tmap = new TableMap('foo', $this->dmap); - $this->columnName = 'bar'; - $this->cmap = new ColumnMap($this->columnName, $this->tmap); - } - - protected function tearDown() - { - // nothing to do for now - parent::tearDown(); - } - - public function testConstructor() - { - $this->assertEquals($this->columnName, $this->cmap->getName(), 'constructor sets the column name'); - $this->assertEquals($this->tmap, $this->cmap->getTable(), 'Constructor sets the table map'); - $this->assertNull($this->cmap->getType(), 'A new column map has no type'); - } - - public function testPhpName() - { - $this->assertNull($this->cmap->getPhpName(), 'phpName is empty until set'); - $this->cmap->setPhpName('FooBar'); - $this->assertEquals('FooBar', $this->cmap->getPhpName(), 'phpName is set by setPhpName()'); - } - - public function testType() - { - $this->assertNull($this->cmap->getType(), 'type is empty until set'); - $this->cmap->setType('FooBar'); - $this->assertEquals('FooBar', $this->cmap->getType(), 'type is set by setType()'); - } - - public function tesSize() - { - $this->assertEquals(0, $this->cmap->getSize(), 'size is empty until set'); - $this->cmap->setSize(123); - $this->assertEquals(123, $this->cmap->getSize(), 'size is set by setSize()'); - } - - public function testPrimaryKey() - { - $this->assertFalse($this->cmap->isPrimaryKey(), 'primaryKey is false by default'); - $this->cmap->setPrimaryKey(true); - $this->assertTrue($this->cmap->isPrimaryKey(), 'primaryKey is set by setPrimaryKey()'); - } - - public function testNotNull() - { - $this->assertFalse($this->cmap->isNotNull(), 'notNull is false by default'); - $this->cmap->setNotNull(true); - $this->assertTrue($this->cmap->isNotNull(), 'notNull is set by setPrimaryKey()'); - } - - public function testDefaultValue() - { - $this->assertNull($this->cmap->getDefaultValue(), 'defaultValue is empty until set'); - $this->cmap->setDefaultValue('FooBar'); - $this->assertEquals('FooBar', $this->cmap->getDefaultValue(), 'defaultValue is set by setDefaultValue()'); - } - - public function testGetForeignKey() - { - $this->assertFalse($this->cmap->isForeignKey(), 'foreignKey is false by default'); - try - { - $this->cmap->getRelatedTable(); - $this->fail('getRelatedTable throws an exception when called on a column with no foreign key'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getRelatedTable throws an exception when called on a column with no foreign key'); - } - try - { - $this->cmap->getRelatedColumn(); - $this->fail('getRelatedColumn throws an exception when called on a column with no foreign key'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getRelatedColumn throws an exception when called on a column with no foreign key'); - } - $relatedTmap = $this->dmap->addTable('foo2'); - // required to let the database map use the foreign TableMap - $relatedCmap = $relatedTmap->addColumn('BAR2', 'Bar2', 'INTEGER'); - $this->cmap->setForeignKey('foo2', 'BAR2'); - $this->assertTrue($this->cmap->isForeignKey(), 'foreignKey is true after setting the foreign key via setForeignKey()'); - $this->assertEquals($relatedTmap, $this->cmap->getRelatedTable(), 'getRelatedTable returns the related TableMap object'); - $this->assertEquals($relatedCmap, $this->cmap->getRelatedColumn(), 'getRelatedColumn returns the related ColumnMap object'); - } - - public function testGetRelation() - { - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php'); - $bookTable = BookPeer::getTableMap(); - $titleColumn = $bookTable->getColumn('TITLE'); - $this->assertNull($titleColumn->getRelation(), 'getRelation() returns null for non-foreign key columns'); - $publisherColumn = $bookTable->getColumn('PUBLISHER_ID'); - $this->assertEquals($publisherColumn->getRelation(), $bookTable->getRelation('Publisher'), 'getRelation() returns the RelationMap object for this foreign key'); - $bookstoreTable = BookstoreEmployeePeer::getTableMap(); - $supervisorColumn = $bookstoreTable->getColumn('SUPERVISOR_ID'); - $this->assertEquals($supervisorColumn->getRelation(), $supervisorColumn->getRelation('Supervisor'), 'getRelation() returns the RelationMap object even whit ha specific refPhpName'); - - } - - public function testNormalizeName() - { - $this->assertEquals('', ColumnMap::normalizeName(''), 'normalizeColumnName() returns an empty string when passed an empty string'); - $this->assertEquals('BAR', ColumnMap::normalizeName('bar'), 'normalizeColumnName() uppercases the input'); - $this->assertEquals('BAR_BAZ', ColumnMap::normalizeName('bar_baz'), 'normalizeColumnName() does not mind underscores'); - $this->assertEquals('BAR', ColumnMap::normalizeName('FOO.BAR'), 'normalizeColumnName() removes table prefix'); - $this->assertEquals('BAR', ColumnMap::normalizeName('BAR'), 'normalizeColumnName() leaves normalized column names unchanged'); - $this->assertEquals('BAR_BAZ', ColumnMap::normalizeName('foo.bar_baz'), 'normalizeColumnName() can do all the above at the same time'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/DatabaseMapTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/DatabaseMapTest.php deleted file mode 100644 index 7a078131d..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/DatabaseMapTest.php +++ /dev/null @@ -1,171 +0,0 @@ -setName('baz'); - $this->setPhpName('Baz'); - } -} - -/** - * Test class for DatabaseMap. - * - * @author François Zaninotto - * @version $Id: DatabaseMapTest.php 1773 2010-05-25 10:25:06Z francois $ - * @package runtime.map - */ -class DatabaseMapTest extends PHPUnit_Framework_TestCase -{ - protected $databaseMap; - - protected function setUp() - { - parent::setUp(); - $this->databaseName = 'foodb'; - $this->databaseMap = TestDatabaseBuilder::getDmap(); - } - - protected function tearDown() - { - // nothing to do for now - parent::tearDown(); - } - - public function testConstructor() - { - $this->assertEquals($this->databaseName, $this->databaseMap->getName(), 'constructor sets the table name'); - } - - public function testAddTable() - { - $this->assertFalse($this->databaseMap->hasTable('foo'), 'tables are empty by default'); - try - { - $this->databaseMap->getTable('foo'); - $this->fail('getTable() throws an exception when called on an inexistent table'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getTable() throws an exception when called on an inexistent table'); - } - $tmap = $this->databaseMap->addTable('foo'); - $this->assertTrue($this->databaseMap->hasTable('foo'), 'hasTable() returns true when the table was added by way of addTable()'); - $this->assertEquals($tmap, $this->databaseMap->getTable('foo'), 'getTable() returns a table by name when the table was added by way of addTable()'); - } - - public function testAddTableObject() - { - $this->assertFalse($this->databaseMap->hasTable('foo2'), 'tables are empty by default'); - try - { - $this->databaseMap->getTable('foo2'); - $this->fail('getTable() throws an exception when called on a table with no builder'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getTable() throws an exception when called on a table with no builder'); - } - $tmap = new TableMap('foo2'); - $this->databaseMap->addTableObject($tmap); - $this->assertTrue($this->databaseMap->hasTable('foo2'), 'hasTable() returns true when the table was added by way of addTableObject()'); - $this->assertEquals($tmap, $this->databaseMap->getTable('foo2'), 'getTable() returns a table by name when the table was added by way of addTableObject()'); - } - - public function testAddTableFromMapClass() - { - $table1 = $this->databaseMap->addTableFromMapClass('BazTableMap'); - try - { - $table2 = $this->databaseMap->getTable('baz'); - $this->assertEquals($table1, $table2, 'addTableFromMapClass() adds a table from a map class'); - } catch(PropelException $e) { - $this->fail('addTableFromMapClass() adds a table from a map class'); - } - } - - public function testGetColumn() - { - try - { - $this->databaseMap->getColumn('foo.BAR'); - $this->fail('getColumn() throws an exception when called on column of an inexistent table'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getColumn() throws an exception when called on column of an inexistent table'); - } - $tmap = $this->databaseMap->addTable('foo'); - try - { - $this->databaseMap->getColumn('foo.BAR'); - $this->fail('getColumn() throws an exception when called on an inexistent column of an existent table'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getColumn() throws an exception when called on an inexistent column of an existent table'); - } - $column = $tmap->addColumn('BAR', 'Bar', 'INTEGER'); - $this->assertEquals($column, $this->databaseMap->getColumn('foo.BAR'), 'getColumn() returns a ColumnMap object based on a fully qualified name'); - } - - public function testGetTableByPhpName() - { - try - { - $this->databaseMap->getTableByPhpName('Foo1'); - $this->fail('getTableByPhpName() throws an exception when called on an inexistent table'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getTableByPhpName() throws an exception when called on an inexistent table'); - } - $tmap = $this->databaseMap->addTable('foo1'); - try - { - $this->databaseMap->getTableByPhpName('Foo1'); - $this->fail('getTableByPhpName() throws an exception when called on a table with no phpName'); - } catch(PropelException $e) { - $this->assertTrue(true, 'getTableByPhpName() throws an exception when called on a table with no phpName'); - } - $tmap2 = new TableMap('foo2'); - $tmap2->setClassname('Foo2'); - $this->databaseMap->addTableObject($tmap2); - $this->assertEquals($tmap2, $this->databaseMap->getTableByPhpName('Foo2'), 'getTableByPhpName() returns tableMap when phpName was set by way of TableMap::setPhpName()'); - } - - public function testGetTableByPhpNameNotLoaded() - { - set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes"); - require_once 'bookstore/map/BookTableMap.php'; - require_once 'bookstore/om/BaseBookPeer.php'; - require_once 'bookstore/BookPeer.php'; - $this->assertEquals('book', Propel::getDatabaseMap('bookstore')->getTableByPhpName('Book')->getName(), 'getTableByPhpName() can autoload a TableMap when the Peer class is generated and autoloaded'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/GeneratedRelationMapTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/GeneratedRelationMapTest.php deleted file mode 100644 index 62b84a77c..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/GeneratedRelationMapTest.php +++ /dev/null @@ -1,75 +0,0 @@ -databaseMap = Propel::getDatabaseMap('bookstore'); - } - - public function testGetRightTable() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $authorTable = $this->databaseMap->getTableByPhpName('Author'); - $this->assertEquals($authorTable, $bookTable->getRelation('Author')->getRightTable(), 'getRightTable() returns correct table when called on a many to one relationship'); - $this->assertEquals($bookTable, $authorTable->getRelation('Book')->getRightTable(), 'getRightTable() returns correct table when called on a one to many relationship'); - $bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $bookEmpAccTable = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount'); - $this->assertEquals($bookEmpAccTable, $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getRightTable(), 'getRightTable() returns correct table when called on a one to one relationship'); - $this->assertEquals($bookEmpTable, $bookEmpAccTable->getRelation('BookstoreEmployee')->getRightTable(), 'getRightTable() returns correct table when called on a one to one relationship'); - } - - public function testColumnMappings() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $bookTable->getRelation('Author')->getColumnMappings(), 'getColumnMappings returns local to foreign by default'); - $this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $bookTable->getRelation('Author')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns local to foreign when asked left to right for a many to one relationship'); - - $authorTable = $this->databaseMap->getTableByPhpName('Author'); - $this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $authorTable->getRelation('Book')->getColumnMappings(), 'getColumnMappings returns local to foreign by default'); - $this->assertEquals(array('author.ID' => 'book.AUTHOR_ID'), $authorTable->getRelation('Book')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns foreign to local when asked left to right for a one to many relationship'); - - $bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $this->assertEquals(array('bookstore_employee_account.EMPLOYEE_ID' => 'bookstore_employee.ID'), $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getColumnMappings(), 'getColumnMappings returns local to foreign by default'); - $this->assertEquals(array('bookstore_employee.ID' => 'bookstore_employee_account.EMPLOYEE_ID'), $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns foreign to local when asked left to right for a one to one relationship'); - } - - public function testCountColumnMappings() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertEquals(1, $bookTable->getRelation('Author')->countColumnMappings()); - - $rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite'); - $this->assertEquals(2, $rfTable->getRelation('BookOpinion')->countColumnMappings()); - } - - public function testIsComposite() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $this->assertFalse($bookTable->getRelation('Author')->isComposite()); - - $rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite'); - $this->assertTrue($rfTable->getRelation('BookOpinion')->isComposite()); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/RelatedMapSymmetricalTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/RelatedMapSymmetricalTest.php deleted file mode 100644 index 6737aa7df..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/RelatedMapSymmetricalTest.php +++ /dev/null @@ -1,70 +0,0 @@ -databaseMap = Propel::getDatabaseMap('bookstore'); - } - - public function testOneToMany() - { - $bookTable = $this->databaseMap->getTableByPhpName('Book'); - $bookToAuthor = $bookTable->getRelation('Author'); - $authorTable = $this->databaseMap->getTableByPhpName('Author'); - $authorToBook = $authorTable->getRelation('Book'); - $this->assertEquals($authorToBook, $bookToAuthor->getSymmetricalRelation()); - $this->assertEquals($bookToAuthor, $authorToBook->getSymmetricalRelation()); - } - - public function testOneToOne() - { - $accountTable = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount'); - $accountToEmployee = $accountTable->getRelation('BookstoreEmployee'); - $employeeTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee'); - $employeeToAccount = $employeeTable->getRelation('BookstoreEmployeeAccount'); - $this->assertEquals($accountToEmployee, $employeeToAccount->getSymmetricalRelation()); - $this->assertEquals($employeeToAccount, $accountToEmployee->getSymmetricalRelation()); - } - - public function testSeveralRelationsOnSameTable() - { - $authorTable = $this->databaseMap->getTableByPhpName('Author'); - $authorToEssay = $authorTable->getRelation('EssayRelatedByFirstAuthor'); - $essayTable = $this->databaseMap->getTableByPhpName('Essay'); - $essayToAuthor = $essayTable->getRelation('AuthorRelatedByFirstAuthor'); - $this->assertEquals($authorToEssay, $essayToAuthor->getSymmetricalRelation()); - $this->assertEquals($essayToAuthor, $authorToEssay->getSymmetricalRelation()); - } - - public function testCompositeForeignKey() - { - $favoriteTable = $this->databaseMap->getTableByPhpName('ReaderFavorite'); - $favoriteToOpinion = $favoriteTable->getRelation('BookOpinion'); - $opinionTable = $this->databaseMap->getTableByPhpName('BookOpinion'); - $opinionToFavorite = $opinionTable->getRelation('ReaderFavorite'); - $this->assertEquals($favoriteToOpinion, $opinionToFavorite->getSymmetricalRelation()); - $this->assertEquals($opinionToFavorite, $favoriteToOpinion->getSymmetricalRelation()); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/RelationMapTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/RelationMapTest.php deleted file mode 100644 index 202755781..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/RelationMapTest.php +++ /dev/null @@ -1,89 +0,0 @@ -databaseMap = new DatabaseMap('foodb'); - $this->relationName = 'foo'; - $this->rmap = new RelationMap($this->relationName); - } - - public function testConstructor() - { - $this->assertEquals($this->relationName, $this->rmap->getName(), 'constructor sets the relation name'); - } - - public function testLocalTable() - { - $this->assertNull($this->rmap->getLocalTable(), 'A new relation has no local table'); - $tmap1 = new TableMap('foo', $this->databaseMap); - $this->rmap->setLocalTable($tmap1); - $this->assertEquals($tmap1, $this->rmap->getLocalTable(), 'The local table is set by setLocalTable()'); - } - - public function testForeignTable() - { - $this->assertNull($this->rmap->getForeignTable(), 'A new relation has no foreign table'); - $tmap2 = new TableMap('bar', $this->databaseMap); - $this->rmap->setForeignTable($tmap2); - $this->assertEquals($tmap2, $this->rmap->getForeignTable(), 'The foreign table is set by setForeignTable()'); - } - - public function testProperties() - { - $properties = array('type', 'onUpdate', 'onDelete'); - foreach ($properties as $property) - { - $getter = 'get' . ucfirst($property); - $setter = 'set' . ucfirst($property); - $this->assertNull($this->rmap->$getter(), "A new relation has no $property"); - $this->rmap->$setter('foo_value'); - $this->assertEquals('foo_value', $this->rmap->$getter(), "The $property is set by setType()"); - } - } - - public function testColumns() - { - $this->assertEquals(array(), $this->rmap->getLocalColumns(), 'A new relation has no local columns'); - $this->assertEquals(array(), $this->rmap->getForeignColumns(), 'A new relation has no foreign columns'); - $tmap1 = new TableMap('foo', $this->databaseMap); - $col1 = $tmap1->addColumn('FOO1', 'Foo1PhpName', 'INTEGER'); - $tmap2 = new TableMap('bar', $this->databaseMap); - $col2 = $tmap2->addColumn('BAR1', 'Bar1PhpName', 'INTEGER'); - $this->rmap->addColumnMapping($col1, $col2); - $this->assertEquals(array($col1), $this->rmap->getLocalColumns(), 'addColumnMapping() adds a local table'); - $this->assertEquals(array($col2), $this->rmap->getForeignColumns(), 'addColumnMapping() adds a foreign table'); - $expected = array('foo.FOO1' => 'bar.BAR1'); - $this->assertEquals($expected, $this->rmap->getColumnMappings(), 'getColumnMappings() returns an associative array of column mappings'); - $col3 = $tmap1->addColumn('FOOFOO', 'FooFooPhpName', 'INTEGER'); - $col4 = $tmap2->addColumn('BARBAR', 'BarBarPhpName', 'INTEGER'); - $this->rmap->addColumnMapping($col3, $col4); - $this->assertEquals(array($col1, $col3), $this->rmap->getLocalColumns(), 'addColumnMapping() adds a local table'); - $this->assertEquals(array($col2, $col4), $this->rmap->getForeignColumns(), 'addColumnMapping() adds a foreign table'); - $expected = array('foo.FOO1' => 'bar.BAR1', 'foo.FOOFOO' => 'bar.BARBAR'); - $this->assertEquals($expected, $this->rmap->getColumnMappings(), 'getColumnMappings() returns an associative array of column mappings'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/map/TableMapTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/map/TableMapTest.php deleted file mode 100644 index 42e7e748b..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/map/TableMapTest.php +++ /dev/null @@ -1,286 +0,0 @@ -rmap = $this->addRelation('Bar', 'Bar', RelationMap::MANY_TO_ONE); - } -} - -class BarTableMap extends TableMap -{ - public function initialize() - { - $this->setName('bar'); - $this->setPhpName('Bar'); - } -} - - - -/** - * Test class for TableMap. - * - * @author François Zaninotto - * @version $Id: TableMapTest.php 1773 2010-05-25 10:25:06Z francois $ - * @package runtime.map - */ -class TableMapTest extends PHPUnit_Framework_TestCase -{ - protected $databaseMap; - - protected function setUp() - { - parent::setUp(); - $this->databaseMap = new DatabaseMap('foodb'); - $this->tableName = 'foo'; - $this->tmap = new TableMap($this->tableName, $this->databaseMap); - } - - protected function tearDown() - { - // nothing to do for now - parent::tearDown(); - } - - public function testConstructor() - { - $this->assertEquals(array(), $this->tmap->getColumns(), 'A new table map has no columns'); - $this->assertEquals($this->tableName, $this->tmap->getName(), 'constructor can set the table name'); - $this->assertEquals($this->databaseMap, $this->tmap->getDatabaseMap(), 'Constructor can set the database map'); - try { - $tmap = new TableMap(); - $this->assertTrue(true, 'A table map can be instanciated with no parameters'); - } catch (Exception $e) { - $this->fail('A table map can be instanciated with no parameters'); - } - } - - public function testProperties() - { - $tmap = new TableMap(); - $properties = array('name', 'phpName', 'className', 'package'); - foreach ($properties as $property) - { - $getter = 'get' . ucfirst($property); - $setter = 'set' . ucfirst($property); - $this->assertNull($tmap->$getter(), "A new relation has no $property"); - $tmap->$setter('foo_value'); - $this->assertEquals('foo_value', $tmap->$getter(), "The $property is set by setType()"); - } - } - - public function testHasColumn() - { - $this->assertFalse($this->tmap->hasColumn('BAR'), 'hascolumn() returns false when the column is not in the table map'); - $column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER'); - $this->assertTrue($this->tmap->hasColumn('BAR'), 'hascolumn() returns true when the column is in the table map'); - $this->assertTrue($this->tmap->hasColumn('foo.bar'), 'hascolumn() accepts a denormalized column name'); - $this->assertFalse($this->tmap->hasColumn('foo.bar', false), 'hascolumn() accepts a $normalize parameter to skip name normalization'); - $this->assertTrue($this->tmap->hasColumn('BAR', false), 'hascolumn() accepts a $normalize parameter to skip name normalization'); - $this->assertTrue($this->tmap->hasColumn($column), 'hascolumn() accepts a ColumnMap object as parameter'); - } - - public function testGetColumn() - { - $column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER'); - $this->assertEquals($column, $this->tmap->getColumn('BAR'), 'getColumn returns a ColumnMap according to a column name'); - try - { - $this->tmap->getColumn('FOO'); - $this->fail('getColumn throws an exception when called on an inexistent column'); - } catch(PropelException $e) {} - $this->assertEquals($column, $this->tmap->getColumn('foo.bar'), 'getColumn accepts a denormalized column name'); - try - { - $this->tmap->getColumn('foo.bar', false); - $this->fail('getColumn accepts a $normalize parameter to skip name normalization'); - } catch(PropelException $e) {} - } - - public function testGetColumnByPhpName() - { - $column = $this->tmap->addColumn('BAR_BAZ', 'BarBaz', 'INTEGER'); - $this->assertEquals($column, $this->tmap->getColumnByPhpName('BarBaz'), 'getColumnByPhpName() returns a ColumnMap according to a column phpName'); - try - { - $this->tmap->getColumn('Foo'); - $this->fail('getColumnByPhpName() throws an exception when called on an inexistent column'); - } catch(PropelException $e) {} - } - - public function testGetColumns() - { - $this->assertEquals(array(), $this->tmap->getColumns(), 'getColumns returns an empty array when no columns were added'); - $column1 = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER'); - $column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER'); - $this->assertEquals(array('BAR' => $column1, 'BAZ' => $column2), $this->tmap->getColumns(), 'getColumns returns the columns indexed by name'); - } - - public function testAddPrimaryKey() - { - $column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER'); - $this->assertTrue($column1->isPrimaryKey(), 'Columns added by way of addPrimaryKey() are primary keys'); - $column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER'); - $this->assertFalse($column2->isPrimaryKey(), 'Columns added by way of addColumn() are not primary keys by default'); - $column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true); - $this->assertTrue($column3->isPrimaryKey(), 'Columns added by way of addColumn() can be defined as primary keys'); - $column4 = $this->tmap->addForeignKey('BAZZZ', 'Bazzz', 'INTEGER', 'Table1', 'column1'); - $this->assertFalse($column4->isPrimaryKey(), 'Columns added by way of addForeignKey() are not primary keys'); - $column5 = $this->tmap->addForeignPrimaryKey('BAZZZZ', 'Bazzzz', 'INTEGER', 'table1', 'column1'); - $this->assertTrue($column5->isPrimaryKey(), 'Columns added by way of addForeignPrimaryKey() are primary keys'); - } - - public function testGetPrimaryKeyColumns() - { - $this->assertEquals(array(), $this->tmap->getPrimaryKeyColumns(), 'getPrimaryKeyColumns() returns an empty array by default'); - $column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER'); - $column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true); - $expected = array($column1, $column3); - $this->assertEquals($expected, $this->tmap->getPrimaryKeyColumns(), 'getPrimaryKeyColumns() returns an array of the table primary keys'); - } - - public function testGetPrimaryKeys() - { - $this->assertEquals(array(), $this->tmap->getPrimaryKeys(), 'getPrimaryKeys() returns an empty array by default'); - $column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER'); - $column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true); - $expected = array('BAR' => $column1, 'BAZZ' => $column3); - $this->assertEquals($expected, $this->tmap->getPrimaryKeys(), 'getPrimaryKeys() returns an array of the table primary keys'); - } - - public function testAddForeignKey() - { - $column1 = $this->tmap->addForeignKey('BAR', 'Bar', 'INTEGER', 'Table1', 'column1'); - $this->assertTrue($column1->isForeignKey(), 'Columns added by way of addForeignKey() are foreign keys'); - $column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER'); - $this->assertFalse($column2->isForeignKey(), 'Columns added by way of addColumn() are not foreign keys by default'); - $column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, false, 'Table1', 'column1'); - $this->assertTrue($column3->isForeignKey(), 'Columns added by way of addColumn() can be defined as foreign keys'); - $column4 = $this->tmap->addPrimaryKey('BAZZZ', 'Bazzz', 'INTEGER'); - $this->assertFalse($column4->isForeignKey(), 'Columns added by way of addPrimaryKey() are not foreign keys'); - $column5 = $this->tmap->addForeignPrimaryKey('BAZZZZ', 'Bazzzz', 'INTEGER', 'table1', 'column1'); - $this->assertTrue($column5->isForeignKey(), 'Columns added by way of addForeignPrimaryKey() are foreign keys'); - } - - public function testGetForeignKeys() - { - $this->assertEquals(array(), $this->tmap->getForeignKeys(), 'getForeignKeys() returns an empty array by default'); - $column1 = $this->tmap->addForeignKey('BAR', 'Bar', 'INTEGER', 'Table1', 'column1'); - $column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, false, 'Table1', 'column1'); - $expected = array('BAR' => $column1, 'BAZZ' => $column3); - $this->assertEquals($expected, $this->tmap->getForeignKeys(), 'getForeignKeys() returns an array of the table foreign keys'); - } - - public function testLazyLoadRelations() - { - try { - $this->tmap->getRelation('Bar'); - $this->fail('getRelation() throws an exception when called on a table with no relations'); - } catch (PropelException $e) { - $this->assertTrue(true, 'getRelation() throws an exception when called on a table with no relations'); - } - $foreigntmap = new BarTableMap(); - $this->databaseMap->addTableObject($foreigntmap); - $localtmap = new FooTableMap(); - $this->databaseMap->addTableObject($localtmap); - $rmap = $localtmap->getRelation('Bar'); - $this->assertEquals($rmap, $localtmap->rmap, 'getRelation() returns the relations lazy loaded by buildRelations()'); - } - - public function testAddRelation() - { - $foreigntmap1 = new TableMap('bar'); - $foreigntmap1->setClassname('Bar'); - $this->databaseMap->addTableObject($foreigntmap1); - $foreigntmap2 = new TableMap('baz'); - $foreigntmap2->setClassname('Baz'); - $this->databaseMap->addTableObject($foreigntmap2); - $this->rmap1 = $this->tmap->addRelation('Bar', 'Bar', RelationMap::MANY_TO_ONE); - $this->rmap2 = $this->tmap->addRelation('Bazz', 'Baz', RelationMap::ONE_TO_MANY); - $this->tmap->getRelations(); - // now on to the test - $this->assertEquals($this->rmap1->getLocalTable(), $this->tmap, 'adding a relation with HAS_ONE sets the local table to the current table'); - $this->assertEquals($this->rmap1->getForeignTable(), $foreigntmap1, 'adding a relation with HAS_ONE sets the foreign table according to the name given'); - $this->assertEquals(RelationMap::MANY_TO_ONE, $this->rmap1->getType(), 'adding a relation with HAS_ONE sets the foreign table type accordingly'); - - $this->assertEquals($this->rmap2->getForeignTable(), $this->tmap, 'adding a relation with HAS_MANY sets the foreign table to the current table'); - $this->assertEquals($this->rmap2->getLocalTable(), $foreigntmap2, 'adding a relation with HAS_MANY sets the local table according to the name given'); - $this->assertEquals(RelationMap::ONE_TO_MANY, $this->rmap2->getType(), 'adding a relation with HAS_MANY sets the foreign table type accordingly'); - - $expectedRelations = array('Bar' => $this->rmap1, 'Bazz' => $this->rmap2); - $this->assertEquals($expectedRelations, $this->tmap->getRelations(), 'getRelations() returns an associative array of all the relations'); - } - - // deprecated method - public function testNormalizeColName() - { - $tmap = new TestableTableMap(); - $this->assertEquals('', $tmap->normalizeColName(''), 'normalizeColName returns an empty string when passed an empty string'); - $this->assertEquals('BAR', $tmap->normalizeColName('bar'), 'normalizeColName uppercases the input'); - $this->assertEquals('BAR_BAZ', $tmap->normalizeColName('bar_baz'), 'normalizeColName does not mind underscores'); - $this->assertEquals('BAR', $tmap->normalizeColName('FOO.BAR'), 'normalizeColName removes table prefix'); - $this->assertEquals('BAR', $tmap->normalizeColName('BAR'), 'normalizeColName leaves normalized column names unchanged'); - $this->assertEquals('BAR_BAZ', $tmap->normalizeColName('foo.bar_baz'), 'normalizeColName can do all the above at the same time'); - } - - // deprecated method - public function testContainsColumn() - { - $this->assertFalse($this->tmap->containsColumn('BAR'), 'containsColumn returns false when the column is not in the table map'); - $column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER'); - $this->assertTrue($this->tmap->containsColumn('BAR'), 'containsColumn returns true when the column is in the table map'); - $this->assertTrue($this->tmap->containsColumn('foo.bar'), 'containsColumn accepts a denormalized column name'); - $this->assertFalse($this->tmap->containsColumn('foo.bar', false), 'containsColumn accepts a $normalize parameter to skip name normalization'); - $this->assertTrue($this->tmap->containsColumn('BAR', false), 'containsColumn accepts a $normalize parameter to skip name normalization'); - $this->assertTrue($this->tmap->containsColumn($column), 'containsColumn accepts a ColumnMap object as parameter'); - } - - // deprecated methods - public function testPrefix() - { - $tmap = new TestableTableMap(); - $this->assertNull($tmap->getPrefix(), 'prefix is empty until set'); - $this->assertFalse($tmap->hasPrefix('barbaz'), 'hasPrefix returns false when prefix is not set'); - $tmap->setPrefix('bar'); - $this->assertEquals('bar', $tmap->getPrefix(), 'prefix is set by setPrefix()'); - $this->assertTrue($tmap->hasPrefix('barbaz'), 'hasPrefix returns true when prefix is set and found in string'); - $this->assertFalse($tmap->hasPrefix('baz'), 'hasPrefix returns false when prefix is set and not found in string'); - $this->assertFalse($tmap->hasPrefix('bazbar'), 'hasPrefix returns false when prefix is set and not found anywhere in string'); - $this->assertEquals('baz', $tmap->removePrefix('barbaz'), 'removePrefix returns string without prefix if found at the beginning'); - $this->assertEquals('bazbaz', $tmap->removePrefix('bazbaz'), 'removePrefix returns original string when prefix is not found'); - $this->assertEquals('bazbar', $tmap->removePrefix('bazbar'), 'removePrefix returns original string when prefix is not found at the beginning'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectSerializeTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectSerializeTest.php deleted file mode 100644 index 16a6fb836..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectSerializeTest.php +++ /dev/null @@ -1,95 +0,0 @@ -assertEquals($book, unserialize($sb)); - } - - public function testSerializePopulatedObject() - { - $book = new Book(); - $book->setTitle('Foo1'); - $book->setISBN('1234'); - $sb = serialize($book); - $this->assertEquals($book, unserialize($sb)); - } - - public function testSerializePersistedObject() - { - $book = new Book(); - $book->setTitle('Foo2'); - $book->setISBN('1234'); - $book->save(); - $sb = serialize($book); - $this->assertEquals($book, unserialize($sb)); - } - - public function testSerializeHydratedObject() - { - $book = new Book(); - $book->setTitle('Foo3'); - $book->setISBN('1234'); - $book->save(); - BookPeer::clearInstancePool(); - - $book = BookQuery::create()->findOneByTitle('Foo3'); - $sb = serialize($book); - $this->assertEquals($book, unserialize($sb)); - } - - public function testSerializeObjectWithRelations() - { - $author = new Author(); - $author->setFirstName('John'); - $book = new Book(); - $book->setTitle('Foo4'); - $book->setISBN('1234'); - $book->setAuthor($author); - $book->save(); - $b = clone $book; - $sb = serialize($b); - $book->clearAllReferences(); - $this->assertEquals($book, unserialize($sb)); - } - - public function testSerializeObjectWithCollections() - { - $book1 = new Book(); - $book1->setTitle('Foo5'); - $book1->setISBN('1234'); - $book2 = new Book(); - $book2->setTitle('Foo6'); - $book2->setISBN('1234'); - $author = new Author(); - $author->setFirstName('JAne'); - $author->addBook($book1); - $author->addBook($book2); - $author->save(); - $a = clone $author; - $sa = serialize($a); - $author->clearAllReferences(); - $this->assertEquals($author, unserialize($sa)); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectTest.php deleted file mode 100644 index dd3f4ebe2..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/om/BaseObjectTest.php +++ /dev/null @@ -1,69 +0,0 @@ -assertEquals(array(), $b->getVirtualColumns(), 'getVirtualColumns() returns an empty array for new objects'); - $b->virtualColumns = array('foo' => 'bar'); - $this->assertEquals(array('foo' => 'bar'), $b->getVirtualColumns(), 'getVirtualColumns() returns an associative array of virtual columns'); - } - - public function testHasVirtualColumn() - { - $b = new TestableBaseObject(); - $this->assertFalse($b->hasVirtualColumn('foo'), 'hasVirtualColumn() returns false if the virtual column is not set'); - $b->virtualColumns = array('foo' => 'bar'); - $this->assertTrue($b->hasVirtualColumn('foo'), 'hasVirtualColumn() returns true if the virtual column is set'); - } - - /** - * @expectedException PropelException - */ - public function testGetVirtualColumnWrongKey() - { - $b = new TestableBaseObject(); - $b->getVirtualColumn('foo'); - } - - public function testGetVirtualColumn() - { - $b = new TestableBaseObject(); - $b->virtualColumns = array('foo' => 'bar'); - $this->assertEquals('bar', $b->getVirtualColumn('foo'), 'getVirtualColumn() returns a virtual column value based on its key'); - } - - public function testSetVirtualColumn() - { - $b = new TestableBaseObject(); - $b->setVirtualColumn('foo', 'bar'); - $this->assertEquals('bar', $b->getVirtualColumn('foo'), 'setVirtualColumn() sets a virtual column value based on its key'); - $b->setVirtualColumn('foo', 'baz'); - $this->assertEquals('baz', $b->getVirtualColumn('foo'), 'setVirtualColumn() can modify the value of an existing virtual column'); - $this->assertEquals($b, $b->setVirtualColumn('foo', 'bar'), 'setVirtualColumn() returns the current object'); - } -} - -class TestableBaseObject extends BaseObject -{ - public $virtualColumns = array(); -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaCombineTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaCombineTest.php deleted file mode 100644 index d5cec12ea..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaCombineTest.php +++ /dev/null @@ -1,385 +0,0 @@ -c = new Criteria(); - $this->savedAdapter = Propel::getDB(null); - Propel::setDB(null, new DBSQLite()); - } - - protected function tearDown() - { - Propel::setDB(null, $this->savedAdapter); - parent::tearDown(); - } - - /** - * test various properties of Criterion and nested criterion - */ - public function testNestedCriterion() - { - $table2 = "myTable2"; - $column2 = "myColumn2"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $table3 = "myTable3"; - $column3 = "myColumn3"; - $value3 = "myValue3"; - $key3 = "$table3.$column3"; - - $table4 = "myTable4"; - $column4 = "myColumn4"; - $value4 = "myValue4"; - $key4 = "$table4.$column4"; - - $table5 = "myTable5"; - $column5 = "myColumn5"; - $value5 = "myValue5"; - $key5 = "$table5.$column5"; - - $crit2 = $this->c->getNewCriterion($key2, $value2, Criteria::EQUAL); - $crit3 = $this->c->getNewCriterion($key3, $value3, Criteria::EQUAL); - $crit4 = $this->c->getNewCriterion($key4, $value4, Criteria::EQUAL); - $crit5 = $this->c->getNewCriterion($key5, $value5, Criteria::EQUAL); - - $crit2->addAnd($crit3)->addOr($crit4->addAnd($crit5)); - $expect = "((myTable2.myColumn2=:p1 AND myTable3.myColumn3=:p2) " - . "OR (myTable4.myColumn4=:p3 AND myTable5.myColumn5=:p4))"; - - $sb = ""; - $params = array(); - $crit2->appendPsTo($sb, $params); - - $expect_params = array( - array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'), - array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'), - array('table' => 'myTable4', 'column' => 'myColumn4', 'value' => 'myValue4'), - array('table' => 'myTable5', 'column' => 'myColumn5', 'value' => 'myValue5'), - ); - - $this->assertEquals($expect, $sb); - $this->assertEquals($expect_params, $params); - - $crit6 = $this->c->getNewCriterion($key2, $value2, Criteria::EQUAL); - $crit7 = $this->c->getNewCriterion($key3, $value3, Criteria::EQUAL); - $crit8 = $this->c->getNewCriterion($key4, $value4, Criteria::EQUAL); - $crit9 = $this->c->getNewCriterion($key5, $value5, Criteria::EQUAL); - - $crit6->addAnd($crit7)->addOr($crit8)->addAnd($crit9); - $expect = "(((myTable2.myColumn2=:p1 AND myTable3.myColumn3=:p2) " - . "OR myTable4.myColumn4=:p3) AND myTable5.myColumn5=:p4)"; - - $sb = ""; - $params = array(); - $crit6->appendPsTo($sb, $params); - - $expect_params = array( - array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'), - array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'), - array('table' => 'myTable4', 'column' => 'myColumn4', 'value' => 'myValue4'), - array('table' => 'myTable5', 'column' => 'myColumn5', 'value' => 'myValue5'), - ); - - $this->assertEquals($expect, $sb); - $this->assertEquals($expect_params, $params); - - // should make sure we have tests for all possibilities - - $crita = $crit2->getAttachedCriterion(); - - $this->assertEquals($crit2, $crita[0]); - $this->assertEquals($crit3, $crita[1]); - $this->assertEquals($crit4, $crita[2]); - $this->assertEquals($crit5, $crita[3]); - - $tables = $crit2->getAllTables(); - - $this->assertEquals($crit2->getTable(), $tables[0]); - $this->assertEquals($crit3->getTable(), $tables[1]); - $this->assertEquals($crit4->getTable(), $tables[2]); - $this->assertEquals($crit5->getTable(), $tables[3]); - - // simple confirmations that equality operations work - $this->assertTrue($crit2->hashCode() === $crit2->hashCode()); - } - - /** - * Tests <= and >=. - */ - public function testBetweenCriterion() - { - $cn1 = $this->c->getNewCriterion("INVOICE.COST", 1000, Criteria::GREATER_EQUAL); - $cn2 = $this->c->getNewCriterion("INVOICE.COST", 5000, Criteria::LESS_EQUAL); - $this->c->add($cn1->addAnd($cn2)); - - $expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 AND INVOICE.COST<=:p2)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST', 'value' => 1000), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => 5000), - ); - - try { - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - } catch (PropelException $e) { - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ".$e->getMessage()); - } - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - /** - * Verify that AND and OR criterion are nested correctly. - */ - public function testPrecedence() - { - $cn1 = $this->c->getNewCriterion("INVOICE.COST", "1000", Criteria::GREATER_EQUAL); - $cn2 = $this->c->getNewCriterion("INVOICE.COST", "2000", Criteria::LESS_EQUAL); - $cn3 = $this->c->getNewCriterion("INVOICE.COST", "8000", Criteria::GREATER_EQUAL); - $cn4 = $this->c->getNewCriterion("INVOICE.COST", "9000", Criteria::LESS_EQUAL); - $this->c->add($cn1->addAnd($cn2)); - $this->c->addOr($cn3->addAnd($cn4)); - - $expect = - "SELECT FROM INVOICE WHERE ((INVOICE.COST>=:p1 AND INVOICE.COST<=:p2) OR (INVOICE.COST>=:p3 AND INVOICE.COST<=:p4))"; - - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '9000'), - ); - - try { - $params=array(); - $result = BasePeer::createSelectSql($this->c, $params); - } catch (PropelException $e) { - $this->fail("PropelException thrown in BasePeer::createSelectSql()"); - } - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionAndSimple() - { - $this->c->addCond('cond1', "INVOICE.COST", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST", "2000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND); - - $expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 AND INVOICE.COST<=:p2)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionAndLessSimple() - { - $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->add("INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND); - $this->c->add("INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - - $expect = "SELECT FROM INVOICE WHERE INVOICE.COST3>=:p1 AND (INVOICE.COST1>=:p2 AND INVOICE.COST2<=:p3) AND INVOICE.COST4<=:p4"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionAndMultiple() - { - $this->c->addCond('cond1',"INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2', 'cond3', 'cond4'), Criteria::LOGICAL_AND); - - $expect = "SELECT FROM INVOICE WHERE (((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) AND INVOICE.COST3>=:p3) AND INVOICE.COST4<=:p4)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionOrSimple() - { - $this->c->addCond('cond1', "INVOICE.COST", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST", "2000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - - $expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 OR INVOICE.COST<=:p2)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionOrLessSimple() - { - $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->add("INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - $this->c->addOr("INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - - $expect = "SELECT FROM INVOICE WHERE INVOICE.COST3>=:p1 AND ((INVOICE.COST1>=:p2 OR INVOICE.COST2<=:p3) OR INVOICE.COST4<=:p4)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineCriterionOrMultiple() - { - $this->c->addCond('cond1',"INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2', 'cond3', 'cond4'), Criteria::LOGICAL_OR); - - $expect = "SELECT FROM INVOICE WHERE (((INVOICE.COST1>=:p1 OR INVOICE.COST2<=:p2) OR INVOICE.COST3>=:p3) OR INVOICE.COST4<=:p4)"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineNamedCriterions() - { - $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND, 'cond12'); - $this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond3', 'cond4'), Criteria::LOGICAL_AND, 'cond34'); - $this->c->combine(array('cond12', 'cond34'), Criteria::LOGICAL_OR); - - $expect = "SELECT FROM INVOICE WHERE ((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) OR (INVOICE.COST3>=:p3 AND INVOICE.COST4<=:p4))"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - - public function testCombineDirtyOperators() - { - $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond1', 'cond2'), 'AnD', 'cond12'); - $this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); - $this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL); - $this->c->combine(array('cond3', 'cond4'), 'aNd', 'cond34'); - $this->c->combine(array('cond12', 'cond34'), 'oR'); - - $expect = "SELECT FROM INVOICE WHERE ((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) OR (INVOICE.COST3>=:p3 AND INVOICE.COST4<=:p4))"; - $expect_params = array( - array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), - array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), - array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), - array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'), - ); - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $this->assertEquals($expect, $result); - $this->assertEquals($expect_params, $params); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaFluidConditionTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaFluidConditionTest.php deleted file mode 100644 index a2f0d2bbc..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaFluidConditionTest.php +++ /dev/null @@ -1,181 +0,0 @@ - - _if(true)-> - test()-> - _endif(); - $this->assertTrue($f->getTest(), '_if() executes the next method if the test is true'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - foo()-> - _endif(); - $this->assertFalse($f->getTest(), '_if() does not check the existence of the next method if the test is false'); - $f = new TestableCriteria(); - $f-> - _if(true)-> - dummy()-> - test()-> - _endif(); - $this->assertTrue($f->getTest(), '_if() executes the next methods until _endif() if the test is true'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - dummy()-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_if() does not execute the next methods until _endif() if the test is false'); - } - - /** - * @expectedException PropelException - */ - public function testNestedIf() - { - $f = new TestableCriteria(); - $f-> - _if(false)-> - _if(true)-> - test()-> - _endif(); - } - - public function testElseIf() - { - $f = new TestableCriteria(); - $f-> - _if(true)-> - _elseif(true)-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is true'); - $f = new TestableCriteria(); - $f-> - _if(true)-> - _elseif(false)-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is true'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - _elseif(true)-> - test()-> - _endif(); - $this->assertTrue($f->getTest(), '_elseif() executes the next method if the main test is false and the elseif test is true'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - _elseif(false)-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is false and the elseif test is false'); - } - - public function testElse() - { - $f = new TestableCriteria(); - $f-> - _if(true)-> - _else()-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_else() does not execute the next method if the main test is true'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - _else()-> - test()-> - _endif(); - $this->assertTrue($f->getTest(), '_else() executes the next method if the main test is false'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - _elseif(true)-> - _else()-> - test()-> - _endif(); - $this->assertFalse($f->getTest(), '_else() does not execute the next method if the previous test is true'); - $f-> - _if(false)-> - _elseif(false)-> - _else()-> - test()-> - _endif(); - $this->assertTrue($f->getTest(), '_else() executes the next method if all the previous tests are false'); - } - - public function testEndif() - { - $f = new TestableCriteria(); - $res = $f-> - _if(true)-> - test()-> - _endif(); - $this->assertEquals($res, $f, '_endif() returns the main object if the test is true'); - $f = new TestableCriteria(); - $res = $f-> - _if(false)-> - test()-> - _endif(); - $this->assertEquals($res, $f, '_endif() returns the main object if the test is false'); - $f = new TestableCriteria(); - $f-> - _if(true)-> - _endif()-> - test(); - $this->assertTrue($f->getTest(), '_endif() stops the condition check'); - $f = new TestableCriteria(); - $f-> - _if(false)-> - _endif()-> - test(); - $this->assertTrue($f->getTest(), '_endif() stops the condition check'); - } -} - -class TestableCriteria extends Criteria -{ - protected $test = false; - - public function test() - { - $this->test = true; - - return $this; - } - - public function dummy() - { - return $this; - } - - public function getTest() - { - return $this->test; - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaMergeTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaMergeTest.php deleted file mode 100644 index e28d8a30b..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaMergeTest.php +++ /dev/null @@ -1,399 +0,0 @@ -Christopher Elkins - * @author Sam Joseph - * @version $Id: CriteriaTest.php 1347 2009-12-03 21:06:36Z francois $ - * @package runtime.query - */ -class CriteriaMergeTest extends BaseTestCase -{ - - protected function assertCriteriaTranslation($criteria, $expectedSql, $message = '') - { - $params = array(); - $result = BasePeer::createSelectSql($criteria, $params); - $this->assertEquals($expectedSql, $result, $message); - } - - public function testMergeWithLimit() - { - $c1 = new Criteria(); - $c1->setLimit(123); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(123, $c1->getLimit(), 'mergeWith() does not remove an existing limit'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->setLimit(123); - $c1->mergeWith($c2); - $this->assertEquals(123, $c1->getLimit(), 'mergeWith() merges the limit'); - $c1 = new Criteria(); - $c1->setLimit(456); - $c2 = new Criteria(); - $c2->setLimit(123); - $c1->mergeWith($c2); - $this->assertEquals(456, $c1->getLimit(), 'mergeWith() does not merge the limit in case of conflict'); - } - - public function testMergeWithOffset() - { - $c1 = new Criteria(); - $c1->setOffset(123); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(123, $c1->getOffset(), 'mergeWith() does not remove an existing offset'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->setOffset(123); - $c1->mergeWith($c2); - $this->assertEquals(123, $c1->getOffset(), 'mergeWith() merges the offset'); - $c1 = new Criteria(); - $c1->setOffset(456); - $c2 = new Criteria(); - $c2->setOffset(123); - $c1->mergeWith($c2); - $this->assertEquals(456, $c1->getOffset(), 'mergeWith() does not merge the offset in case of conflict'); - } - - public function testMergeWithSelectModifiers() - { - $c1 = new Criteria(); - $c1->setDistinct(); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() does not remove an existing select modifier'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->setDistinct(); - $c1->mergeWith($c2); - $this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() merges the select modifiers'); - $c1 = new Criteria(); - $c1->setDistinct(); - $c2 = new Criteria(); - $c2->setDistinct(); - $c1->mergeWith($c2); - $this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() does not duplicate select modifiers'); - $c1 = new Criteria(); - $c1->setAll(); - $c2 = new Criteria(); - $c2->setDistinct(); - $c1->mergeWith($c2); - $this->assertEquals(array(Criteria::ALL), $c1->getSelectModifiers(), 'mergeWith() does not merge the select modifiers in case of conflict'); - } - - public function testMergeWithSelectColumns() - { - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::TITLE); - $c1->addSelectColumn(BookPeer::ID); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() does not remove an existing select columns'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addSelectColumn(BookPeer::TITLE); - $c2->addSelectColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() merges the select columns to an empty select'); - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addSelectColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() merges the select columns after the existing select columns'); - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addSelectColumn(BookPeer::TITLE); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::TITLE), $c1->getSelectColumns(), 'mergeWith() merges the select columns to an existing select, even if duplicated'); - } - - public function testMergeWithAsColumns() - { - $c1 = new Criteria(); - $c1->addAsColumn('foo', BookPeer::TITLE); - $c1->addAsColumn('bar', BookPeer::ID); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() does not remove an existing as columns'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addAsColumn('foo', BookPeer::TITLE); - $c2->addAsColumn('bar', BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() merges the select columns to an empty as'); - $c1 = new Criteria(); - $c1->addAsColumn('foo', BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addAsColumn('bar', BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() merges the select columns after the existing as columns'); - } - - /** - * @expectedException PropelException - */ - public function testMergeWithAsColumnsThrowsException() - { - $c1 = new Criteria(); - $c1->addAsColumn('foo', BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addAsColumn('foo', BookPeer::ID); - $c1->mergeWith($c2); - } - - public function testMergeWithOrderByColumns() - { - $c1 = new Criteria(); - $c1->addAscendingOrderByColumn(BookPeer::TITLE); - $c1->addAscendingOrderByColumn(BookPeer::ID); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() does not remove an existing orderby columns'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addAscendingOrderByColumn(BookPeer::TITLE); - $c2->addAscendingOrderByColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() merges the select columns to an empty order by'); - $c1 = new Criteria(); - $c1->addAscendingOrderByColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addAscendingOrderByColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() merges the select columns after the existing orderby columns'); - $c1 = new Criteria(); - $c1->addAscendingOrderByColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addAscendingOrderByColumn(BookPeer::TITLE); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() does not merge duplicated orderby columns'); - $c1 = new Criteria(); - $c1->addAscendingOrderByColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addDescendingOrderByColumn(BookPeer::TITLE); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::TITLE . ' DESC'), $c1->getOrderByColumns(), 'mergeWith() merges duplicated orderby columns with inverse direction'); - } - - public function testMergeWithGroupByColumns() - { - $c1 = new Criteria(); - $c1->addGroupByColumn(BookPeer::TITLE); - $c1->addGroupByColumn(BookPeer::ID); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() does not remove an existing groupby columns'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addGroupByColumn(BookPeer::TITLE); - $c2->addGroupByColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() merges the select columns to an empty groupby'); - $c1 = new Criteria(); - $c1->addGroupByColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addGroupByColumn(BookPeer::ID); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() merges the select columns after the existing groupby columns'); - $c1 = new Criteria(); - $c1->addGroupByColumn(BookPeer::TITLE); - $c2 = new Criteria(); - $c2->addGroupByColumn(BookPeer::TITLE); - $c1->mergeWith($c2); - $this->assertEquals(array(BookPeer::TITLE), $c1->getGroupByColumns(), 'mergeWith() does not merge duplicated groupby columns'); - } - - public function testMergeWithWhereConditions() - { - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing where condition'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'foo'); - $c1->mergeWith($c2); - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to an empty condition'); - $c1 = new Criteria(); - $c1->add(BookPeer::ID, 123); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'foo'); - $c1->mergeWith($c2); - $sql = 'SELECT FROM `book` WHERE book.ID=:p1 AND book.TITLE=:p2'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions'); - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'bar'); - $c1->mergeWith($c2); - $sql = 'SELECT FROM `book` WHERE (book.TITLE=:p1 AND book.TITLE=:p2)'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the same column'); - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); - $c2 = new Criteria(); - $c2->add(AuthorPeer::FIRST_NAME, 'bar'); - $c1->mergeWith($c2); - $sql = 'SELECT FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE book.TITLE=:p1 AND author.FIRST_NAME=:p2'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the different tables'); - } - - public function testMergeOrWithWhereConditions() - { - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c2 = new Criteria(); - $c1->mergeWith($c2, Criteria::LOGICAL_OR); - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing where condition'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'foo'); - $c1->mergeWith($c2, Criteria::LOGICAL_OR); - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to an empty condition'); - $c1 = new Criteria(); - $c1->add(BookPeer::ID, 123); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'foo'); - $c1->mergeWith($c2, Criteria::LOGICAL_OR); - $sql = 'SELECT FROM `book` WHERE (book.ID=:p1 OR book.TITLE=:p2)'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions'); - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'bar'); - $c1->mergeWith($c2, Criteria::LOGICAL_OR); - $sql = 'SELECT FROM `book` WHERE (book.TITLE=:p1 OR book.TITLE=:p2)'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the same column'); - $c1 = new Criteria(); - $c1->add(BookPeer::TITLE, 'foo'); - $c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); - $c2 = new Criteria(); - $c2->add(AuthorPeer::FIRST_NAME, 'bar'); - $c1->mergeWith($c2, Criteria::LOGICAL_OR); - $sql = 'SELECT FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE (book.TITLE=:p1 OR author.FIRST_NAME=:p2)'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the different tables'); - } - - public function testMergeWithHavingConditions() - { - $c1 = new Criteria(); - $cton = $c1->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL); - $c1->addHaving($cton); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $sql = 'SELECT FROM HAVING book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing having condition'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $cton = $c2->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL); - $c2->addHaving($cton); - $c1->mergeWith($c2); - $sql = 'SELECT FROM HAVING book.TITLE=:p1'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges having condition to an empty having'); - $c1 = new Criteria(); - $cton = $c1->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL); - $c1->addHaving($cton); - $c2 = new Criteria(); - $cton = $c2->getNewCriterion(BookPeer::TITLE, 'bar', Criteria::EQUAL); - $c2->addHaving($cton); - $c1->mergeWith($c2); - $sql = 'SELECT FROM HAVING (book.TITLE=:p1 AND book.TITLE=:p2)'; - $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() combines having with AND'); - } - - public function testMergeWithAliases() - { - $c1 = new Criteria(); - $c1->addAlias('b', BookPeer::TABLE_NAME); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $this->assertEquals(array('b' => BookPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() does not remove an existing alias'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addAlias('a', AuthorPeer::TABLE_NAME); - $c1->mergeWith($c2); - $this->assertEquals(array('a' => AuthorPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() merge aliases to an empty alias'); - $c1 = new Criteria(); - $c1->addAlias('b', BookPeer::TABLE_NAME); - $c2 = new Criteria(); - $c2->addAlias('a', AuthorPeer::TABLE_NAME); - $c1->mergeWith($c2); - $this->assertEquals(array('b' => BookPeer::TABLE_NAME, 'a' => AuthorPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() merge aliases to an existing alias'); - } - - /** - * @expectedException PropelException - */ - public function testMergeWithAliasesThrowsException() - { - $c1 = new Criteria(); - $c1->addAlias('b', BookPeer::TABLE_NAME); - $c2 = new Criteria(); - $c2->addAlias('b', AuthorPeer::TABLE_NAME); - $c1->mergeWith($c2); - } - - public function testMergeWithJoins() - { - $c1 = new Criteria(); - $c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); - $c2 = new Criteria(); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(1, count($joins), 'mergeWith() does not remove an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() does not remove an existing join'); - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(1, count($joins), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() merge joins to an empty join'); - $c1 = new Criteria(); - $c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); - $c2 = new Criteria(); - $c2->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(2, count($joins), 'mergeWith() merge joins to an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('INNER JOIN : book.PUBLISHER_ID=publisher.ID(ignoreCase not considered)', $joins[1]->toString(), 'mergeWith() merge joins to an empty join'); - } - - public function testMergeWithFurtherModified() - { - $c1 = new Criteria(); - $c2 = new Criteria(); - $c2->setLimit(123); - $c1->mergeWith($c2); - $this->assertEquals(123, $c1->getLimit(), 'mergeWith() makes the merge'); - $c2->setLimit(456); - $this->assertEquals(123, $c1->getLimit(), 'further modifying a merged criteria does not affect the merger'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaTest.php deleted file mode 100644 index c05b9b0e8..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/CriteriaTest.php +++ /dev/null @@ -1,974 +0,0 @@ -Christopher Elkins - * @author Sam Joseph - * @version $Id: CriteriaTest.php 1773 2010-05-25 10:25:06Z francois $ - * @package runtime.query - */ -class CriteriaTest extends BaseTestCase -{ - - /** - * The criteria to use in the test. - * @var Criteria - */ - private $c; - - /** - * DB adapter saved for later. - * - * @var DBAdapter - */ - private $savedAdapter; - - protected function setUp() - { - parent::setUp(); - $this->c = new Criteria(); - $this->savedAdapter = Propel::getDB(null); - Propel::setDB(null, new DBSQLite()); - } - - protected function tearDown() - { - Propel::setDB(null, $this->savedAdapter); - parent::tearDown(); - } - - /** - * Test basic adding of strings. - */ - public function testAddString() - { - $table = "myTable"; - $column = "myColumn"; - $value = "myValue"; - - // Add the string - $this->c->add($table . '.' . $column, $value); - - // Verify that the key exists - $this->assertTrue($this->c->containsKey($table . '.' . $column)); - - // Verify that what we get out is what we put in - $this->assertTrue($this->c->getValue($table . '.' . $column) === $value); - } - - public function testAddAndSameColumns() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable1"; - $column2 = "myColumn1"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->addAnd($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1 WHERE (myTable1.myColumn1=:p1 AND myTable1.myColumn1=:p2)"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'), - ); - - $this->assertEquals($expect, $result, 'addAnd() called on an existing column creates a combined criterion'); - $this->assertEquals($expect_params, $params, 'addAnd() called on an existing column creates a combined criterion'); - } - - public function testAddAndSameColumnsPropel14Compatibility() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable1"; - $column2 = "myColumn1"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $table3 = "myTable3"; - $column3 = "myColumn3"; - $value3 = "myValue3"; - $key3 = "$table3.$column3"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->add($key3, $value3, Criteria::EQUAL); - $this->c->addAnd($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1, myTable3 WHERE (myTable1.myColumn1=:p1 AND myTable1.myColumn1=:p2) AND myTable3.myColumn3=:p3"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'), - array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'), - ); - - $this->assertEquals($expect, $result, 'addAnd() called on an existing column creates a combined criterion'); - $this->assertEquals($expect_params, $params, 'addAnd() called on an existing column creates a combined criterion'); - } - - public function testAddAndDistinctColumns() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable2"; - $column2 = "myColumn2"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->addAnd($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1, myTable2 WHERE myTable1.myColumn1=:p1 AND myTable2.myColumn2=:p2"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'), - ); - - $this->assertEquals($expect, $result, 'addAnd() called on a distinct column adds a criterion to the criteria'); - $this->assertEquals($expect_params, $params, 'addAnd() called on a distinct column adds a criterion to the criteria'); - } - - public function testAddOrSameColumns() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable1"; - $column2 = "myColumn1"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->addOr($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1 WHERE (myTable1.myColumn1=:p1 OR myTable1.myColumn1=:p2)"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'), - ); - - $this->assertEquals($expect, $result, 'addOr() called on an existing column creates a combined criterion'); - $this->assertEquals($expect_params, $params, 'addOr() called on an existing column creates a combined criterion'); - } - - public function testAddAndOrColumnsPropel14Compatibility() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable1"; - $column2 = "myColumn1"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $table3 = "myTable3"; - $column3 = "myColumn3"; - $value3 = "myValue3"; - $key3 = "$table3.$column3"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->add($key3, $value3, Criteria::EQUAL); - $this->c->addOr($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1, myTable3 WHERE (myTable1.myColumn1=:p1 OR myTable1.myColumn1=:p2) AND myTable3.myColumn3=:p3"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'), - array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'), - ); - - $this->assertEquals($expect, $result, 'addOr() called on an existing column creates a combined criterion'); - $this->assertEquals($expect_params, $params, 'addOr() called on an existing column creates a combined criterion'); - } - - public function testAddOrDistinctColumns() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $table2 = "myTable2"; - $column2 = "myColumn2"; - $value2 = "myValue2"; - $key2 = "$table2.$column2"; - - $this->c->add($key1, $value1, Criteria::EQUAL); - $this->c->addOr($key2, $value2, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1, myTable2 WHERE (myTable1.myColumn1=:p1 OR myTable2.myColumn2=:p2)"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'), - ); - - $this->assertEquals($expect, $result, 'addOr() called on a distinct column adds a criterion to the latest criterion'); - $this->assertEquals($expect_params, $params, 'addOr() called on a distinct column adds a criterion to the latest criterion'); - } - - public function testAddOrEmptyCriteria() - { - $table1 = "myTable1"; - $column1 = "myColumn1"; - $value1 = "myValue1"; - $key1 = "$table1.$column1"; - - $this->c->addOr($key1, $value1, Criteria::EQUAL); - - $expect = "SELECT FROM myTable1 WHERE myTable1.myColumn1=:p1"; - - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - - $expect_params = array( - array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'), - ); - - $this->assertEquals($expect, $result, 'addOr() called on an empty Criteria adds a criterion to the criteria'); - $this->assertEquals($expect_params, $params, 'addOr() called on an empty Criteria adds a criterion to the criteria'); - } - - /** - * Test Criterion.setIgnoreCase(). - * As the output is db specific the test just prints the result to - * System.out - */ - public function testCriterionIgnoreCase() - { - $originalDB = Propel::getDB(); - $adapters = array(new DBMySQL(), new DBPostgres()); - $expectedIgnore = array("UPPER(TABLE.COLUMN) LIKE UPPER(:p1)", "TABLE.COLUMN ILIKE :p1"); - - $i =0; - foreach ($adapters as $adapter) { - - Propel::setDB(null, $adapter); - $myCriteria = new Criteria(); - - $myCriterion = $myCriteria->getNewCriterion( - "TABLE.COLUMN", "FoObAr", Criteria::LIKE); - $sb = ""; - $params=array(); - $myCriterion->appendPsTo($sb, $params); - $expected = "TABLE.COLUMN LIKE :p1"; - - $this->assertEquals($expected, $sb); - - $ignoreCriterion = $myCriterion->setIgnoreCase(true); - - $sb = ""; - $params=array(); - $ignoreCriterion->appendPsTo($sb, $params); - // $expected = "UPPER(TABLE.COLUMN) LIKE UPPER(?)"; - $this->assertEquals($expectedIgnore[$i], $sb); - $i++; - } - Propel::setDB(null, $originalDB); - } - - public function testOrderByIgnoreCase() - { - $originalDB = Propel::getDB(); - Propel::setDB(null, new DBMySQL()); - - $criteria = new Criteria(); - $criteria->setIgnoreCase(true); - $criteria->addAscendingOrderByColumn(BookPeer::TITLE); - BookPeer::addSelectColumns($criteria); - $params=array(); - $sql = BasePeer::createSelectSql($criteria, $params); - $expectedSQL = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, UPPER(book.TITLE) FROM `book` ORDER BY UPPER(book.TITLE) ASC'; - $this->assertEquals($expectedSQL, $sql); - - Propel::setDB(null, $originalDB); - } - - /** - * Test that true is evaluated correctly. - */ - public function testBoolean() - { - $this->c = new Criteria(); - $this->c->add("TABLE.COLUMN", true); - - $expect = "SELECT FROM TABLE WHERE TABLE.COLUMN=:p1"; - $expect_params = array( array('table' => 'TABLE', 'column' => 'COLUMN', 'value' => true), - ); - try { - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - } catch (PropelException $e) { - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - - $this->assertEquals($expect, $result, "Boolean test failed."); - $this->assertEquals($expect_params, $params); - - } - - public function testCurrentDate() - { - $this->c = new Criteria(); - $this->c->add("TABLE.TIME_COLUMN", Criteria::CURRENT_TIME); - $this->c->add("TABLE.DATE_COLUMN", Criteria::CURRENT_DATE); - - $expect = "SELECT FROM TABLE WHERE TABLE.TIME_COLUMN=CURRENT_TIME AND TABLE.DATE_COLUMN=CURRENT_DATE"; - - $result = null; - try { - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - - $this->assertEquals($expect, $result, "Current date test failed!"); - - } - - public function testCountAster() - { - $this->c = new Criteria(); - $this->c->addSelectColumn("COUNT(*)"); - $this->c->add("TABLE.TIME_COLUMN", Criteria::CURRENT_TIME); - $this->c->add("TABLE.DATE_COLUMN", Criteria::CURRENT_DATE); - - $expect = "SELECT COUNT(*) FROM TABLE WHERE TABLE.TIME_COLUMN=CURRENT_TIME AND TABLE.DATE_COLUMN=CURRENT_DATE"; - - $result = null; - try { - $params = array(); - $result = BasePeer::createSelectSql($this->c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - - $this->assertEquals($expect, $result); - - } - - public function testIn() - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->add("TABLE.SOME_COLUMN", array(), Criteria::IN); - $c->add("TABLE.OTHER_COLUMN", array(1, 2, 3), Criteria::IN); - - $expect = "SELECT * FROM TABLE WHERE 1<>1 AND TABLE.OTHER_COLUMN IN (:p1,:p2,:p3)"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testInEmptyAfterFull() - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->add("TABLE.OTHER_COLUMN", array(1, 2, 3), Criteria::IN); - $c->add("TABLE.SOME_COLUMN", array(), Criteria::IN); - - $expect = "SELECT * FROM TABLE WHERE TABLE.OTHER_COLUMN IN (:p1,:p2,:p3) AND 1<>1"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testInNested() - { - // now do a nested logic test, just for sanity (not that this should be any surprise) - - $c = new Criteria(); - $c->addSelectColumn("*"); - $myCriterion = $c->getNewCriterion("TABLE.COLUMN", array(), Criteria::IN); - $myCriterion->addOr($c->getNewCriterion("TABLE.COLUMN2", array(1,2), Criteria::IN)); - $c->add($myCriterion); - - $expect = "SELECT * FROM TABLE WHERE (1<>1 OR TABLE.COLUMN2 IN (:p1,:p2))"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - - } - - public function testJoinObject () - { - $j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_2'); - $this->assertEquals(null, $j->getJoinType()); - $this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn()); - $this->assertEquals('TABLE_A', $j->getLeftTableName()); - $this->assertEquals('COL_1', $j->getLeftColumnName()); - $this->assertEquals('TABLE_B.COL_2', $j->getRightColumn()); - $this->assertEquals('TABLE_B', $j->getRightTableName()); - $this->assertEquals('COL_2', $j->getRightColumnName()); - - $j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::LEFT_JOIN); - $this->assertEquals('LEFT JOIN', $j->getJoinType()); - $this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn()); - $this->assertEquals('TABLE_B.COL_1', $j->getRightColumn()); - - $j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::RIGHT_JOIN); - $this->assertEquals('RIGHT JOIN', $j->getJoinType()); - $this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn()); - $this->assertEquals('TABLE_B.COL_1', $j->getRightColumn()); - - $j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN); - $this->assertEquals('INNER JOIN', $j->getJoinType()); - $this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn()); - $this->assertEquals('TABLE_B.COL_1', $j->getRightColumn()); - - $j = new Join(array('TABLE_A.COL_1', 'TABLE_A.COL_2'), array('TABLE_B.COL_1', 'TABLE_B.COL_2'), Criteria::INNER_JOIN); - $this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn(0)); - $this->assertEquals('TABLE_A.COL_2', $j->getLeftColumn(1)); - $this->assertEquals('TABLE_B.COL_1', $j->getRightColumn(0)); - $this->assertEquals('TABLE_B.COL_2', $j->getRightColumn(1)); - } - - public function testAddStraightJoin () - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1'); // straight join - - $expect = "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.COL_1=TABLE_B.COL_1"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddSeveralJoins () - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1'); - $c->addJoin('TABLE_B.COL_X', 'TABLE_D.COL_X'); - - $expect = 'SELECT * FROM TABLE_A, TABLE_B, TABLE_D ' - .'WHERE TABLE_A.COL_1=TABLE_B.COL_1 AND TABLE_B.COL_X=TABLE_D.COL_X'; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddLeftJoin () - { - $c = new Criteria(); - $c->addSelectColumn("TABLE_A.*"); - $c->addSelectColumn("TABLE_B.*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_2', Criteria::LEFT_JOIN); - - $expect = "SELECT TABLE_A.*, TABLE_B.* FROM TABLE_A LEFT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_2)"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddSeveralLeftJoins () - { - // Fails.. Suspect answer in the chunk starting at BasePeer:605 - $c = new Criteria(); - $c->addSelectColumn('*'); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::LEFT_JOIN); - $c->addJoin('TABLE_A.COL_2', 'TABLE_C.COL_2', Criteria::LEFT_JOIN); - - $expect = 'SELECT * FROM TABLE_A ' - .'LEFT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) ' - .'LEFT JOIN TABLE_C ON (TABLE_A.COL_2=TABLE_C.COL_2)'; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddRightJoin () - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_2', Criteria::RIGHT_JOIN); - - $expect = "SELECT * FROM TABLE_A RIGHT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_2)"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddSeveralRightJoins () - { - // Fails.. Suspect answer in the chunk starting at BasePeer:605 - $c = new Criteria(); - $c->addSelectColumn('*'); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::RIGHT_JOIN); - $c->addJoin('TABLE_A.COL_2', 'TABLE_C.COL_2', Criteria::RIGHT_JOIN); - - $expect = 'SELECT * FROM TABLE_A ' - .'RIGHT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) ' - .'RIGHT JOIN TABLE_C ON (TABLE_A.COL_2=TABLE_C.COL_2)'; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddInnerJoin () - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN); - - $expect = "SELECT * FROM TABLE_A INNER JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1)"; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - public function testAddSeveralInnerJoin () - { - $c = new Criteria(); - $c->addSelectColumn("*"); - $c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN); - $c->addJoin('TABLE_B.COL_1', 'TABLE_C.COL_1', Criteria::INNER_JOIN); - - $expect = 'SELECT * FROM TABLE_A ' - .'INNER JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) ' - .'INNER JOIN TABLE_C ON (TABLE_B.COL_1=TABLE_C.COL_1)'; - try { - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - } catch (PropelException $e) { - print $e->getTraceAsString(); - $this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage()); - } - $this->assertEquals($expect, $result); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/451 - */ - public function testSeveralMixedJoinOrders() - { - $c = new Criteria(); - $c->clearSelectColumns()-> - addJoin("TABLE_A.FOO_ID", "TABLE_B.ID", Criteria::LEFT_JOIN)-> - addJoin("TABLE_A.BAR_ID", "TABLE_C.ID")-> - addSelectColumn("TABLE_A.ID"); - - # These are no longer different, see http://propel.phpdb.org/trac/ticket/283#comment:8 - #$db = Propel::getDB(); - # - #if ($db instanceof DBMySQL) { - # $expect = 'SELECT TABLE_A.ID FROM (TABLE_A CROSS JOIN TABLE_C)' - # .' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID) WHERE TABLE_A.BAR_ID=TABLE_C.ID'; - #} else { - $expect = 'SELECT TABLE_A.ID FROM TABLE_A CROSS JOIN TABLE_C' - .' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID) WHERE TABLE_A.BAR_ID=TABLE_C.ID'; - #} - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinArray() - { - $c = new Criteria(); - $c->clearSelectColumns()-> - addJoin(array('TABLE_A.FOO_ID'), array('TABLE_B.ID'), Criteria::LEFT_JOIN)-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A' - .' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID)'; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinArrayMultiple() - { - $c = new Criteria(); - $c->clearSelectColumns()-> - addJoin( - array('TABLE_A.FOO_ID', 'TABLE_A.BAR'), - array('TABLE_B.ID', 'TABLE_B.BAZ'), - Criteria::LEFT_JOIN)-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A' - .' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ)'; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * Test the Criteria::addJoinMultiple() method with an implicit join - * - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinMultiple() - { - $c = new Criteria(); - $c-> - clearSelectColumns()-> - addMultipleJoin(array( - array('TABLE_A.FOO_ID', 'TABLE_B.ID'), - array('TABLE_A.BAR', 'TABLE_B.BAZ')))-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B ' - . 'WHERE TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ'; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * Test the Criteria::addJoinMultiple() method with a value as second argument - * - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinMultipleValue() - { - $c = new Criteria(); - $c-> - clearSelectColumns()-> - addMultipleJoin(array( - array('TABLE_A.FOO_ID', 'TABLE_B.ID'), - array('TABLE_A.BAR', 3)))-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B ' - . 'WHERE TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=3'; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * Test the Criteria::addJoinMultiple() method with a joinType - * - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinMultipleWithJoinType() - { - $c = new Criteria(); - $c-> - clearSelectColumns()-> - addMultipleJoin(array( - array('TABLE_A.FOO_ID', 'TABLE_B.ID'), - array('TABLE_A.BAR', 'TABLE_B.BAZ')), - Criteria::LEFT_JOIN)-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A ' - . 'LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ)'; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expect, $result); - } - - /** - * Test the Criteria::addJoinMultiple() method with operator - * - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinMultipleWithOperator() - { - $c = new Criteria(); - $c-> - clearSelectColumns()-> - addMultipleJoin(array( - array('TABLE_A.FOO_ID', 'TABLE_B.ID', Criteria::GREATER_EQUAL), - array('TABLE_A.BAR', 'TABLE_B.BAZ', Criteria::LESS_THAN)))-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B ' - . 'WHERE TABLE_A.FOO_ID>=TABLE_B.ID AND TABLE_A.BARassertEquals($expect, $result); - } - - /** - * Test the Criteria::addJoinMultiple() method with join type and operator - * - * @link http://propel.phpdb.org/trac/ticket/606 - */ - public function testAddJoinMultipleWithJoinTypeAndOperator() - { - $c = new Criteria(); - $c-> - clearSelectColumns()-> - addMultipleJoin(array( - array('TABLE_A.FOO_ID', 'TABLE_B.ID', Criteria::GREATER_EQUAL), - array('TABLE_A.BAR', 'TABLE_B.BAZ', Criteria::LESS_THAN)), - Criteria::LEFT_JOIN)-> - addSelectColumn("TABLE_A.ID"); - - $expect = 'SELECT TABLE_A.ID FROM TABLE_A ' - . 'LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID>=TABLE_B.ID AND TABLE_A.BARassertEquals($expect, $result); - } - - /** - * Test the Criteria::CUSTOM behavior. - */ - public function testCustomOperator() - { - $c = new Criteria(); - $c->addSelectColumn('A.COL'); - $c->add('A.COL', 'date_part(\'YYYY\', A.COL) = \'2007\'', Criteria::CUSTOM); - - $expected = "SELECT A.COL FROM A WHERE date_part('YYYY', A.COL) = '2007'"; - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expected, $result); - } - - /** - * Tests adding duplicate joins. - * @link http://propel.phpdb.org/trac/ticket/613 - */ - public function testAddJoin_Duplicate() - { - $c = new Criteria(); - - $c->addJoin("tbl.COL1", "tbl.COL2", Criteria::LEFT_JOIN); - $c->addJoin("tbl.COL1", "tbl.COL2", Criteria::LEFT_JOIN); - $this->assertEquals(1, count($c->getJoins()), "Expected not to have duplciate LJOIN added."); - - $c->addJoin("tbl.COL1", "tbl.COL2", Criteria::RIGHT_JOIN); - $c->addJoin("tbl.COL1", "tbl.COL2", Criteria::RIGHT_JOIN); - $this->assertEquals(2, count($c->getJoins()), "Expected 1 new right join to be added."); - - $c->addJoin("tbl.COL1", "tbl.COL2"); - $c->addJoin("tbl.COL1", "tbl.COL2"); - $this->assertEquals(3, count($c->getJoins()), "Expected 1 new implicit join to be added."); - - $c->addJoin("tbl.COL3", "tbl.COL4"); - $this->assertEquals(4, count($c->getJoins()), "Expected new col join to be added."); - - } - - /** - * @link http://propel.phpdb.org/trac/ticket/634 - */ - public function testHasSelectClause() - { - $c = new Criteria(); - $c->addSelectColumn("foo"); - - $this->assertTrue($c->hasSelectClause()); - - $c = new Criteria(); - $c->addAsColumn("foo", "bar"); - - $this->assertTrue($c->hasSelectClause()); - } - - /** - * Tests including aliases in criterion objects. - * @link http://propel.phpdb.org/trac/ticket/636 - */ - public function testAliasInCriterion() - { - $c = new Criteria(); - $c->addAsColumn("column_alias", "tbl.COL1"); - $crit = $c->getNewCriterion("column_alias", "FOO"); - $this->assertNull($crit->getTable()); - $this->assertEquals("column_alias", $crit->getColumn()); - $c->addHaving($crit); // produces invalid SQL referring to '.olumn_alias' - } - - /** - * Test whether GROUP BY is being respected in equals() check. - * @link http://propel.phpdb.org/trac/ticket/674 - */ - public function testEqualsGroupBy() - { - $c1 = new Criteria(); - $c1->addGroupByColumn('GBY1'); - - $c2 = new Criteria(); - $c2->addGroupByColumn('GBY2'); - - $this->assertFalse($c2->equals($c1), "Expected Criteria NOT to be the same with different GROUP BY columns"); - - $c3 = new Criteria(); - $c3->addGroupByColumn('GBY1'); - $c4 = new Criteria(); - $c4->addGroupByColumn('GBY1'); - $this->assertTrue($c4->equals($c3), "Expected Criteria objects to match."); - } - - /** - * Test whether calling setDistinct twice puts in two distinct keywords or not. - * @link http://propel.phpdb.org/trac/ticket/716 - */ - public function testDoubleSelectModifiers() - { - $c = new Criteria(); - $c->setDistinct(); - $this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'Initial setDistinct works'); - $c->setDistinct(); - $this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'Calling setDistinct again leaves a single distinct'); - $c->setAll(); - $this->assertEquals(array(Criteria::ALL), $c->getSelectModifiers(), 'All keyword is swaps distinct out'); - $c->setAll(); - $this->assertEquals(array(Criteria::ALL), $c->getSelectModifiers(), 'Calling setAll leaves a single all'); - $c->setDistinct(); - $this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'All back to distinct works'); - - $c2 = new Criteria(); - $c2->setAll(); - $this->assertEquals(array(Criteria::ALL), $c2->getSelectModifiers(), 'Initial setAll works'); - } - - public function testAddSelectModifier() - { - $c = new Criteria(); - $c->setDistinct(); - $c->addSelectModifier('SQL_CALC_FOUND_ROWS'); - $this->assertEquals(array(Criteria::DISTINCT, 'SQL_CALC_FOUND_ROWS'), $c->getSelectModifiers(), 'addSelectModifier() adds a select modifier to the Criteria'); - $c->addSelectModifier('SQL_CALC_FOUND_ROWS'); - $this->assertEquals(array(Criteria::DISTINCT, 'SQL_CALC_FOUND_ROWS'), $c->getSelectModifiers(), 'addSelectModifier() adds a select modifier only once'); - $params = array(); - $result = BasePeer::createSelectSql($c, $params); - $this->assertEquals('SELECT DISTINCT SQL_CALC_FOUND_ROWS FROM ', $result, 'addSelectModifier() adds a modifier to the final query'); - } - - public function testClone() - { - $c1 = new Criteria(); - $c1->add('tbl.COL1', 'foo', Criteria::EQUAL); - $c2 = clone $c1; - $c2->addAnd('tbl.COL1', 'bar', Criteria::EQUAL); - $nbCrit = 0; - foreach ($c1->keys() as $key) { - foreach ($c1->getCriterion($key)->getAttachedCriterion() as $criterion) { - $nbCrit++; - } - } - $this->assertEquals(1, $nbCrit, 'cloning a Criteria clones its Criterions'); - } - - public function testComment() - { - $c = new Criteria(); - $this->assertNull($c->getComment(), 'Comment is null by default'); - $c2 = $c->setComment('foo'); - $this->assertEquals('foo', $c->getComment(), 'Comment is set by setComment()'); - $this->assertEquals($c, $c2, 'setComment() returns the current Criteria'); - $c->setComment(); - $this->assertNull($c->getComment(), 'Comment is reset by setComment(null)'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/JoinTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/JoinTest.php deleted file mode 100644 index c3a324552..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/JoinTest.php +++ /dev/null @@ -1,135 +0,0 @@ -savedAdapter = Propel::getDB(null); - Propel::setDB(null, new DBSQLite()); - } - - protected function tearDown() - { - Propel::setDB(null, $this->savedAdapter); - parent::tearDown(); - } - - public function testEmptyConditions() - { - $j = new Join(); - $this->assertEquals(array(), $j->getConditions()); - } - - public function testAddCondition() - { - $j = new Join(); - $j->addCondition('foo', 'bar'); - $this->assertEquals('=', $j->getOperator()); - $this->assertEquals('foo', $j->getLeftColumn()); - $this->assertEquals('bar', $j->getRightColumn()); - } - - public function testGetConditions() - { - $j = new Join(); - $j->addCondition('foo', 'bar'); - $expect = array(array('left' => 'foo', 'operator' => '=', 'right' => 'bar')); - $this->assertEquals($expect, $j->getConditions()); - } - - public function testAddConditionWithOperator() - { - $j = new Join(); - $j->addCondition('foo', 'bar', '>='); - $expect = array(array('left' => 'foo', 'operator' => '>=', 'right' => 'bar')); - $this->assertEquals($expect, $j->getConditions()); - } - - public function testAddConditions() - { - $j = new Join(); - $j->addCondition('foo', 'bar'); - $j->addCondition('baz', 'bal'); - $expect = array( - array('left' => 'foo', 'operator' => '=', 'right' => 'bar'), - array('left' => 'baz', 'operator' => '=', 'right' => 'bal') - ); - $this->assertEquals(array('=', '='), $j->getOperators()); - $this->assertEquals(array('foo', 'baz'), $j->getLeftColumns()); - $this->assertEquals(array('bar', 'bal'), $j->getRightColumns()); - $this->assertEquals($expect, $j->getConditions()); - } - - public function testEmptyJoinType() - { - $j = new Join(); - $this->assertNull($j->getJoinType()); - } - - public function testSetJoinType() - { - $j = new Join(); - $j->setJoinType('foo'); - $this->assertEquals('foo', $j->getJoinType()); - } - - public function testSimpleConstructor() - { - $j = new Join('foo', 'bar', 'LEFT JOIN'); - $expect = array(array('left' => 'foo', 'operator' => '=', 'right' => 'bar')); - $this->assertEquals($expect, $j->getConditions()); - $this->assertEquals('LEFT JOIN', $j->getJoinType()); - } - - public function testCompositeeConstructor() - { - $j = new Join(array('foo1', 'foo2'), array('bar1', 'bar2'), 'LEFT JOIN'); - $expect = array( - array('left' => 'foo1', 'operator' => '=', 'right' => 'bar1'), - array('left' => 'foo2', 'operator' => '=', 'right' => 'bar2') - ); - $this->assertEquals($expect, $j->getConditions()); - $this->assertEquals('LEFT JOIN', $j->getJoinType()); - } - - public function testCountConditions() - { - $j = new Join(); - $this->assertEquals(0, $j->countConditions()); - $j->addCondition('foo', 'bar'); - $this->assertEquals(1, $j->countConditions()); - $j->addCondition('foo1', 'bar1'); - $this->assertEquals(2, $j->countConditions()); - - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaHooksTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaHooksTest.php deleted file mode 100644 index 8c1107a87..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaHooksTest.php +++ /dev/null @@ -1,196 +0,0 @@ -find(); - $this->assertEquals(1, count($books), 'preSelect() can modify the Criteria before find() fires the query'); - - $c = new ModelCriteriaWithPreSelectHook('bookstore', 'Book'); - $nbBooks = $c->count(); - $this->assertEquals(1, $nbBooks, 'preSelect() can modify the Criteria before count() fires the query'); - } - - public function testPreDelete() - { - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - $count = count($books); - $book = $books->shift(); - - $c = new ModelCriteriaWithPreDeleteHook('bookstore', 'Book', 'b'); - $c->where('b.Id = ?', $book->getId()); - $nbBooks = $c->delete(); - $this->assertEquals(12, $nbBooks, 'preDelete() can change the return value of delete()'); - - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->count(); - $this->assertEquals($count, $nbBooks, 'preDelete() can bypass the row deletion'); - - $c = new ModelCriteriaWithPreDeleteHook('bookstore', 'Book'); - $nbBooks = $c->deleteAll(); - $this->assertEquals(12, $nbBooks, 'preDelete() can change the return value of deleteAll()'); - - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->count(); - $this->assertEquals($count, $nbBooks, 'preDelete() can bypass the row deletion'); - } - - public function testPostDelete() - { - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - $count = count($books); - $book = $books->shift(); - - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPostDeleteHook('bookstore', 'Book', 'b'); - $c->where('b.Id = ?', $book->getId()); - $nbBooks = $c->delete($this->con); - $this->assertEquals(1, $this->con->lastAffectedRows, 'postDelete() is called after delete()'); - - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPostDeleteHook('bookstore', 'Book'); - $nbBooks = $c->deleteAll($this->con); - $this->assertEquals(3, $this->con->lastAffectedRows, 'postDelete() is called after deleteAll()'); - } - - public function testPreAndPostDelete() - { - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - $count = count($books); - $book = $books->shift(); - - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', 'Book', 'b'); - $c->where('b.Id = ?', $book->getId()); - $nbBooks = $c->delete($this->con); - $this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after delete() even if preDelete() returns not null'); - - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', 'Book'); - $nbBooks = $c->deleteAll($this->con); - $this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after deleteAll() even if preDelete() returns not null'); - } - - public function testPreUpdate() - { - $c = new ModelCriteriaWithPreUpdateHook('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->update(array('Title' => 'foo')); - - $c = new ModelCriteriaWithPreUpdateHook('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $book = $c->findOne(); - - $this->assertEquals('1234', $book->getISBN(), 'preUpdate() can modify the values'); - } - - public function testPostUpdate() - { - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPostUpdateHook('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->update(array('Title' => 'foo'), $this->con); - $this->assertEquals(1, $this->con->lastAffectedRows, 'postUpdate() is called after update()'); - } - - public function testPreAndPostUpdate() - { - $this->con->lastAffectedRows = 0; - - $c = new ModelCriteriaWithPreAndPostUpdateHook('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->update(array('Title' => 'foo'), $this->con); - $this->assertEquals(52, $this->con->lastAffectedRows, 'postUpdate() is called after update() even if preUpdate() returns not null'); - } -} - -class ModelCriteriaWithPreSelectHook extends ModelCriteria -{ - public function preSelect(PropelPDO $con) - { - $this->where($this->getModelAliasOrName() . '.Title = ?', 'Don Juan'); - } -} - -class ModelCriteriaWithPreDeleteHook extends ModelCriteria -{ - public function preDelete(PropelPDO $con) - { - return 12; - } -} - -class ModelCriteriaWithPostDeleteHook extends ModelCriteria -{ - public function postDelete($affectedRows, PropelPDO $con) - { - $con->lastAffectedRows = $affectedRows; - } -} - -class ModelCriteriaWithPreAndPostDeleteHook extends ModelCriteriaWithPostDeleteHook -{ - public function preDelete(PropelPDO $con) - { - return 12; - } -} - -class ModelCriteriaWithPreUpdateHook extends ModelCriteria -{ - public function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false) - { - $values['ISBN'] = '1234'; - } -} - -class ModelCriteriaWithPostUpdateHook extends ModelCriteria -{ - public function postUpdate($affectedRows, PropelPDO $con) - { - $con->lastAffectedRows = $affectedRows; - } -} - -class ModelCriteriaWithPreAndPostUpdateHook extends ModelCriteriaWithPostUpdateHook -{ - public function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false) - { - return 52; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaTest.php deleted file mode 100644 index fdd8efb69..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelCriteriaTest.php +++ /dev/null @@ -1,2068 +0,0 @@ -assertEquals($expectedSql, $result, $message); - $this->assertEquals($expectedParams, $params, $message); - } - - public function testGetModelName() - { - $c = new ModelCriteria('bookstore', 'Book'); - $this->assertEquals('Book', $c->getModelName(), 'getModelName() returns the name of the class associated to the model class'); - } - - public function testGetModelPeerName() - { - $c = new ModelCriteria('bookstore', 'Book'); - $this->assertEquals('BookPeer', $c->getModelPeerName(), 'getModelPeerName() returns the name of the Peer class associated to the model class'); - } - - public function testFormatter() - { - $c = new ModelCriteria('bookstore', 'Book'); - $this->assertTrue($c->getFormatter() instanceof PropelFormatter, 'getFormatter() returns a PropelFormatter instance'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setFormatter(ModelCriteria::FORMAT_STATEMENT); - $this->assertTrue($c->getFormatter() instanceof PropelStatementFormatter, 'setFormatter() accepts the name of a PropelFormatter class'); - - try { - $c->setFormatter('Book'); - $this->fail('setFormatter() throws an exception when passed the name of a class not extending PropelFormatter'); - } catch(PropelException $e) { - $this->assertTrue(true, 'setFormatter() throws an exception when passed the name of a class not extending PropelFormatter'); - } - $c = new ModelCriteria('bookstore', 'Book'); - $formatter = new PropelStatementFormatter(); - $c->setFormatter($formatter); - $this->assertTrue($c->getFormatter() instanceof PropelStatementFormatter, 'setFormatter() accepts a PropelFormatter instance'); - - try { - $formatter = new Book(); - $c->setFormatter($formatter); - $this->fail('setFormatter() throws an exception when passed an object not extending PropelFormatter'); - } catch(PropelException $e) { - $this->assertTrue(true, 'setFormatter() throws an exception when passedan object not extending PropelFormatter'); - } - - } - - public static function conditionsForTestReplaceNames() - { - return array( - array('Book.Title = ?', 'Title', 'book.TITLE = ?'), // basic case - array('Book.Title=?', 'Title', 'book.TITLE=?'), // without spaces - array('Book.Id<= ?', 'Id', 'book.ID<= ?'), // with non-equal comparator - array('Book.AuthorId LIKE ?', 'AuthorId', 'book.AUTHOR_ID LIKE ?'), // with SQL keyword separator - array('(Book.AuthorId) LIKE ?', 'AuthorId', '(book.AUTHOR_ID) LIKE ?'), // with parenthesis - array('(Book.Id*1.5)=1', 'Id', '(book.ID*1.5)=1'), // ignore numbers - array('1=1', null, '1=1'), // with no name - array('', null, '') // with empty string - ); - } - - /** - * @dataProvider conditionsForTestReplaceNames - */ - public function testReplaceNames($origClause, $columnPhpName = false, $modifiedClause) - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->replaceNames($origClause); - $columns = $c->replacedColumns; - if ($columnPhpName) { - $this->assertEquals(array(BookPeer::getTableMap()->getColumnByPhpName($columnPhpName)), $columns); - } - $this->assertEquals($modifiedClause, $origClause); - } - - public static function conditionsForTestReplaceMultipleNames() - { - return array( - array('(Book.Id+Book.Id)=1', array('Id', 'Id'), '(book.ID+book.ID)=1'), // match multiple names - array('CONCAT(Book.Title,"Book.Id")= ?', array('Title', 'Id'), 'CONCAT(book.TITLE,"Book.Id")= ?'), // ignore names in strings - array('CONCAT(Book.Title," Book.Id ")= ?', array('Title', 'Id'), 'CONCAT(book.TITLE," Book.Id ")= ?'), // ignore names in strings - array('MATCH (Book.Title,Book.ISBN) AGAINST (?)', array('Title', 'ISBN'), 'MATCH (book.TITLE,book.ISBN) AGAINST (?)'), - ); - } - - /** - * @dataProvider conditionsForTestReplaceMultipleNames - */ - public function testReplaceMultipleNames($origClause, $expectedColumns, $modifiedClause) - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->replaceNames($origClause); - $foundColumns = $c->replacedColumns; - foreach ($foundColumns as $column) { - $expectedColumn = BookPeer::getTableMap()->getColumnByPhpName(array_shift($expectedColumns)); - $this->assertEquals($expectedColumn, $column); - } - $this->assertEquals($modifiedClause, $origClause); - } - - public function testTableAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b'); - $c->where('b.Title = ?', 'foo'); - - $sql = "SELECT FROM `book` WHERE book.TITLE = :p1"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'setModelAlias() allows the definition of the alias after constrution'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - - $sql = "SELECT FROM `book` WHERE book.TITLE = :p1"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'A ModelCriteria accepts a model name with an alias'); - } - - public function testTrueTableAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->where('b.Title = ?', 'foo'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'john'); - - - $sql = "SELECT FROM `book` `b` INNER JOIN author a ON (b.AUTHOR_ID=a.ID) WHERE b.TITLE = :p1 AND a.FIRST_NAME = :p2"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'author', 'column' => 'FIRST_NAME', 'value' => 'john'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'setModelAlias() allows the definition of a true SQL alias after constrution'); - } - - public function testCondition() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->combine(array('cond1', 'cond2'), 'or'); - - $sql = "SELECT FROM `book` WHERE (book.TITLE <> :p1 OR book.TITLE like :p2)"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'TITLE', 'value' => '%bar%'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'condition() can store condition for later combination'); - } - - public static function conditionsForTestWhere() - { - return array( - array('Book.Title = ?', 'foo', 'book.TITLE = :p1', array(array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'))), - array('Book.AuthorId = ?', 12, 'book.AUTHOR_ID = :p1', array(array('table' => 'book', 'column' => 'AUTHOR_ID', 'value' => 12))), - array('Book.AuthorId IS NULL', null, 'book.AUTHOR_ID IS NULL', array()), - array('Book.Id BETWEEN ? AND ?', array(3, 4), 'book.ID BETWEEN :p1 AND :p2', array(array('table' => 'book', 'column' => 'ID', 'value' => 3), array('table' => 'book', 'column' => 'ID', 'value' => 4))), - array('Book.Id betWEen ? and ?', array(3, 4), 'book.ID betWEen :p1 and :p2', array(array('table' => 'book', 'column' => 'ID', 'value' => 3), array('table' => 'book', 'column' => 'ID', 'value' => 4))), - array('Book.Id IN ?', array(1, 2, 3), 'book.ID IN (:p1,:p2,:p3)', array(array('table' => 'book', 'column' => 'ID', 'value' => 1), array('table' => 'book', 'column' => 'ID', 'value' => 2), array('table' => 'book', 'column' => 'ID', 'value' => 3))), - array('Book.Id in ?', array(1, 2, 3), 'book.ID in (:p1,:p2,:p3)', array(array('table' => 'book', 'column' => 'ID', 'value' => 1), array('table' => 'book', 'column' => 'ID', 'value' => 2), array('table' => 'book', 'column' => 'ID', 'value' => 3))), - array('Book.Id IN ?', array(), '1<>1', array()), - array('Book.Id not in ?', array(), '1=1', array()), - array('UPPER(Book.Title) = ?', 'foo', 'UPPER(book.TITLE) = :p1', array(array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'))), - array('MATCH (Book.Title,Book.ISBN) AGAINST (?)', 'foo', 'MATCH (book.TITLE,book.ISBN) AGAINST (:p1)', array(array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'))), - ); - } - - /** - * @dataProvider conditionsForTestWhere - */ - public function testWhere($clause, $value, $sql, $params) - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->where($clause, $value); - $sql = 'SELECT FROM `book` WHERE ' . $sql; - $this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts a string clause'); - } - - public function testWhereTwiceSameColumn() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Id IN ?', array(1, 2, 3)); - $c->where('Book.Id <> ?', 5); - $params = array( - array('table' => 'book', 'column' => 'ID', 'value' => '1'), - array('table' => 'book', 'column' => 'ID', 'value' => '2'), - array('table' => 'book', 'column' => 'ID', 'value' => '3'), - array('table' => 'book', 'column' => 'ID', 'value' => '5'), - ); - $sql = 'SELECT FROM `book` WHERE (book.ID IN (:p1,:p2,:p3) AND book.ID <> :p4)'; - $this->assertCriteriaTranslation($c, $sql, $params, 'where() adds clauses on the same column correctly'); - } - - public function testWhereConditions() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->where(array('cond1', 'cond2')); - - $sql = "SELECT FROM `book` WHERE (book.TITLE <> :p1 AND book.TITLE like :p2)"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'TITLE', 'value' => '%bar%'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts an array of named conditions'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->where(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - - $sql = "SELECT FROM `book` WHERE (book.TITLE <> :p1 OR book.TITLE like :p2)"; - $this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts an array of named conditions with operator'); - } - - public function testWhereNoReplacement() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $c->where('1=1'); - - $sql = "SELECT FROM `book` WHERE book.TITLE = :p1 AND 1=1"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'where() results in a Criteria::CUSTOM if no column name is matched'); - - $c = new ModelCriteria('bookstore', 'Book'); - try { - $c->where('b.Title = ?', 'foo'); - $this->fail('where() throws an exception when it finds a ? but cannot determine a column'); - } catch (PropelException $e) { - $this->assertTrue(true, 'where() throws an exception when it finds a ? but cannot determine a column'); - } - } - - public function testWhereFunction() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('UPPER(b.Title) = ?', 'foo'); - - $sql = "SELECT FROM `book` WHERE UPPER(book.TITLE) = :p1"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts a complex calculation'); - } - - public function testOrWhere() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Title <> ?', 'foo'); - $c->orWhere('Book.Title like ?', '%bar%'); - - $sql = "SELECT FROM `book` WHERE (book.TITLE <> :p1 OR book.TITLE like :p2)"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'TITLE', 'value' => '%bar%'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() combines the clause with the previous one using OR'); - } - - public function testOrWhereConditions() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Id = ?', 12); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->orWhere(array('cond1', 'cond2')); - - $sql = "SELECT FROM `book` WHERE (book.ID = :p1 OR (book.TITLE <> :p2 AND book.TITLE like :p3))"; - $params = array( - array('table' => 'book', 'column' => 'ID', 'value' => 12), - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'TITLE', 'value' => '%bar%'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() accepts an array of named conditions'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Id = ?', 12); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->orWhere(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - - $sql = "SELECT FROM `book` WHERE (book.ID = :p1 OR (book.TITLE <> :p2 OR book.TITLE like :p3))"; - $this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() accepts an array of named conditions with operator'); - } - - public function testMixedCriteria() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->where('Book.Title = ?', 'foo'); - $c->add(BookPeer::ID, array(1, 2), Criteria::IN); - - $sql = 'SELECT FROM `book` WHERE book.TITLE = :p1 AND book.ID IN (:p2,:p3)'; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'ID', 'value' => 1), - array('table' => 'book', 'column' => 'ID', 'value' => 2) - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'ModelCriteria accepts Criteria operators'); - } - - public function testFilterBy() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->filterBy('Title', 'foo'); - - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'filterBy() accepts a simple column name'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->filterBy('Title', 'foo', Criteria::NOT_EQUAL); - - $sql = 'SELECT FROM `book` WHERE book.TITLE<>:p1'; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'filterBy() accepts a sicustom comparator'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->filterBy('Title', 'foo'); - - $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'filterBy() accepts a simple column name, even if initialized with an alias'); - } - - public function testHaving() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->having('Book.Title <> ?', 'foo'); - - $sql = "SELECT FROM HAVING book.TITLE <> :p1"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts a string clause'); - } - - public function testHavingConditions() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->having(array('cond1', 'cond2')); - - $sql = "SELECT FROM HAVING (book.TITLE <> :p1 AND book.TITLE like :p2)"; - $params = array( - array('table' => 'book', 'column' => 'TITLE', 'value' => 'foo'), - array('table' => 'book', 'column' => 'TITLE', 'value' => '%bar%'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts an array of named conditions'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->condition('cond1', 'Book.Title <> ?', 'foo'); - $c->condition('cond2', 'Book.Title like ?', '%bar%'); - $c->having(array('cond1', 'cond2'), Criteria::LOGICAL_OR); - - $sql = "SELECT FROM HAVING (book.TITLE <> :p1 OR book.TITLE like :p2)"; - $this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts an array of named conditions with an operator'); - } - - public function testOrderBy() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title'); - - $sql = 'SELECT FROM ORDER BY book.TITLE ASC'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a column name and adds an ORDER BY clause'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Book.Title', 'desc'); - - $sql = 'SELECT FROM ORDER BY book.TITLE DESC'; - $this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts an order parameter'); - - $c = new ModelCriteria('bookstore', 'Book'); - try { - $c->orderBy('Book.Foo'); - $this->fail('orderBy() throws an exception when called with an unkown column name'); - } catch (PropelException $e) { - $this->assertTrue(true, 'orderBy() throws an exception when called with an unkown column name'); - } - $c = new ModelCriteria('bookstore', 'Book'); - try { - $c->orderBy('Book.Title', 'foo'); - $this->fail('orderBy() throws an exception when called with an unkown order'); - } catch (PropelException $e) { - $this->assertTrue(true, 'orderBy() throws an exception when called with an unkown order'); - } - } - - public function testOrderBySimpleColumn() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->orderBy('Title'); - - $sql = 'SELECT FROM ORDER BY book.TITLE ASC'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a simple column name and adds an ORDER BY clause'); - } - - public function testOrderByAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->addAsColumn('t', BookPeer::TITLE); - $c->orderBy('t'); - - $sql = 'SELECT book.TITLE AS t FROM ORDER BY t ASC'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a column alias and adds an ORDER BY clause'); - } - - public function testGroupBy() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->groupBy('Book.AuthorId'); - - $sql = 'SELECT FROM GROUP BY book.AUTHOR_ID'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a column name and adds a GROUP BY clause'); - - $c = new ModelCriteria('bookstore', 'Book'); - try { - $c->groupBy('Book.Foo'); - $this->fail('groupBy() throws an exception when called with an unkown column name'); - } catch (PropelException $e) { - $this->assertTrue(true, 'groupBy() throws an exception when called with an unkown column name'); - } - } - - public function testGroupBySimpleColumn() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->groupBy('AuthorId'); - - $sql = 'SELECT FROM GROUP BY book.AUTHOR_ID'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a simple column name and adds a GROUP BY clause'); - } - - public function testGroupByAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->addAsColumn('t', BookPeer::TITLE); - $c->groupBy('t'); - - $sql = 'SELECT book.TITLE AS t FROM GROUP BY t'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a column alias and adds a GROUP BY clause'); - } - - public function testDistinct() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->distinct(); - $sql = 'SELECT DISTINCT FROM '; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'distinct() adds a DISTINCT clause'); - } - - public function testLimit() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->limit(10); - $sql = 'SELECT FROM LIMIT 10'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'limit() adds a LIMIT clause'); - } - - public function testOffset() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->limit(50); - $c->offset(10); - $sql = 'SELECT FROM LIMIT 10, 50'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'offset() adds an OFFSET clause'); - } - - public function testJoin() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() uses a relation to guess the columns'); - - $c = new ModelCriteria('bookstore', 'Book'); - try { - $c->join('Book.Foo'); - $this->fail('join() throws an exception when called with a non-existing relation'); - } catch (PropelException $e) { - $this->assertTrue(true, 'join() throws an exception when called with a non-existing relation'); - } - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $c->where('Author.FirstName = ?', 'Leo'); - $sql = 'SELECT FROM INNER JOIN author ON (book.AUTHOR_ID=author.ID) WHERE author.FIRST_NAME = :p1'; - $params = array( - array('table' => 'author', 'column' => 'FIRST_NAME', 'value' => 'Leo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() uses a relation to guess the columns'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Author'); - $c->where('Author.FirstName = ?', 'Leo'); - $sql = 'SELECT FROM INNER JOIN author ON (book.AUTHOR_ID=author.ID) WHERE author.FIRST_NAME = :p1'; - $params = array( - array('table' => 'author', 'column' => 'FIRST_NAME', 'value' => 'Leo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() uses the current model name when given a simple relation name'); - } - - public function testJoinQuery() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::depopulate($con); - BookstoreDataPopulator::populate($con); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $c->where('Author.FirstName = ?', 'Neal'); - $books = BookPeer::doSelect($c); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID) WHERE author.FIRST_NAME = 'Neal'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() issues a real JOIN query'); - $this->assertEquals(1, count($books), 'join() issues a real JOIN query'); - } - - public function testJoinRelationName() - { - $c = new ModelCriteria('bookstore', 'BookstoreEmployee'); - $c->join('BookstoreEmployee.Supervisor'); - $sql = 'SELECT FROM INNER JOIN bookstore_employee ON (bookstore_employee.SUPERVISOR_ID=bookstore_employee.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() uses relation names as defined in schema.xml'); - } - - public function testJoinComposite() - { - $c = new ModelCriteria('bookstore', 'ReaderFavorite'); - $c->join('ReaderFavorite.BookOpinion'); - $sql = 'SELECT FROM `reader_favorite` INNER JOIN book_opinion ON (reader_favorite.BOOK_ID=book_opinion.BOOK_ID AND reader_favorite.READER_ID=book_opinion.READER_ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() knows how to create a JOIN clause for relationships with composite fkeys'); - } - - public function testJoinType() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds an INNER JOIN by default'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author', Criteria::INNER_JOIN); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds an INNER JOIN by default'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author', Criteria::LEFT_JOIN); - $sql = 'SELECT FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() can add a LEFT JOIN'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author', Criteria::RIGHT_JOIN); - $sql = 'SELECT FROM `book` RIGHT JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() can add a RIGHT JOIN'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author', 'incorrect join'); - $sql = 'SELECT FROM `book` incorrect join author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() accepts any join string'); - } - - public function testJoinDirection() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for many to one relationship'); - - $c = new ModelCriteria('bookstore', 'Author'); - $c->join('Author.Book'); - $sql = 'SELECT FROM `author` INNER JOIN book ON (author.ID=book.AUTHOR_ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to many relationship'); - - $c = new ModelCriteria('bookstore', 'BookstoreEmployee'); - $c->join('BookstoreEmployee.BookstoreEmployeeAccount'); - $sql = 'SELECT FROM `bookstore_employee` INNER JOIN bookstore_employee_account ON (bookstore_employee.ID=bookstore_employee_account.EMPLOYEE_ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to one relationship'); - - $c = new ModelCriteria('bookstore', 'BookstoreEmployeeAccount'); - $c->join('BookstoreEmployeeAccount.BookstoreEmployee'); - $sql = 'SELECT FROM `bookstore_employee_account` INNER JOIN bookstore_employee ON (bookstore_employee_account.EMPLOYEE_ID=bookstore_employee.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to one relationship'); - } - - public function testJoinSeveral() - { - $c = new ModelCriteria('bookstore', 'Author'); - $c->join('Author.Book'); - $c->join('Book.Publisher'); - $c->where('Publisher.Name = ?', 'foo'); - $sql = 'SELECT FROM INNER JOIN book ON (author.ID=book.AUTHOR_ID) INNER JOIN publisher ON (book.PUBLISHER_ID=publisher.ID) WHERE publisher.NAME = :p1'; - $params = array( - array('table' => 'publisher', 'column' => 'NAME', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() can guess relationships from related tables'); - } - - public function testJoinAlias() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author'); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation on main alias'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('Author'); - $sql = 'SELECT FROM `book` INNER JOIN author ON (book.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() can use a simple relation name when the model has an alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author a'); - $sql = 'SELECT FROM `book` INNER JOIN author a ON (book.AUTHOR_ID=a.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation alias'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $sql = 'SELECT FROM `book` INNER JOIN author a ON (book.AUTHOR_ID=a.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation alias on main alias'); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'Leo'); - $sql = 'SELECT FROM INNER JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = :p1'; - $params = array( - array('table' => 'author', 'column' => 'FIRST_NAME', 'value' => 'Leo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() allows the use of relation alias in where()'); - - $c = new ModelCriteria('bookstore', 'Author', 'a'); - $c->join('a.Book b'); - $c->join('b.Publisher p'); - $c->where('p.Name = ?', 'foo'); - $sql = 'SELECT FROM INNER JOIN book b ON (author.ID=b.AUTHOR_ID) INNER JOIN publisher p ON (b.PUBLISHER_ID=p.ID) WHERE p.NAME = :p1'; - $params = array( - array('table' => 'publisher', 'column' => 'NAME', 'value' => 'foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() allows the use of relation alias in further join()'); - } - - public function testJoinTrueTableAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->join('b.Author'); - $sql = 'SELECT FROM `book` `b` INNER JOIN author ON (b.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation on true table alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->join('Author'); - $sql = 'SELECT FROM `book` `b` INNER JOIN author ON (b.AUTHOR_ID=author.ID)'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation without alias name on true table alias'); - } - - public function testJoinOnSameTable() - { - $c = new ModelCriteria('bookstore', 'BookstoreEmployee', 'be'); - $c->join('be.Supervisor sup'); - $c->join('sup.Subordinate sub'); - $c->where('sub.Name = ?', 'Foo'); - $sql = 'SELECT FROM INNER JOIN bookstore_employee sup ON (bookstore_employee.SUPERVISOR_ID=sup.ID) INNER JOIN bookstore_employee sub ON (sup.ID=sub.SUPERVISOR_ID) WHERE sub.NAME = :p1'; - $params = array( - array('table' => 'bookstore_employee', 'column' => 'NAME', 'value' => 'Foo'), - ); - $this->assertCriteriaTranslation($c, $sql, $params, 'join() allows two joins on the same table thanks to aliases'); - } - - public function testJoinAliasQuery() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'Leo'); - $books = BookPeer::doSelect($c, $con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` INNER JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() allows the use of relation alias in where()'); - - $c = new ModelCriteria('bookstore', 'BookstoreEmployee', 'be'); - $c->join('be.Supervisor sup'); - $c->join('sup.Subordinate sub'); - $c->where('sub.Name = ?', 'Foo'); - $employees = BookstoreEmployeePeer::doSelect($c, $con); - $expectedSQL = "SELECT bookstore_employee.ID, bookstore_employee.CLASS_KEY, bookstore_employee.NAME, bookstore_employee.JOB_TITLE, bookstore_employee.SUPERVISOR_ID FROM `bookstore_employee` INNER JOIN bookstore_employee sup ON (bookstore_employee.SUPERVISOR_ID=sup.ID) INNER JOIN bookstore_employee sub ON (sup.ID=sub.SUPERVISOR_ID) WHERE sub.NAME = 'Foo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() allows the use of relation alias in further joins()'); - } - - public function testGetJoin() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - - $joins = $c->getJoins(); - $this->assertEquals($joins['Author'], $c->getJoin('Author'), "getJoin() returns a specific Join from the ModelCriteria"); - } - - public function testWith() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $c->with('Author'); - $withs = $c->getWith(); - $this->assertTrue(array_key_exists('Author', $withs), 'with() adds an entry to the internal list of Withs'); - $this->assertTrue($withs['Author'] instanceof ModelJoin, 'with() references the ModelJoin object'); - } - - /** - * @expectedException PropelException - */ - public function testWithThrowsExceptionWhenJoinLacks() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->with('Author'); - } - - public function testWithAlias() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->join('Book.Author a'); - $c->with('a'); - $withs = $c->getWith(); - $this->assertTrue(array_key_exists('a', $withs), 'with() uses the alias for the index of the internal list of Withs'); - } - - /** - * @expectedException PropelException - */ - public function testWithThrowsExceptionWhenNotUsingAlias() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->join('Book.Author a'); - $c->with('Author'); - } - - public function testWithAddsSelectColumns() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - BookPeer::addSelectColumns($c); - $c->join('Book.Author'); - $c->with('Author'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table'); - } - - public function testWithAliasAddsSelectColumns() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - BookPeer::addSelectColumns($c); - $c->join('Book.Author a'); - $c->with('a'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - 'a.ID', - 'a.FIRST_NAME', - 'a.LAST_NAME', - 'a.EMAIL', - 'a.AGE' - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table'); - } - - public function testWithAddsSelectColumnsOfMainTable() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->join('Book.Author'); - $c->with('Author'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the main table if required'); - } - - public function testWithAliasAddsSelectColumnsOfMainTable() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->join('b.Author a'); - $c->with('a'); - $expectedColumns = array( - 'b.ID', - 'b.TITLE', - 'b.ISBN', - 'b.PRICE', - 'b.PUBLISHER_ID', - 'b.AUTHOR_ID', - 'a.ID', - 'a.FIRST_NAME', - 'a.LAST_NAME', - 'a.EMAIL', - 'a.AGE' - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the main table with an alias if required'); - } - - public function testWithOneToManyAddsSelectColumns() - { - $c = new TestableModelCriteria('bookstore', 'Author'); - AuthorPeer::addSelectColumns($c); - $c->leftJoin('Author.Book'); - $c->with('Book'); - $expectedColumns = array( - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE, - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table even in a one-to-many relationship'); - } - - public function testJoinWith() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->joinWith('Book.Author'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the join'); - $joins = $c->getJoins(); - $join = $joins['Author']; - $this->assertEquals(Criteria::INNER_JOIN, $join->getJoinType(), 'joinWith() adds an INNER JOIN by default'); - } - - public function testJoinWithType() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->joinWith('Book.Author', Criteria::LEFT_JOIN); - $joins = $c->getJoins(); - $join = $joins['Author']; - $this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'joinWith() accepts a join type as second parameter'); - } - - public function testJoinWithAlias() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->joinWith('Book.Author a'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - 'a.ID', - 'a.FIRST_NAME', - 'a.LAST_NAME', - 'a.EMAIL', - 'a.AGE' - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the join with the alias'); - } - - public function testJoinWithSeveral() - { - $c = new TestableModelCriteria('bookstore', 'Review'); - $c->joinWith('Review.Book'); - $c->joinWith('Book.Author'); - $c->joinWith('Book.Publisher'); - $expectedColumns = array( - ReviewPeer::ID, - ReviewPeer::REVIEWED_BY, - ReviewPeer::REVIEW_DATE, - ReviewPeer::RECOMMENDED, - ReviewPeer::STATUS, - ReviewPeer::BOOK_ID, - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE, - PublisherPeer::ID, - PublisherPeer::NAME - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the with'); - $joins = $c->getJoins(); - $expectedJoinKeys = array('Book', 'Author', 'Publisher'); - $this->assertEquals($expectedJoinKeys, array_keys($joins), 'joinWith() adds the join'); - } - - public function testJoinWithTwice() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->join('Book.Review'); - $c->joinWith('Book.Author'); - $c->joinWith('Book.Review'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE, - ReviewPeer::ID, - ReviewPeer::REVIEWED_BY, - ReviewPeer::REVIEW_DATE, - ReviewPeer::RECOMMENDED, - ReviewPeer::STATUS, - ReviewPeer::BOOK_ID, - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the with'); - $joins = $c->getJoins(); - $expectedJoinKeys = array('Review', 'Author'); - $this->assertEquals($expectedJoinKeys, array_keys($joins), 'joinWith() adds the join'); - } - - public static function conditionsForTestWithColumn() - { - return array( - array('Book.Title', 'BookTitle', 'book.TITLE AS BookTitle'), - array('Book.Title', null, 'book.TITLE AS BookTitle'), - array('UPPER(Book.Title)', null, 'UPPER(book.TITLE) AS UPPERBookTitle'), - array('CONCAT(Book.Title, Book.ISBN)', 'foo', 'CONCAT(book.TITLE, book.ISBN) AS foo'), - ); - } - - /** - * @dataProvider conditionsForTestWithColumn - */ - public function testWithColumn($clause, $alias, $selectTranslation) - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->withColumn($clause, $alias); - $sql = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, ' . $selectTranslation . ' FROM `book`'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() adds a calculated column to the select clause'); - } - - public function testWithColumnAndSelectColumns() - { - $c = new ModelCriteria('bookstore', 'Book'); - $c->withColumn('UPPER(Book.Title)', 'foo'); - $sql = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, UPPER(book.TITLE) AS foo FROM `book`'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() adds the object columns if the criteria has no select columns'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->addSelectColumn('book.ID'); - $c->withColumn('UPPER(Book.Title)', 'foo'); - $sql = 'SELECT book.ID, UPPER(book.TITLE) AS foo FROM `book`'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() does not add the object columns if the criteria already has select columns'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->addSelectColumn('book.ID'); - $c->withColumn('UPPER(Book.Title)', 'foo'); - $c->addSelectColumn('book.TITLE'); - $sql = 'SELECT book.ID, book.TITLE, UPPER(book.TITLE) AS foo FROM `book`'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() does adds as column after the select columns even though the withColumn() method was called first'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->addSelectColumn('book.ID'); - $c->withColumn('UPPER(Book.Title)', 'foo'); - $c->withColumn('UPPER(Book.ISBN)', 'isbn'); - $sql = 'SELECT book.ID, UPPER(book.TITLE) AS foo, UPPER(book.ISBN) AS isbn FROM `book`'; - $params = array(); - $this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() called repeatedly adds several as colums'); - } - - public function testKeepQuery() - { - $c = BookQuery::create(); - $this->assertFalse($c->isKeepQuery(), 'keepQuery is disabled by default'); - $c->keepQuery(); - $this->assertTrue($c->isKeepQuery(), 'keepQuery() enables the keepQuery property'); - $c->keepQuery(false); - $this->assertFalse($c->isKeepQuery(), 'keepQuery(false) disables the keepQuery property'); - } - - public function testKeepQueryFind() - { - $c = BookQuery::create(); - $c->filterByTitle('foo'); - $c->find(); - $expected = array('book.ID', 'book.TITLE', 'book.ISBN', 'book.PRICE', 'book.PUBLISHER_ID', 'book.AUTHOR_ID'); - $this->assertEquals($expected, $c->getSelectColumns(), 'find() modifies the query by default'); - - $c = BookQuery::create(); - $c->filterByTitle('foo'); - $c->keepQuery(); - $c->find(); - $this->assertEquals(array(), $c->getSelectColumns(), 'keepQuery() forces find() to use a clone and keep the original query unmodified'); - } - - public function testKeepQueryFindOne() - { - $c = BookQuery::create(); - $c->filterByTitle('foo'); - $c->findOne(); - $this->assertEquals(1, $c->getLimit(), 'findOne() modifies the query by default'); - - $c = BookQuery::create(); - $c->filterByTitle('foo'); - $c->keepQuery(); - $c->findOne(); - $this->assertEquals(0, $c->getLimit(), 'keepQuery() forces findOne() to use a clone and keep the original query unmodified'); - } - - public function testKeepQueryFindPk() - { - $c = BookQuery::create(); - $c->findPk(1); - $expected = array('book.ID', 'book.TITLE', 'book.ISBN', 'book.PRICE', 'book.PUBLISHER_ID', 'book.AUTHOR_ID'); - $this->assertEquals($expected, $c->getSelectColumns(), 'findPk() modifies the query by default'); - - $c = BookQuery::create(); - $c->keepQuery(); - $c->findPk(1); - $this->assertEquals(array(), $c->getSelectColumns(), 'keepQuery() forces findPk() to use a clone and keep the original query unmodified'); - } - - public function testKeepQueryCount() - { - $c = BookQuery::create(); - $c->orderByTitle(); - $c->count(); - $this->assertEquals(array(), $c->getOrderByColumns(), 'count() modifies the query by default'); - - $c = BookQuery::create(); - $c->orderByTitle(); - $c->keepQuery(); - $c->count(); - $this->assertEquals(array('book.TITLE ASC'), $c->getOrderByColumns(), 'keepQuery() forces count() to use a clone and keep the original query unmodified'); - } - - public function testFind() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $books = $c->find(); - $this->assertTrue($books instanceof PropelCollection, 'find() returns a collection by default'); - $this->assertEquals(0, count($books), 'find() returns an empty array when the query returns no result'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'Neal'); - $books = $c->find(); - $this->assertTrue($books instanceof PropelCollection, 'find() returns a collection by default'); - $this->assertEquals(1, count($books), 'find() returns as many rows as the results in the query'); - $book = $books->shift(); - $this->assertTrue($book instanceof Book, 'find() returns an array of Model objects by default'); - $this->assertEquals('Quicksilver', $book->getTitle(), 'find() returns the model objects matching the query'); - } - - public function testFindAddsSelectColumns() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find($con); - $sql = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book`"; - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'find() adds the select columns of the current model'); - } - - public function testFindTrueAliasAddsSelectColumns() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $books = $c->find($con); - $sql = "SELECT b.ID, b.TITLE, b.ISBN, b.PRICE, b.PUBLISHER_ID, b.AUTHOR_ID FROM `book` `b`"; - $this->assertEquals($sql, $con->getLastExecutedQuery(), 'find() uses the true model alias if available'); - } - - public function testFindOne() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $book = $c->findOne(); - $this->assertNull($book, 'findOne() returns null when the query returns no result'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->orderBy('b.Title'); - $book = $c->findOne(); - $this->assertTrue($book instanceof Book, 'findOne() returns a Model object by default'); - $this->assertEquals('Don Juan', $book->getTitle(), 'find() returns the model objects matching the query'); - } - - public function testFindOneOrCreateNotExists() - { - BookQuery::create()->deleteAll(); - $book = BookQuery::create('b') - ->where('b.Title = ?', 'foo') - ->filterByPrice(125) - ->findOneOrCreate(); - $this->assertTrue($book instanceof Book, 'findOneOrCreate() returns an instance of the model when the request has no result'); - $this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result'); - $this->assertEquals('foo', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions'); - $this->assertEquals(125, $book->getPrice(), 'findOneOrCreate() returns a populated objects based on the conditions'); - } - - public function testFindOneOrCreateNotExistsFormatter() - { - BookQuery::create()->deleteAll(); - $book = BookQuery::create('b') - ->where('b.Title = ?', 'foo') - ->filterByPrice(125) - ->setFormatter(ModelCriteria::FORMAT_ARRAY) - ->findOneOrCreate(); - $this->assertTrue(is_array($book), 'findOneOrCreate() uses the query formatter even when the request has no result'); - $this->assertEquals('foo', $book['Title'], 'findOneOrCreate() returns a populated array based on the conditions'); - $this->assertEquals(125, $book['Price'], 'findOneOrCreate() returns a populated array based on the conditions'); - } - - public function testFindOneOrCreateExists() - { - BookQuery::create()->deleteAll(); - $book = new Book(); - $book->setTitle('foo'); - $book->setPrice(125); - $book->save(); - $book = BookQuery::create('b') - ->where('b.Title = ?', 'foo') - ->filterByPrice(125) - ->findOneOrCreate(); - $this->assertTrue($book instanceof Book, 'findOneOrCreate() returns an instance of the model when the request has one result'); - $this->assertFalse($book->isNew(), 'findOneOrCreate() returns an existing instance of the model when the request has one result'); - $this->assertEquals('foo', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions'); - $this->assertEquals(125, $book->getPrice(), 'findOneOrCreate() returns a populated objects based on the conditions'); - } - - public function testFindPkSimpleKey() - { - BookstoreDataPopulator::depopulate(); - - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findPk(765432); - $this->assertNull($book, 'findPk() returns null when the primary key is not found'); - - BookstoreDataPopulator::populate(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'Book'); - $testBook = $c->findOne(); - - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findPk($testBook->getId()); - $this->assertEquals($testBook, $book, 'findPk() returns a model object corresponding to the pk'); - } - - public function testFindPksSimpleKey() - { - BookstoreDataPopulator::depopulate(); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findPks(array(765432, 434535)); - $this->assertEquals($books instanceof PropelCollection, 'findPks() returns a PropelCollection'); - $this->assertEquals(0, count($books), 'findPks() returns an empty collection when the primary keys are not found'); - - BookstoreDataPopulator::populate(); - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'Book'); - $testBooks = $c->find(); - $testBook1 = $testBooks->pop(); - $testBook2 = $testBooks->pop(); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findPks(array($testBook1->getId(), $testBook2->getId())); - $this->assertEquals(array($testBook2, $testBook1), $books->getData(), 'findPks() returns an array of model objects corresponding to the pks'); - } - - public function testFindPkCompositeKey() - { - BookstoreDataPopulator::depopulate(); - - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRel = $c->findPk(array(1, 2)); - $this->assertNull($bookListRel, 'findPk() returns null when the composite primary key is not found'); - - Propel::enableInstancePooling(); - BookstoreDataPopulator::populate(); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - // retrieve the test data - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRelTest = $c->findOne(); - $pk = $bookListRelTest->getPrimaryKey(); - - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRel = $c->findPk($pk); - $this->assertEquals($bookListRelTest, $bookListRel, 'findPk() can find objects with composite primary keys'); - } - - /** - * @expectedException PropelException - */ - public function testFindPksCompositeKey() - { - $c = new ModelCriteria('bookstore', 'BookListRel'); - $bookListRel = $c->findPks(array(array(1, 2))); - - } - - public function testFindBy() - { - try { - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findBy('Foo', 'Bar'); - $this->fail('findBy() throws an exception when called on an unknown column name'); - } catch (PropelException $e) { - $this->assertTrue(true, 'findBy() throws an exception when called on an unknown column name'); - } - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findBy('Title', 'Don Juan', $con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findBy() adds simple column conditions'); - $this->assertTrue($books instanceof PropelCollection, 'findBy() issues a find()'); - $this->assertEquals(1, count($books), 'findBy() adds simple column conditions'); - $book = $books->shift(); - $this->assertTrue($book instanceof Book, 'findBy() returns an array of Model objects by default'); - $this->assertEquals('Don Juan', $book->getTitle(), 'findBy() returns the model objects matching the query'); - } - - public function testFindByArray() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findByArray(array('Title' => 'Don Juan', 'ISBN' => 12345), $con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' AND book.ISBN=12345"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByArray() adds multiple column conditions'); - } - - public function testFindOneBy() - { - try { - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findOneBy('Foo', 'Bar'); - $this->fail('findOneBy() throws an exception when called on an unknown column name'); - } catch (PropelException $e) { - $this->assertTrue(true, 'findOneBy() throws an exception when called on an unknown column name'); - } - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findOneBy('Title', 'Don Juan', $con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneBy() adds simple column conditions'); - $this->assertTrue($book instanceof Book, 'findOneBy() returns a Model object by default'); - $this->assertEquals('Don Juan', $book->getTitle(), 'findOneBy() returns the model object matching the query'); - } - - public function testFindOneByArray() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findOneByArray(array('Title' => 'Don Juan', 'ISBN' => 12345), $con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' AND book.ISBN=12345 LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneBy() adds multiple column conditions'); - } - - public function testCount() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $nbBooks = $c->count(); - $this->assertTrue(is_int($nbBooks), 'count() returns an integer'); - $this->assertEquals(0, $nbBooks, 'count() returns 0 when the query returns no result'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'Neal'); - $nbBooks = $c->count(); - $this->assertTrue(is_int($nbBooks), 'count() returns an integer'); - $this->assertEquals(1, $nbBooks, 'count() returns the number of results in the query'); - } - - public function testPaginate() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->join('b.Author a'); - $c->where('a.FirstName = ?', 'Neal'); - $books = $c->paginate(1, 5); - $this->assertTrue($books instanceof PropelModelPager, 'paginate() returns a PropelModelPager'); - $this->assertEquals(1, count($books), 'paginate() returns a countable pager with the correct count'); - foreach ($books as $book) { - $this->assertEquals('Neal', $book->getAuthor()->getFirstName(), 'paginate() returns an iterable pager'); - } - } - - public function testDelete() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $c = new ModelCriteria('bookstore', 'Book'); - try { - $nbBooks = $c->delete(); - $this->fail('delete() throws an exception when called on an empty Criteria'); - } catch (PropelException $e) { - $this->assertTrue(true, 'delete() throws an exception when called on an empty Criteria'); - } - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $nbBooks = $c->delete(); - $this->assertTrue(is_int($nbBooks), 'delete() returns an integer'); - $this->assertEquals(0, $nbBooks, 'delete() returns 0 when the query deleted no rows'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->delete(); - $this->assertTrue(is_int($nbBooks), 'delete() returns an integer'); - $this->assertEquals(1, $nbBooks, 'delete() returns the number of the deleted rows'); - - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->count(); - $this->assertEquals(3, $nbBooks, 'delete() deletes rows in the database'); - } - - public function testDeleteUsingTableAlias() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', false); - $c->where('b.Title = ?', 'foo'); - $c->delete(); - $expectedSQL = "DELETE FROM `book` WHERE book.TITLE = 'foo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'delete() also works on tables with table alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->where('b.Title = ?', 'foo'); - $c->delete(); - $expectedSQL = "DELETE b FROM `book` AS b WHERE b.TITLE = 'foo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'delete() also works on tables with true table alias'); - } - - public function testDeleteAll() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->deleteAll(); - $this->assertTrue(is_int($nbBooks), 'deleteAll() returns an integer'); - $this->assertEquals(4, $nbBooks, 'deleteAll() returns the number of deleted rows'); - - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->deleteAll(); - $this->assertEquals(4, $nbBooks, 'deleteAll() ignores conditions on the criteria'); - } - - public function testUpdate() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::depopulate($con); - BookstoreDataPopulator::populate($con); - - $count = $con->getQueryCount(); - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->update(array('Title' => 'foo'), $con); - $this->assertEquals(4, $nbBooks, 'update() returns the number of updated rows'); - $this->assertEquals($count + 1, $con->getQueryCount(), 'update() updates all the objects in one query by default'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $nbBooks = $c->count(); - $this->assertEquals(4, $nbBooks, 'update() updates all records by default'); - - BookstoreDataPopulator::depopulate($con); - BookstoreDataPopulator::populate($con); - - $count = $con->getQueryCount(); - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->update(array('ISBN' => '3456'), $con); - $this->assertEquals(1, $nbBooks, 'update() updates only the records matching the criteria'); - $this->assertEquals($count + 1, $con->getQueryCount(), 'update() updates all the objects in one query by default'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $book = $c->findOne(); - $this->assertEquals('3456', $book->getISBN(), 'update() updates only the records matching the criteria'); - } - - public function testUpdateUsingTableAlias() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', false); - $c->where('b.Title = ?', 'foo'); - $c->update(array('Title' => 'foo2'), $con); - $expectedSQL = "UPDATE `book` SET `TITLE`='foo2' WHERE book.TITLE = 'foo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'update() also works on tables with table alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('b', true); - $c->where('b.Title = ?', 'foo'); - $c->update(array('Title' => 'foo2'), $con); - $expectedSQL = "UPDATE `book` `b` SET `TITLE`='foo2' WHERE b.TITLE = 'foo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'update() also works on tables with true table alias'); - } - - public function testUpdateOneByOne() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BookstoreDataPopulator::depopulate($con); - BookstoreDataPopulator::populate($con); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - $count = $con->getQueryCount(); - $c = new ModelCriteria('bookstore', 'Book'); - $nbBooks = $c->update(array('Title' => 'foo'), $con, true); - $this->assertEquals(4, $nbBooks, 'update() returns the number of updated rows'); - $this->assertEquals($count + 1 + 4, $con->getQueryCount(), 'update() updates the objects one by one when called with true as last parameter'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'foo'); - $nbBooks = $c->count(); - $this->assertEquals(4, $nbBooks, 'update() updates all records by default'); - - BookstoreDataPopulator::depopulate($con); - BookstoreDataPopulator::populate($con); - - // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->find(); - foreach ($books as $book) { - $book->save(); - } - - $count = $con->getQueryCount(); - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $nbBooks = $c->update(array('ISBN' => '3456'), $con, true); - $this->assertEquals(1, $nbBooks, 'update() updates only the records matching the criteria'); - $this->assertEquals($count + 1 + 1, $con->getQueryCount(), 'update() updates the objects one by one when called with true as last parameter'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->where('b.Title = ?', 'Don Juan'); - $book = $c->findOne(); - $this->assertEquals('3456', $book->getISBN(), 'update() updates only the records matching the criteria'); - } - - public static function conditionsForTestGetRelationName() - { - return array( - array('Author', 'Author'), - array('Book.Author', 'Author'), - array('Author.Book', 'Book'), - array('Book.Author a', 'a'), - ); - } - - /** - * @dataProvider conditionsForTestGetRelationName - */ - public function testGetRelationName($relation, $relationName) - { - $this->assertEquals($relationName, ModelCriteria::getrelationName($relation)); - } - - public function testMagicJoin() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->leftJoin('b.Author a'); - $c->where('a.FirstName = ?', 'Leo'); - $books = $c->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoin($x) is turned into join($x, Criteria::LEFT_JOIN)'); - - $books = BookQuery::create() - ->leftJoinAuthor('a') - ->where('a.FirstName = ?', 'Leo') - ->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoinX() is turned into join($x, Criteria::LEFT_JOIN)'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->innerJoin('b.Author a'); - $c->where('a.FirstName = ?', 'Leo'); - $books = $c->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` INNER JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'innerJoin($x) is turned into join($x, Criteria::INNER_JOIN)'); - - $books = BookQuery::create() - ->innerJoinAuthor('a') - ->where('a.FirstName = ?', 'Leo') - ->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` INNER JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'innerJoinX() is turned into join($x, Criteria::INNER_JOIN)'); - - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->rightJoin('b.Author a'); - $c->where('a.FirstName = ?', 'Leo'); - $books = $c->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` RIGHT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'rightJoin($x) is turned into join($x, Criteria::RIGHT_JOIN)'); - - $books = BookQuery::create() - ->rightJoinAuthor('a') - ->where('a.FirstName = ?', 'Leo') - ->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` RIGHT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE a.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'rightJoinX() is turned into join($x, Criteria::RIGHT_JOIN)'); - - $books = BookQuery::create() - ->leftJoinAuthor() - ->where('Author.FirstName = ?', 'Leo') - ->findOne($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE author.FIRST_NAME = 'Leo' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoinX() is turned into join($x, Criteria::LEFT_JOIN)'); - } - - public function testMagicJoinWith() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->leftJoinWith('Book.Author a'); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - 'a.ID', - 'a.FIRST_NAME', - 'a.LAST_NAME', - 'a.EMAIL', - 'a.AGE' - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'leftJoinWith() adds the join with the alias'); - $joins = $c->getJoins(); - $join = $joins['a']; - $this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'leftJoinWith() adds a LEFT JOIN'); - } - - public function testMagicJoinWithRelation() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->joinWithAuthor(); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWithXXX() adds the join with the XXX relation'); - $joins = $c->getJoins(); - $join = $joins['Author']; - $this->assertEquals(Criteria::INNER_JOIN, $join->getJoinType(), 'joinWithXXX() adds an INNER JOIN'); - } - - public function testMagicJoinWithTypeAndRelation() - { - $c = new TestableModelCriteria('bookstore', 'Book'); - $c->leftJoinWithAuthor(); - $expectedColumns = array( - BookPeer::ID, - BookPeer::TITLE, - BookPeer::ISBN, - BookPeer::PRICE, - BookPeer::PUBLISHER_ID, - BookPeer::AUTHOR_ID, - AuthorPeer::ID, - AuthorPeer::FIRST_NAME, - AuthorPeer::LAST_NAME, - AuthorPeer::EMAIL, - AuthorPeer::AGE - ); - $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'leftJoinWithXXX() adds the join with the XXX relation'); - $joins = $c->getJoins(); - $join = $joins['Author']; - $this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'leftJoinWithXXX() adds an INNER JOIN'); - } - - public function testMagicFind() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findByTitle('Don Juan'); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)'); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->findByTitleAndISBN('Don Juan', 1234); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' AND book.ISBN=1234"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX,YYY), $value)'); - - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findOneByTitle('Don Juan'); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneByXXX($value) is turned into findOneBy(XXX, $value)'); - - $c = new ModelCriteria('bookstore', 'Book'); - $book = $c->findOneByTitleAndISBN('Don Juan', 1234); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan' AND book.ISBN=1234 LIMIT 1"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneByXXX($value) is turned into findOneBy(XXX, $value)'); - } - - public function testMagicFilterBy() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->filterByTitle('Don Juan')->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE='Don Juan'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'filterByXXX($value) is turned into filterBy(XXX, $value)'); - } - - public function testMagicOrderBy() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->orderByTitle()->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` ORDER BY book.TITLE ASC"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'orderByXXX() is turned into orderBy(XXX)'); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->orderByTitle(Criteria::DESC)->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` ORDER BY book.TITLE DESC"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'orderByXXX($direction) is turned into orderBy(XXX, $direction)'); - } - - public function testMagicGroupBy() - { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - - $c = new ModelCriteria('bookstore', 'Book'); - $books = $c->groupByTitle()->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` GROUP BY book.TITLE"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'groupByXXX() is turned into groupBy(XXX)'); - } - - public function testUseQuery() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->thisIsMe = true; - $c->where('b.Title = ?', 'foo'); - $c->setOffset(10); - $c->leftJoin('b.Author'); - - $c2 = $c->useQuery('Author'); - $this->assertTrue($c2 instanceof AuthorQuery, 'useQuery() returns a secondary Criteria'); - $this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria'); - $c2->where('Author.FirstName = ?', 'john'); - $c2->limit(5); - - $c = $c2->endUse(); - $this->assertTrue($c->thisIsMe, 'endUse() returns the Primary Criteria'); - $this->assertEquals('Book', $c->getModelName(), 'endUse() returns the Primary Criteria'); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE book.TITLE = 'foo' AND author.FIRST_NAME = 'john' LIMIT 10, 5"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria'); - } - - public function testUseQueryAlias() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->thisIsMe = true; - $c->where('b.Title = ?', 'foo'); - $c->setOffset(10); - $c->leftJoin('b.Author a'); - - $c2 = $c->useQuery('a'); - $this->assertTrue($c2 instanceof AuthorQuery, 'useQuery() returns a secondary Criteria'); - $this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria'); - $this->assertEquals(array('a' => 'author'), $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly'); - $c2->where('a.FirstName = ?', 'john'); - $c2->limit(5); - - $c = $c2->endUse(); - $this->assertTrue($c->thisIsMe, 'endUse() returns the Primary Criteria'); - $this->assertEquals('Book', $c->getModelName(), 'endUse() returns the Primary Criteria'); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE book.TITLE = 'foo' AND a.FIRST_NAME = 'john' LIMIT 10, 5"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria'); - } - - public function testUseQueryCustomClass() - { - $c = new ModelCriteria('bookstore', 'Book', 'b'); - $c->thisIsMe = true; - $c->where('b.Title = ?', 'foo'); - $c->setLimit(10); - $c->leftJoin('b.Author a'); - - $c2 = $c->useQuery('a', 'ModelCriteriaForUseQuery'); - $this->assertTrue($c2 instanceof ModelCriteriaForUseQuery, 'useQuery() returns a secondary Criteria with the custom class'); - $c2->withNoName(); - $c = $c2->endUse(); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` LEFT JOIN author a ON (book.AUTHOR_ID=a.ID) WHERE book.TITLE = 'foo' AND a.FIRST_NAME IS NOT NULL AND a.LAST_NAME IS NOT NULL LIMIT 10"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a custom secondary criteria'); - } - - public function testUseQueryJoinWithFind() - { - $c = new ModelCriteria('bookstore', 'Review'); - $c->joinWith('Book'); - - $c2 = $c->useQuery('Book'); - - $joins = $c->getJoins(); - $this->assertEquals($c->getPreviousJoin(), null, 'The default value for previousJoin remains null'); - $this->assertEquals($c2->getPreviousJoin(), $joins['Book'], 'useQuery() sets the previousJoin'); - - // join Book with Author, which is possible since previousJoin is set, which makes resolving of relations possible during hydration - $c2->joinWith('Author'); - - $c = $c2->endUse(); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT review.ID, review.REVIEWED_BY, review.REVIEW_DATE, review.RECOMMENDED, review.STATUS, review.BOOK_ID, book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, author.ID, author.FIRST_NAME, author.LAST_NAME, author.EMAIL, author.AGE FROM `review` INNER JOIN book ON (review.BOOK_ID=book.ID) INNER JOIN author ON (book.AUTHOR_ID=author.ID)"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and joinWith() can be used together and form a correct query'); - } - - public function testUseQueryCustomRelationPhpName() - { - $c = new ModelCriteria('bookstore', 'BookstoreContest'); - $c->leftJoin('BookstoreContest.Work'); - $c2 = $c->useQuery('Work'); - $this->assertTrue($c2 instanceof BookQuery, 'useQuery() returns a secondary Criteria'); - $this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria'); - //$this->assertEquals(array('a' => 'author'), $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly'); - $c2->where('Work.Title = ?', 'War And Peace'); - - $c = $c2->endUse(); - $this->assertEquals('BookstoreContest', $c->getModelName(), 'endUse() returns the Primary Criteria'); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT bookstore_contest.BOOKSTORE_ID, bookstore_contest.CONTEST_ID, bookstore_contest.PRIZE_BOOK_ID FROM `bookstore_contest` LEFT JOIN book ON (bookstore_contest.PRIZE_BOOK_ID=book.ID) WHERE book.TITLE = 'War And Peace'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria'); - } - - public function testUseQueryCustomRelationPhpNameAndAlias() - { - $c = new ModelCriteria('bookstore', 'BookstoreContest'); - $c->leftJoin('BookstoreContest.Work w'); - $c2 = $c->useQuery('w'); - $this->assertTrue($c2 instanceof BookQuery, 'useQuery() returns a secondary Criteria'); - $this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria'); - //$this->assertEquals(array('a' => 'author'), $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly'); - $c2->where('w.Title = ?', 'War And Peace'); - - $c = $c2->endUse(); - $this->assertEquals('BookstoreContest', $c->getModelName(), 'endUse() returns the Primary Criteria'); - - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - $c->find($con); - $expectedSQL = "SELECT bookstore_contest.BOOKSTORE_ID, bookstore_contest.CONTEST_ID, bookstore_contest.PRIZE_BOOK_ID FROM `bookstore_contest` LEFT JOIN book w ON (bookstore_contest.PRIZE_BOOK_ID=w.ID) WHERE w.TITLE = 'War And Peace'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria'); - } - - public function testMergeWithJoins() - { - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c1->leftJoin('b.Author a'); - $c2 = new ModelCriteria('bookstore', 'Author'); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(1, count($joins), 'mergeWith() does not remove an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered)', $joins['a']->toString(), 'mergeWith() does not remove an existing join'); - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2->leftJoin('b.Author a'); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(1, count($joins), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered)', $joins['a']->toString(), 'mergeWith() merge joins to an empty join'); - - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c1->leftJoin('b.Author a'); - $c2 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2->innerJoin('b.Publisher p'); - $c1->mergeWith($c2); - $joins = $c1->getJoins(); - $this->assertEquals(2, count($joins), 'mergeWith() merge joins to an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered)', $joins['a']->toString(), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('INNER JOIN : book.PUBLISHER_ID=p.ID(ignoreCase not considered)', $joins['p']->toString(), 'mergeWith() merge joins to an empty join'); - } - - public function testMergeWithWiths() - { - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c1->leftJoinWith('b.Author a'); - $c2 = new ModelCriteria('bookstore', 'Author'); - $c1->mergeWith($c2); - $with = $c1->getWith(); - $this->assertEquals(1, count($with), 'mergeWith() does not remove an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered) tableMap: AuthorTableMap relationMap: Author previousJoin: null relationAlias: a', $with['a']->__toString(), 'mergeWith() does not remove an existing join'); - - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2->leftJoinWith('b.Author a'); - $c1->mergeWith($c2); - $with = $c1->getWith(); - $this->assertEquals(1, count($with), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered) tableMap: AuthorTableMap relationMap: Author previousJoin: null relationAlias: a', $with['a']->__toString(), 'mergeWith() merge joins to an empty join'); - - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c1->leftJoinWith('b.Author a'); - $c2 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2->innerJoinWith('b.Publisher p'); - $c1->mergeWith($c2); - $with = $c1->getWith(); - $this->assertEquals(2, count($with), 'mergeWith() merge joins to an existing join'); - $this->assertEquals('LEFT JOIN : book.AUTHOR_ID=a.ID(ignoreCase not considered) tableMap: AuthorTableMap relationMap: Author previousJoin: null relationAlias: a', $with['a']->__toString(), 'mergeWith() merge joins to an empty join'); - $this->assertEquals('INNER JOIN : book.PUBLISHER_ID=p.ID(ignoreCase not considered) tableMap: PublisherTableMap relationMap: Publisher previousJoin: null relationAlias: p', $with['p']->__toString(), 'mergeWith() merge joins to an empty join'); - - } - - public function testGetAliasedColName() - { - $c = new ModelCriteria('bookstore', 'Book'); - $this->assertEquals(BookPeer::TITLE, $c->getAliasedColName(BookPeer::TITLE), 'getAliasedColName() returns the input when the table has no alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('foo'); - $this->assertEquals(BookPeer::TITLE, $c->getAliasedColName(BookPeer::TITLE), 'getAliasedColName() returns the input when the table has a query alias'); - - $c = new ModelCriteria('bookstore', 'Book'); - $c->setModelAlias('foo', true); - $this->assertEquals('foo.TITLE', $c->getAliasedColName(BookPeer::TITLE), 'getAliasedColName() returns the column name with table alias when the table has a true alias'); - } - - public function testAddUsingAliasNoAlias() - { - $c1 = new ModelCriteria('bookstore', 'Book'); - $c1->addUsingAlias(BookPeer::TITLE, 'foo'); - $c2 = new ModelCriteria('bookstore', 'Book'); - $c2->add(BookPeer::TITLE, 'foo'); - $this->assertEquals($c2, $c1, 'addUsingalias() translates to add() when the table has no alias'); - } - - public function testAddUsingAliasQueryAlias() - { - $c1 = new ModelCriteria('bookstore', 'Book', 'b'); - $c1->addUsingAlias(BookPeer::TITLE, 'foo'); - $c2 = new ModelCriteria('bookstore', 'Book', 'b'); - $c2->add(BookPeer::TITLE, 'foo'); - $this->assertEquals($c2, $c1, 'addUsingalias() translates the colname using the table alias before calling add() when the table has a true alias'); - } - - public function testAddUsingAliasTrueAlias() - { - $c1 = new ModelCriteria('bookstore', 'Book'); - $c1->setModelAlias('b', true); - $c1->addUsingAlias(BookPeer::TITLE, 'foo'); - $c2 = new ModelCriteria('bookstore', 'Book'); - $c2->setModelAlias('b', true); - $c2->add('b.TITLE', 'foo'); - $this->assertEquals($c2, $c1, 'addUsingalias() translates to add() when the table has a true alias'); - } - - public function testAddUsingAliasTwice() - { - $c1 = new ModelCriteria('bookstore', 'Book'); - $c1->addUsingAlias(BookPeer::TITLE, 'foo'); - $c1->addUsingAlias(BookPeer::TITLE, 'bar'); - $c2 = new ModelCriteria('bookstore', 'Book'); - $c2->add(BookPeer::TITLE, 'foo'); - $c2->addAnd(BookPeer::TITLE, 'bar'); - $this->assertEquals($c2, $c1, 'addUsingalias() translates to addAnd() when the table already has a condition on the column'); - } - - public function testAddUsingAliasTrueAliasTwice() - { - $c1 = new ModelCriteria('bookstore', 'Book'); - $c1->setModelAlias('b', true); - $c1->addUsingAlias(BookPeer::TITLE, 'foo'); - $c1->addUsingAlias(BookPeer::TITLE, 'bar'); - $c2 = new ModelCriteria('bookstore', 'Book'); - $c2->setModelAlias('b', true); - $c2->add('b.TITLE', 'foo'); - $c2->addAnd('b.TITLE', 'bar'); - $this->assertEquals($c2, $c1, 'addUsingalias() translates to addAnd() when the table already has a condition on the column'); - } - - public function testClone() - { - $bookQuery1 = BookQuery::create() - ->filterByPrice(1); - $bookQuery2 = clone $bookQuery1; - $bookQuery2 - ->filterByPrice(2); - $params = array(); - $sql = BasePeer::createSelectSql($bookQuery1, $params); - $this->assertEquals('SELECT FROM `book` WHERE book.PRICE=:p1', $sql, 'conditions applied on a cloned query don\'t get applied on the original query'); - } -} - -class TestableModelCriteria extends ModelCriteria -{ - public $joins = array(); - - public function replaceNames(&$clause) - { - return parent::replaceNames($clause); - } - -} - -class ModelCriteriaForUseQuery extends ModelCriteria -{ - public function __construct($dbName = 'bookstore', $modelName = 'Author', $modelAlias = null) - { - parent::__construct($dbName, $modelName, $modelAlias); - } - - public function withNoName() - { - return $this - ->filterBy('FirstName', null, Criteria::ISNOTNULL) - ->where($this->getModelAliasOrName() . '.LastName IS NOT NULL'); - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelJoinTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelJoinTest.php deleted file mode 100644 index afc89ff6d..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelJoinTest.php +++ /dev/null @@ -1,85 +0,0 @@ -assertNull($join->getTableMap(), 'getTableMap() returns null as long as no table map is set'); - - $tmap = new TableMap(); - $tmap->foo = 'bar'; - - $join->setTableMap($tmap); - $this->assertEquals($tmap, $join->getTableMap(), 'getTableMap() returns the TableMap previously set by setTableMap()'); - } - - public function testSetRelationMap() - { - $join = new ModelJoin(); - $this->assertNull($join->getRelationMap(), 'getRelationMap() returns null as long as no relation map is set'); - $bookTable = BookPeer::getTableMap(); - $relationMap = $bookTable->getRelation('Author'); - $join->setRelationMap($relationMap); - $this->assertEquals($relationMap, $join->getRelationMap(), 'getRelationMap() returns the RelationMap previously set by setRelationMap()'); - } - - public function testSetRelationMapDefinesJoinColumns() - { - $bookTable = BookPeer::getTableMap(); - $join = new ModelJoin(); - $join->setTableMap($bookTable); - $join->setRelationMap($bookTable->getRelation('Author')); - $this->assertEquals(array(BookPeer::AUTHOR_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns'); - $this->assertEquals(array(AuthorPeer::ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns'); - } - - public function testSetRelationMapLeftAlias() - { - $bookTable = BookPeer::getTableMap(); - $join = new ModelJoin(); - $join->setTableMap($bookTable); - $join->setRelationMap($bookTable->getRelation('Author'), 'b'); - $this->assertEquals(array('b.AUTHOR_ID'), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns using the left table alias'); - $this->assertEquals(array(AuthorPeer::ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns'); - } - - public function testSetRelationMapRightAlias() - { - $bookTable = BookPeer::getTableMap(); - $join = new ModelJoin(); - $join->setTableMap($bookTable); - $join->setRelationMap($bookTable->getRelation('Author'), null, 'a'); - $this->assertEquals(array(BookPeer::AUTHOR_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns'); - $this->assertEquals(array('a.ID'), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns using the right table alias'); - } - - public function testSetRelationMapComposite() - { - $table = ReaderFavoritePeer::getTableMap(); - $join = new ModelJoin(); - $join->setTableMap($table); - $join->setRelationMap($table->getRelation('BookOpinion')); - $this->assertEquals(array(ReaderFavoritePeer::BOOK_ID, ReaderFavoritePeer::READER_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns for composite relationships'); - $this->assertEquals(array(BookOpinionPeer::BOOK_ID, BookOpinionPeer::READER_ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns for composite relationships'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelWithTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelWithTest.php deleted file mode 100644 index ffe5e8fe6..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/ModelWithTest.php +++ /dev/null @@ -1,183 +0,0 @@ -joinAuthor(); - $joins = $q->getJoins(); - $join = $joins['Author']; - $with = new ModelWith($join); - $this->assertEquals($with->getModelName(), 'Author', 'A ModelWith computes the model name from the join'); - $this->assertEquals($with->getModelPeerName(), 'AuthorPeer', 'A ModelWith computes the model peer name from the join'); - } - - public function testModelNameOneToMany() - { - $q = AuthorQuery::create() - ->joinBook(); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertEquals($with->getModelName(), 'Book', 'A ModelWith computes the model peer name from the join'); - $this->assertEquals($with->getModelPeerName(), 'BookPeer', 'A ModelWith computes the model peer name from the join'); - } - - public function testModelNameAlias() - { - $q = BookQuery::create() - ->joinAuthor('a'); - $joins = $q->getJoins(); - $join = $joins['a']; - $with = new ModelWith($join); - $this->assertEquals($with->getModelName(), 'Author', 'A ModelWith computes the model peer name from the join'); - $this->assertEquals($with->getModelPeerName(), 'AuthorPeer', 'A ModelWith computes the model peer name from the join'); - } - - public function testRelationManyToOne() - { - $q = BookQuery::create() - ->joinAuthor(); - $joins = $q->getJoins(); - $join = $joins['Author']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelationMethod(), 'setAuthor', 'A ModelWith computes the relation method from the join'); - $this->assertEquals($with->getRelationName(), 'Author', 'A ModelWith computes the relation name from the join'); - $this->assertFalse($with->isAdd(), 'A ModelWith computes the relation cardinality from the join'); - } - - public function testRelationOneToMany() - { - $q = AuthorQuery::create() - ->joinBook(); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelationMethod(), 'addBook', 'A ModelWith computes the relation method from the join'); - $this->assertEquals($with->getRelationName(), 'Books', 'A ModelWith computes the relation name from the join'); - $this->assertTrue($with->isAdd(), 'A ModelWith computes the relation cardinality from the join'); - } - - public function testRelationOneToOne() - { - $q = BookstoreEmployeeQuery::create() - ->joinBookstoreEmployeeAccount(); - $joins = $q->getJoins(); - $join = $joins['BookstoreEmployeeAccount']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelationMethod(), 'setBookstoreEmployeeAccount', 'A ModelWith computes the relation method from the join'); - $this->assertEquals($with->getRelationName(), 'BookstoreEmployeeAccount', 'A ModelWith computes the relation name from the join'); - $this->assertFalse($with->isAdd(), 'A ModelWith computes the relation cardinality from the join'); - } - - public function testIsPrimary() - { - $q = AuthorQuery::create() - ->joinBook(); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary'); - - $q = BookQuery::create() - ->joinAuthor() - ->joinReview(); - $joins = $q->getJoins(); - $join = $joins['Review']; - $with = new ModelWith($join); - $this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary'); - - $q = AuthorQuery::create() - ->join('Author.Book') - ->join('Book.Publisher'); - $joins = $q->getJoins(); - $join = $joins['Publisher']; - $with = new ModelWith($join); - $this->assertFalse($with->isPrimary(), 'A ModelWith initialized from a non-primary join is not primary'); - } - - public function testGetRelatedClass() - { - $q = AuthorQuery::create() - ->joinBook(); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join has a null related class'); - - $q = AuthorQuery::create('a') - ->joinBook(); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join with alias has a null related class'); - - $q = AuthorQuery::create() - ->joinBook('b'); - $joins = $q->getJoins(); - $join = $joins['b']; - $with = new ModelWith($join); - $this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join with alias has a null related class'); - - $q = AuthorQuery::create() - ->join('Author.Book') - ->join('Book.Publisher'); - $joins = $q->getJoins(); - $join = $joins['Publisher']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class'); - - $q = ReviewQuery::create() - ->join('Review.Book') - ->join('Book.Author') - ->join('Book.Publisher'); - $joins = $q->getJoins(); - $join = $joins['Publisher']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class'); - - $q = ReviewQuery::create() - ->join('Review.Book') - ->join('Book.BookOpinion') - ->join('BookOpinion.BookReader'); - $joins = $q->getJoins(); - $join = $joins['BookOpinion']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class'); - $join = $joins['BookReader']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'BookOpinion', 'A ModelWith uses the previous join relation name as related class'); - - $q = BookReaderQuery::create() - ->join('BookReader.BookOpinion') - ->join('BookOpinion.Book') - ->join('Book.Author'); - $joins = $q->getJoins(); - $join = $joins['Book']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'BookOpinion', 'A ModelWith uses the previous join relation name as related class'); - $join = $joins['Author']; - $with = new ModelWith($join); - $this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/query/PropelQueryTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/query/PropelQueryTest.php deleted file mode 100644 index 5ef619da1..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/query/PropelQueryTest.php +++ /dev/null @@ -1,63 +0,0 @@ -assertEquals($expected, $q, 'from() returns a Model query instance based on the model name'); - - $q = PropelQuery::from('Book b'); - $expected = new BookQuery(); - $expected->setModelAlias('b'); - $this->assertEquals($expected, $q, 'from() sets the model alias if found after the blank'); - - $q = PropelQuery::from('myBook'); - $expected = new myBookQuery(); - $this->assertEquals($expected, $q, 'from() can find custom query classes'); - - try { - $q = PropelQuery::from('Foo'); - $this->fail('PropelQuery::from() throws an exception when called on a non-existing query class'); - } catch (PropelException $e) { - $this->assertTrue(true, 'PropelQuery::from() throws an exception when called on a non-existing query class'); - } - } - - public function testQuery() - { - BookstoreDataPopulator::depopulate(); - BookstoreDataPopulator::populate(); - - $book = PropelQuery::from('Book b') - ->where('b.Title like ?', 'Don%') - ->orderBy('b.ISBN', 'desc') - ->findOne(); - $this->assertTrue($book instanceof Book); - $this->assertEquals('Don Juan', $book->getTitle()); - - } -} - -class myBookQuery extends BookQuery -{ -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerExceptionsTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerExceptionsTest.php deleted file mode 100644 index e3d56f2a6..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerExceptionsTest.php +++ /dev/null @@ -1,94 +0,0 @@ -add(BookPeer::ID, 12, ' BAD SQL'); - BookPeer::addSelectColumns($c); - BasePeer::doSelect($c); - } catch (PropelException $e) { - $this->assertContains('[SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - - public function testDoCount() - { - try { - $c = new Criteria(); - $c->add(BookPeer::ID, 12, ' BAD SQL'); - BookPeer::addSelectColumns($c); - BasePeer::doCount($c); - } catch (PropelException $e) { - $this->assertContains('[SELECT COUNT(*) FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - - public function testDoDelete() - { - try { - $c = new Criteria(); - $c->setPrimaryTableName(BookPeer::TABLE_NAME); - $c->add(BookPeer::ID, 12, ' BAD SQL'); - BasePeer::doDelete($c, Propel::getConnection()); - } catch (PropelException $e) { - $this->assertContains('[DELETE FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - - public function testDoDeleteAll() - { - try { - BasePeer::doDeleteAll('BAD TABLE', Propel::getConnection()); - } catch (PropelException $e) { - $this->assertContains('[DELETE FROM `BAD` `TABLE`]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - - public function testDoUpdate() - { - try { - $c1 = new Criteria(); - $c1->setPrimaryTableName(BookPeer::TABLE_NAME); - $c1->add(BookPeer::ID, 12, ' BAD SQL'); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'Foo'); - BasePeer::doUpdate($c1, $c2, Propel::getConnection()); - } catch (PropelException $e) { - $this->assertContains('[UPDATE `book` SET `TITLE`=:p1 WHERE book.ID BAD SQL:p2]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - - public function testDoInsert() - { - try { - $c = new Criteria(); - $c->setPrimaryTableName(BookPeer::TABLE_NAME); - $c->add(BookPeer::AUTHOR_ID, 'lkhlkhj'); - BasePeer::doInsert($c, Propel::getConnection()); - } catch (PropelException $e) { - $this->assertContains('[INSERT INTO `book` (`AUTHOR_ID`) VALUES (:p1)]', $e->getMessage(), 'SQL query is written in the exception message'); - } - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerTest.php deleted file mode 100644 index cb8772ee5..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/BasePeerTest.php +++ /dev/null @@ -1,413 +0,0 @@ - - * @package runtime.util - */ -class BasePeerTest extends BookstoreTestBase -{ - - /** - * @link http://propel.phpdb.org/trac/ticket/425 - */ - public function testMultipleFunctionInCriteria() - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - try { - $c = new Criteria(); - $c->setDistinct(); - if ($db instanceof DBPostgres) { - $c->addSelectColumn("substring(".BookPeer::TITLE." from position('Potter' in ".BookPeer::TITLE.")) AS col"); - } else { - $this->markTestSkipped(); - } - $stmt = BookPeer::doSelectStmt( $c ); - } catch (PropelException $x) { - $this->fail("Paring of nested functions failed: " . $x->getMessage()); - } - } - - public function testNeedsSelectAliases() - { - $c = new Criteria(); - $this->assertFalse(BasePeer::needsSelectAliases($c), 'Empty Criterias dont need aliases'); - - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with distinct column names dont need aliases'); - - $c = new Criteria(); - BookPeer::addSelectColumns($c); - $this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with only the columns of a model dont need aliases'); - - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(AuthorPeer::ID); - $this->assertTrue(BasePeer::needsSelectAliases($c), 'Criterias with common column names do need aliases'); - } - - public function testTurnSelectColumnsToAliases() - { - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::ID); - BasePeer::turnSelectColumnsToAliases($c1); - - $c2 = new Criteria(); - $c2->addAsColumn('book_ID', BookPeer::ID); - $this->assertTrue($c1->equals($c2)); - } - - public function testTurnSelectColumnsToAliasesPreservesAliases() - { - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::ID); - $c1->addAsColumn('foo', BookPeer::TITLE); - BasePeer::turnSelectColumnsToAliases($c1); - - $c2 = new Criteria(); - $c2->addAsColumn('book_ID', BookPeer::ID); - $c2->addAsColumn('foo', BookPeer::TITLE); - $this->assertTrue($c1->equals($c2)); - } - - public function testTurnSelectColumnsToAliasesExisting() - { - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::ID); - $c1->addAsColumn('book_ID', BookPeer::ID); - BasePeer::turnSelectColumnsToAliases($c1); - - $c2 = new Criteria(); - $c2->addAsColumn('book_ID_1', BookPeer::ID); - $c2->addAsColumn('book_ID', BookPeer::ID); - $this->assertTrue($c1->equals($c2)); - } - - public function testTurnSelectColumnsToAliasesDuplicate() - { - $c1 = new Criteria(); - $c1->addSelectColumn(BookPeer::ID); - $c1->addSelectColumn(BookPeer::ID); - BasePeer::turnSelectColumnsToAliases($c1); - - $c2 = new Criteria(); - $c2->addAsColumn('book_ID', BookPeer::ID); - $c2->addAsColumn('book_ID_1', BookPeer::ID); - $this->assertTrue($c1->equals($c2)); - } - - public function testDoCountDuplicateColumnName() - { - $con = Propel::getConnection(); - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID); - $c->addSelectColumn(AuthorPeer::ID); - $c->setLimit(3); - try { - $count = BasePeer::doCount($c, $con); - } catch (Exception $e) { - $this->fail('doCount() cannot deal with a criteria selecting duplicate column names '); - } - } - - public function testCreateSelectSqlPart() - { - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addAsColumn('book_ID', BookPeer::ID); - $fromClause = array(); - $selectSql = BasePeer::createSelectSqlPart($c, $fromClause); - $this->assertEquals('SELECT book.ID, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() returns a SQL SELECT clause with both select and as columns'); - $this->assertEquals(array('book'), $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause'); - } - - public function testCreateSelectSqlPartSelectModifier() - { - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addAsColumn('book_ID', BookPeer::ID); - $c->setDistinct(); - $fromClause = array(); - $selectSql = BasePeer::createSelectSqlPart($c, $fromClause); - $this->assertEquals('SELECT DISTINCT book.ID, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() includes the select modifiers in the SELECT clause'); - $this->assertEquals(array('book'), $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause'); - } - - public function testCreateSelectSqlPartAliasAll() - { - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addAsColumn('book_ID', BookPeer::ID); - $fromClause = array(); - $selectSql = BasePeer::createSelectSqlPart($c, $fromClause, true); - $this->assertEquals('SELECT book.ID AS book_ID_1, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() aliases all columns if passed true as last parameter'); - $this->assertEquals(array(), $fromClause, 'createSelectSqlPart() does not add the tables from an all-aliased list of select columns'); - } - - public function testBigIntIgnoreCaseOrderBy() - { - BookstorePeer::doDeleteAll(); - - // Some sample data - $b = new Bookstore(); - $b->setStoreName("SortTest1")->setPopulationServed(2000)->save(); - - $b = new Bookstore(); - $b->setStoreName("SortTest2")->setPopulationServed(201)->save(); - - $b = new Bookstore(); - $b->setStoreName("SortTest3")->setPopulationServed(302)->save(); - - $b = new Bookstore(); - $b->setStoreName("SortTest4")->setPopulationServed(10000000)->save(); - - $c = new Criteria(); - $c->setIgnoreCase(true); - $c->add(BookstorePeer::STORE_NAME, 'SortTest%', Criteria::LIKE); - $c->addAscendingOrderByColumn(BookstorePeer::POPULATION_SERVED); - - $rows = BookstorePeer::doSelect($c); - $this->assertEquals('SortTest2', $rows[0]->getStoreName()); - $this->assertEquals('SortTest3', $rows[1]->getStoreName()); - $this->assertEquals('SortTest1', $rows[2]->getStoreName()); - $this->assertEquals('SortTest4', $rows[3]->getStoreName()); - } - - /** - * - */ - public function testMixedJoinOrder() - { - $this->markTestSkipped('Famous cross join problem, to be solved one day'); - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID); - - $params = array(); - $sql = BasePeer::createSelectSql($c, $params); - - $expectedSql = "SELECT book.ID, book.TITLE FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID), author WHERE book.AUTHOR_ID=author.ID"; - $this->assertEquals($expectedSql, $sql); - } - - public function testMssqlApplyLimitNoOffset() - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if(! ($db instanceof DBMSSQL)) - { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)'); - - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - - $c->setOffset(0); - $c->setLimit(20); - - $params = array(); - $sql = BasePeer::createSelectSql($c, $params); - - $expectedSql = "SELECT TOP 20 book.ID, book.TITLE, publisher.NAME, (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS PublisherName FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)"; - $this->assertEquals($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffset() - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if(! ($db instanceof DBMSSQL)) - { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->setOffset(20); - $c->setLimit(20); - - $params = array(); - - $expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY book.ID) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40"; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffsetOrderByAggregate() - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if(! ($db instanceof DBMSSQL)) - { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->addDescendingOrderByColumn('PublisherName'); - $c->setOffset(20); - $c->setLimit(20); - - $params = array(); - - $expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) DESC) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40"; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffsetMultipleOrderBy() - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if(! ($db instanceof DBMSSQL)) - { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->addDescendingOrderByColumn('PublisherName'); - $c->addAscendingOrderByColumn(BookPeer::TITLE); - $c->setOffset(20); - $c->setLimit(20); - - $params = array(); - - $expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) DESC, book.TITLE ASC) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40"; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertEquals($expectedSql, $sql); - } - - /** - * @expectedException PropelException - */ - public function testDoDeleteNoCondition() - { - $con = Propel::getConnection(); - $c = new Criteria(BookPeer::DATABASE_NAME); - BasePeer::doDelete($c, $con); - } - - public function testDoDeleteSimpleCondition() - { - $con = Propel::getConnection(); - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->add(BookPeer::TITLE, 'War And Peace'); - BasePeer::doDelete($c, $con); - $expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() translates a contition into a WHERE'); - } - - public function testDoDeleteSeveralConditions() - { - $con = Propel::getConnection(); - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->add(BookPeer::TITLE, 'War And Peace'); - $c->add(BookPeer::ID, 12); - BasePeer::doDelete($c, $con); - $expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace' AND book.ID=12"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() combines conditions in WHERE whith an AND'); - } - - public function testDoDeleteTableAlias() - { - $con = Propel::getConnection(); - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addAlias('b', BookPeer::TABLE_NAME); - $c->add('b.TITLE', 'War And Peace'); - BasePeer::doDelete($c, $con); - $expectedSQL = "DELETE b FROM `book` AS b WHERE b.TITLE='War And Peace'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() accepts a Criteria with a table alias'); - } - - /** - * Not documented anywhere, and probably wrong - * @see http://www.propelorm.org/ticket/952 - */ - public function testDoDeleteSeveralTables() - { - $con = Propel::getConnection(); - $count = $con->getQueryCount(); - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->add(BookPeer::TITLE, 'War And Peace'); - $c->add(AuthorPeer::FIRST_NAME, 'Leo'); - BasePeer::doDelete($c, $con); - $expectedSQL = "DELETE FROM `author` WHERE author.FIRST_NAME='Leo'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() issues two DELETE queries when passed conditions on two tables'); - $this->assertEquals($count + 2, $con->getQueryCount(), 'doDelete() issues two DELETE queries when passed conditions on two tables'); - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->add(AuthorPeer::FIRST_NAME, 'Leo'); - $c->add(BookPeer::TITLE, 'War And Peace'); - BasePeer::doDelete($c, $con); - $expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace'"; - $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() issues two DELETE queries when passed conditions on two tables'); - $this->assertEquals($count + 4, $con->getQueryCount(), 'doDelete() issues two DELETE queries when passed conditions on two tables'); - } - - public function testCommentDoSelect() - { - $c = new Criteria(); - $c->setComment('Foo'); - $c->addSelectColumn(BookPeer::ID); - $expected = 'SELECT /* Foo */ book.ID FROM `book`'; - $params = array(); - $this->assertEquals($expected, BasePeer::createSelectSQL($c, $params), 'Criteria::setComment() adds a comment to select queries'); - } - - public function testCommentDoUpdate() - { - $c1 = new Criteria(); - $c1->setPrimaryTableName(BookPeer::TABLE_NAME); - $c1->setComment('Foo'); - $c2 = new Criteria(); - $c2->add(BookPeer::TITLE, 'Updated Title'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BasePeer::doUpdate($c1, $c2, $con); - $expected = 'UPDATE /* Foo */ `book` SET `TITLE`=\'Updated Title\''; - $this->assertEquals($expected, $con->getLastExecutedQuery(), 'Criteria::setComment() adds a comment to update queries'); - } - - public function testCommentDoDelete() - { - $c = new Criteria(); - $c->setComment('Foo'); - $c->add(BookPeer::TITLE, 'War And Peace'); - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - BasePeer::doDelete($c, $con); - $expected = 'DELETE /* Foo */ FROM `book` WHERE book.TITLE=\'War And Peace\''; - $this->assertEquals($expected, $con->getLastExecutedQuery(), 'Criteria::setComment() adds a comment to delete queries'); - } - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelConfigurationTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelConfigurationTest.php deleted file mode 100644 index d653f3318..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelConfigurationTest.php +++ /dev/null @@ -1,69 +0,0 @@ - array('fooo' => 'bar', 'fi' => array('fooooo' => 'bara')), 'baz' => 'bar2'); - - public function testConstruct() - { - $conf = new PropelConfiguration($this->testArray); - $this->assertEquals($this->testArray, $conf->getParameters(), 'constructor sets values from an associative array'); - } - - public function testGetParameters() - { - $conf = new PropelConfiguration($this->testArray); - $expected = array('foo.fooo' => 'bar', 'foo.fi.fooooo' => 'bara', 'baz' => 'bar2'); - $this->assertEquals($expected, $conf->getParameters(PropelConfiguration::TYPE_ARRAY_FLAT), 'getParameters can return a flat array'); - } - - public function testGetParameter() - { - $conf = new PropelConfiguration($this->testArray); - $this->assertEquals('bar', $conf->getParameter('foo.fooo'), 'getParameter accepts a flat key'); - $this->assertEquals('bara', $conf->getParameter('foo.fi.fooooo'), 'getParameter accepts a flat key'); - $this->assertEquals('bar2', $conf->getParameter('baz'), 'getParameter accepts a flat key'); - } - - public function testGetParameterDefault() - { - $conf = new PropelConfiguration($this->testArray); - $this->assertEquals('bar', $conf->getParameter('foo.fooo'), 'getParameter accepts a flat key'); - $this->assertEquals('', $conf->getParameter('foo.fooo2'), 'getParameter returns null for nonexistent keys'); - $this->assertEquals('babar', $conf->getParameter('foo.fooo3', 'babar'), 'getParameter accepts a default value'); - } - - public function testSetParameter() - { - $conf = new PropelConfiguration(array()); - $conf->setParameter('foo.fooo', 'bar'); - $conf->setParameter('foo.fi.fooooo', 'bara'); - $conf->setParameter('baz', 'bar2'); - $this->assertEquals($this->testArray, $conf->getParameters(), 'setParameter accepts a flat array'); - } - - public function testArrayAccess() - { - $conf = new PropelConfiguration($this->testArray); - $expected = array('fooo' => 'bar', 'fi' => array('fooooo' => 'bara')); - $this->assertEquals($expected, $conf['foo'], 'PropelConfiguration implements ArrayAccess for OffsetGet'); - $this->assertEquals('bar', $conf['foo']['fooo'], 'Array access allows deep access'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelDateTimeTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelDateTimeTest.php deleted file mode 100644 index af490e0e4..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelDateTimeTest.php +++ /dev/null @@ -1,139 +0,0 @@ -assertEquals($dt1->format('Y-m-d H:i:s'), $dt1->format('Y-m-d H:i:s'), sprintf($msg, "Dates w/ no timezone resolution were not the same.")); - $this->assertEquals($dt1->getTimeZone()->getName(), $dt2->getTimeZone()->getName(), sprintf($msg, "timezones were not the same.")); - - - // We do this last, because a PHP bug will make this true while the dates - // may not truly be equal. - // See: http://bugs.php.net/bug.php?id=40743 - $this->assertTrue($dt1 == $dt2, sprintf($msg, "dates did not pass equality check (==).")); - } - - /** - * Assert that two dates are equal. - */ - protected function assertDatesEqual(DateTime $dt1, DateTime $dt2, $msg = "Expected DateTime1 == DateTime2: %s") - { - if ($dt1 != $dt2) { - if ($dt1->getTimeZone()->getName() != $dt2->getTimeZone()->getName()) { - $this->fail(sprintf($msg, "Timezones were not the same.")); - } else { - $this->fail(sprintf($msg, "Timezones were the same, but date values were different.")); - } - } - } - - /** - * Assert that two dates are not equal. - */ - protected function assertDatesNotEqual(DateTime $dt1, DateTime $dt2, $msg = "Expected DateTime1 != DateTime2: %s") - { - $this->assertTrue($dt1 != $dt2, $msg); - } - - /** - * Ensure that our constructor matches DateTime constructor signature. - */ - public function testConstruct() - { - - // Because of a PHP bug () - // we cannot use a timestamp format that includes a timezone. It gets weird. :) - $now = date('Y-m-d H:i:s'); - - $dt = new DateTime($now); - $pdt = new PropelDateTime($now); - $this->assertDatesEqual($dt, $pdt, "Expected DateTime == PropelDateTime: %s"); - - $dt = new DateTime($now, new DateTimeZone('UTC')); - $pdt = new PropelDateTime($now, new DateTimeZone('America/New_York')); - $this->assertDatesNotEqual($dt, $pdt, "Expected DateTime != PropelDateTime: %s"); - - } - - /** - * Tests the ability to serialize() a PropelDateTime object. - */ - public function testSerialize_NoTZ() - { - $now = date('Y-m-d H:i:s'); - $dt = new DateTime($now); - $pdt = new PropelDateTime($now); - - $this->assertDatesIdentical($dt, $pdt); - - // We expect these to be the same -- there's no time zone info - $ser = serialize($pdt); - unset($pdt); - - $pdt = unserialize($ser); - $this->assertDatesIdentical($dt, $pdt); - } - - /** - * Tests the ability to serialize() a PropelDateTime object. - */ - public function testSerialize_SameTZ() - { - $now = date('Y-m-d H:i:s'); - $dt = new DateTime($now, new DateTimeZone('America/New_York')); - $pdt = new PropelDateTime($now, new DateTimeZone('America/New_York')); - - $this->assertDatesIdentical($dt, $pdt); - - // We expect these to be the same -- there's no time zone info - $ser = serialize($pdt); - unset($pdt); - - $pdt = unserialize($ser); - $this->assertDatesIdentical($dt, $pdt); - } - - /** - * Tests the ability to serialize() a PropelDateTime object. - */ - public function testSerialize_DiffTZ() - { - $now = date('Y-m-d H:i:s'); - $dt = new DateTime($now, new DateTimeZone('UTC')); - $pdt = new PropelDateTime($now, new DateTimeZone('America/New_York')); - - $this->assertDatesNotEqual($dt, $pdt); - - // We expect these to be the same -- there's no time zone info - $ser = serialize($pdt); - unset($pdt); - - $pdt = unserialize($ser); - $this->assertDatesNotEqual($dt, $pdt); - } - - -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelModelPagerTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelModelPagerTest.php deleted file mode 100644 index b622663df..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelModelPagerTest.php +++ /dev/null @@ -1,149 +0,0 @@ -deleteAll($con); - $books = new PropelObjectCollection(); - $books->setModel('Book'); - for ($i=0; $i < $nb; $i++) { - $b = new Book(); - $b->setTitle('Book' . $i); - $books[]= $b; - } - $books->save($con); - } - - protected function getPager($maxPerPage, $page = 1) - { - $pager = new PropelModelPager(BookQuery::create(), $maxPerPage); - $pager->setPage($page); - $pager->init(); - return $pager; - } - - public function testHaveToPaginate() - { - BookQuery::create()->deleteAll(); - $this->assertEquals(false, $this->getPager(0)->haveToPaginate(), 'haveToPaginate() returns false when there is no result'); - $this->createBooks(5); - $this->assertEquals(false, $this->getPager(0)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is null'); - $this->assertEquals(true, $this->getPager(2)->haveToPaginate(), 'haveToPaginate() returns true when the maxPerPage is less than the number of results'); - $this->assertEquals(false, $this->getPager(6)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is greater than the number of results'); - $this->assertEquals(false, $this->getPager(5)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is equal to the number of results'); - } - - public function testGetNbResults() - { - BookQuery::create()->deleteAll(); - $pager = $this->getPager(4, 1); - $this->assertEquals(0, $pager->getNbResults(), 'getNbResults() returns 0 when there are no results'); - $this->createBooks(5); - $pager = $this->getPager(4, 1); - $this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results'); - $pager = $this->getPager(2, 1); - $this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results'); - $pager = $this->getPager(2, 2); - $this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results'); - $pager = $this->getPager(7, 6); - $this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results'); - $pager = $this->getPager(0, 0); - $this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results'); - } - - public function testGetResults() - { - $this->createBooks(5); - $pager = $this->getPager(4, 1); - $this->assertTrue($pager->getResults() instanceof PropelObjectCollection, 'getResults() returns a PropelObjectCollection'); - $this->assertEquals(4, count($pager->getResults()), 'getResults() returns at most $maxPerPage results'); - $pager = $this->getPager(4, 2); - $this->assertEquals(1, count($pager->getResults()), 'getResults() returns the remaining results when in the last page'); - $pager = $this->getPager(4, 3); - $this->assertEquals(1, count($pager->getResults()), 'getResults() returns the results of the last page when called on nonexistent pages'); - } - - public function testGetIterator() - { - $this->createBooks(5); - - $pager = $this->getPager(4, 1); - $i = 0; - foreach ($pager as $book) { - $this->assertEquals('Book' . $i, $book->getTitle(), 'getIterator() returns an iterator'); - $i++; - } - $this->assertEquals(4, $i, 'getIterator() uses the results collection'); - } - - public function testIterateTwice() - { - $this->createBooks(5); - $pager = $this->getPager(4, 1); - - $i = 0; - foreach ($pager as $book) { - $this->assertEquals('Book' . $i, $book->getTitle(), 'getIterator() returns an iterator'); - $i++; - } - $this->assertEquals(4, $i, 'getIterator() uses the results collection'); - - $i = 0; - foreach ($pager as $book) { - $this->assertEquals('Book' . $i, $book->getTitle()); - $i++; - } - $this->assertEquals(4, $i, 'getIterator() can be called several times'); - } - - public function testSetPage() - { - $this->createBooks(5); - $pager = $this->getPager(2, 2); - $i = 2; - foreach ($pager as $book) { - $this->assertEquals('Book' . $i, $book->getTitle(), 'setPage() sets the list to start on a given page'); - $i++; - } - $this->assertEquals(4, $i, 'setPage() doesn\'t change the page count'); - } - - public function testIsFirstPage() - { - $this->createBooks(5); - $pager = $this->getPager(4, 1); - $this->assertTrue($pager->isFirstPage(), 'isFirstPage() returns true on the first page'); - $pager = $this->getPager(4, 2); - $this->assertFalse($pager->isFirstPage(), 'isFirstPage() returns false when not on the first page'); - } - - public function testIsLastPage() - { - $this->createBooks(5); - $pager = $this->getPager(4, 1); - $this->assertFalse($pager->isLastPage(), 'isLastPage() returns false when not on the last page'); - $pager = $this->getPager(4, 2); - $this->assertTrue($pager->isLastPage(), 'isLastPage() returns true on the last page'); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelPagerTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelPagerTest.php deleted file mode 100644 index 473f56c09..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/util/PropelPagerTest.php +++ /dev/null @@ -1,162 +0,0 @@ - - * @version $Id: PropelPagerTest.php - * @package runtime.util - */ -class PropelPagerTest extends BookstoreEmptyTestBase -{ - private $authorId; - private $books; - - protected function setUp() - { - parent::setUp(); - BookstoreDataPopulator::populate(); - - $cr = new Criteria(); - $cr->add(AuthorPeer::LAST_NAME, "Rowling"); - $cr->add(AuthorPeer::FIRST_NAME, "J.K."); - $rowling = AuthorPeer::doSelectOne($cr); - $this->authorId = $rowling->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Philosopher's Stone"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Chamber of Secrets"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Prisoner of Azkaban"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Goblet of Fire"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Half-Blood Prince"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - - $book = new Book(); - $book->setTitle("Harry Potter and the Deathly Hallows"); - $book->setISBN("1234"); - $book->setAuthor($rowling); - $book->save(); - $this->books[] = $book->getId(); - } - - protected function tearDown() - { - parent::tearDown(); - $cr = new Criteria(); - $cr->add(BookPeer::ID, $this->books, Criteria::IN); - BookPeer::doDelete($cr); - } - - public function testCountNoPageNoLimit() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $pager = new PropelPager($cr, "BookPeer", "doSelect"); - $this->assertEquals(7, count($pager)); - } - - public function testCountFirstPageWithLimits() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $pager = new PropelPager($cr, "BookPeer", "doSelect", 1, 5); - $this->assertEquals(5, count($pager)); - } - - public function testCountLastPageWithLimits() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $pager = new PropelPager($cr, "BookPeer", "doSelect", 2, 5); - $this->assertEquals(2, count($pager)); - } - - public function testIterateAll() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $pager = new PropelPager($cr, "BookPeer", "doSelect"); - $i = 0; - foreach ($pager as $key => $book) { - $i++; - } - $this->assertEquals(7, $i); - } - - public function testIterateWithLimits() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $pager = new PropelPager($cr, "BookPeer", "doSelect", 2, 5); - $i = 0; - foreach ($pager as $key => $book) { - $i++; - } - $this->assertEquals(2, $i); - } - - public function testIterateCheckSecond() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $cr->addAscendingOrderByColumn(BookPeer::TITLE); - $pager = new PropelPager($cr, "BookPeer", "doSelect"); - $books = array(); - foreach($pager as $book) { - $books[] = $book; - } - $this->assertEquals("Harry Potter and the Goblet of Fire", $books[2]->getTitle()); - } - - public function testIterateTwice() - { - $cr = new Criteria(); - $cr->add(BookPeer::AUTHOR_ID, $this->authorId); - $cr->addAscendingOrderByColumn(BookPeer::TITLE); - $pager = new PropelPager($cr, "BookPeer", "doSelect"); - $i = 0; - foreach($pager as $book) { - $i++; - } - foreach($pager as $book) { - $i++; - } - $this->assertEquals(14, $i); - } -} diff --git a/airtime_mvc/library/propel/test/testsuite/runtime/validator/ValidatorTest.php b/airtime_mvc/library/propel/test/testsuite/runtime/validator/ValidatorTest.php deleted file mode 100644 index 323c58629..000000000 --- a/airtime_mvc/library/propel/test/testsuite/runtime/validator/ValidatorTest.php +++ /dev/null @@ -1,228 +0,0 @@ - - * @package runtime.validator - */ -class ValidatorTest extends BookstoreEmptyTestBase -{ - - protected function setUp() - { - parent::setUp(); - BookstoreDataPopulator::populate(); - require_once 'tools/helpers/bookstore/validator/ISBNValidator.php'; - } - - /** - * Test minLength validator. - * This also tests the ${value} substitution. - */ - public function testDoValidate_MinLength() - { - $book = new Book(); - $book->setTitle("12345"); // min length is 10 - - $res = $book->validate(); - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $book->getValidationFailures(); - $this->assertSingleValidation($failures, "Book title must be more than 10 characters long."); - } - - /** - * Test unique validator. - */ - public function testDoValidate_Unique() - { - $book = new Book(); - $book->setTitle("Don Juan"); - - $ret = $book->validate(); - $failures = $book->getValidationFailures(); - $this->assertSingleValidation($failures, "Book title already in database."); - } - - /** - * Test recursive validaton. - */ - public function testDoValidate_Complex() - { - $book = new Book(); - $book->setTitle("12345"); // min length is 10 - - $author = new Author(); - $author->setFirstName("Hans"); // last name required, valid email format, age > 0 - - $review = new Review(); - $review->setReviewDate("08/09/2001"); // reviewed_by column required, invalid status (new, reviewed, archived) - - $book->setAuthor($author); - $book->addReview($review); - - $res = $book->validate(); - - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $book->getValidationFailures(); - - /* Make sure 3 validation messages were returned; NOT 6, because the others were NULL */ - $this->assertEquals(3, count($failures), ""); - - /* Make sure correct columns failed */ - $expectedCols = array( - AuthorPeer::LAST_NAME, - BookPeer::TITLE, - ReviewPeer::REVIEWED_BY - ); - $returnedCols = array_keys($failures); - - /* implode for readability */ - $this->assertEquals(implode(',', $expectedCols), implode(',', $returnedCols)); - } - - /** - * Test recursive validaton with specified columns. - */ - public function testDoValidate_ComplexSpecifiedCols() - { - $book = new Book(); - $book->setTitle("12345"); // min length is 10 - - $author = new Author(); - $author->setFirstName("Hans"); // last name required, valid email format, age > 0 - - $review = new Review(); - $review->setReviewDate("08/09/2001"); // reviewed_by column required, invalid status (new, reviewed, archived) - - $book->setAuthor($author); - $book->addReview($review); - - $cols = array(AuthorPeer::LAST_NAME, ReviewPeer::REVIEWED_BY); - - $res = $book->validate($cols); - - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $book->getValidationFailures(); - - /* Make sure 3 validation messages were returned; NOT 6, because the others were NULL */ - $this->assertEquals(2, count($failures), ""); - - /* Make sure correct columns failed */ - $expectedCols = array( - AuthorPeer::LAST_NAME, - ReviewPeer::REVIEWED_BY - ); - - $returnedCols = array_keys($failures); - - /* implode for readability */ - $this->assertEquals(implode(',', $expectedCols), implode(',', $returnedCols)); - } - - /** - * Test the fact that validators should not complain NULL values for non-required columns. - */ - public function testDoValidate_Nulls() - { - $author = new Author(); - $author->setFirstName("Malcolm"); // last name required, valid email format, age > 0 - $author->setLastName("X"); - - $author->setEmail(null); // just to be explicit, of course these are the defaults anyway - $author->setAge(null); - - $res = $author->validate(); - - - $this->assertTrue($res, "Expected validation to pass with NULL columns"); - - $author->setEmail('malcolm@'); // fail - $res = $author->validate(); - - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $author->getValidationFailures(); - $this->assertEquals(1, count($failures), "Expected 1 column to fail validation."); - $this->assertEquals(array(AuthorPeer::EMAIL), array_keys($failures), "Expected EMAIL to fail validation."); - - } - - public function testDoValidate_BasicValidatorObj() - { - $author = new Author(); - $author->setFirstName("Malcolm"); // last name required, valid email format, age > 0 - $author->setLastName("X"); - $author->setEmail('malcolm@'); // fail - - $res = $author->validate(); - - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $author->getValidationFailures(); - - $this->assertEquals(1, count($failures), "Expected 1 column to fail validation."); - $this->assertEquals(array(AuthorPeer::EMAIL), array_keys($failures), "Expected EMAIL to fail validation."); - - $validator = $failures[AuthorPeer::EMAIL]->getValidator(); - $this->assertTrue($validator instanceof MatchValidator, "Expected validator that failed to be MatchValidator"); - - } - - public function testDoValidate_CustomValidator() - { - $book = new Book(); - $book->setTitle("testDoValidate_CustomValidator"); // (valid) - $book->setISBN("Foo.Bar.Baz"); // (invalid) - - $res = $book->validate(); - - $this->assertFalse($res, "Expected validation to fail."); - - $failures = $book->getValidationFailures(); - - $this->assertEquals(1, count($failures), "Expected 1 column to fail validation."); - $this->assertEquals(array(BookPeer::ISBN), array_keys($failures), "Expected EMAIL to fail validation."); - - $validator = $failures[BookPeer::ISBN]->getValidator(); - $this->assertType('ISBNValidator', $validator, "Expected validator that failed to be ISBNValidator"); - } - - protected function assertSingleValidation($ret, $expectedMsg) - { - /* Make sure validation failed */ - $this->assertTrue($ret !== true, "Expected validation to fail !"); - - /* Make sure 1 validation message was returned */ - $count = count($ret); - $this->assertTrue($count === 1, "Expected that exactly one validation failed ($count) !"); - - /* Make sure expected validation message was returned */ - $el = array_shift($ret); - $this->assertEquals($el->getMessage(), $expectedMsg, "Got unexpected validation failed message: " . $el->getMessage()); - } - -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/BaseTestCase.php b/airtime_mvc/library/propel/test/tools/helpers/BaseTestCase.php deleted file mode 100644 index f3827c24b..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/BaseTestCase.php +++ /dev/null @@ -1,30 +0,0 @@ - (Propel) - * @author Daniel Rall (Torque) - * @author Christopher Elkins (Torque) - * @version $Revision: 1773 $ - */ -abstract class BaseTestCase extends PHPUnit_Framework_TestCase { - - /** - * Conditional compilation flag. - */ - const DEBUG = false; - -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreDataPopulator.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreDataPopulator.php deleted file mode 100644 index 5dc3902be..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreDataPopulator.php +++ /dev/null @@ -1,247 +0,0 @@ - - */ -class BookstoreDataPopulator -{ - - public static function populate($con = null) - { - if($con === null) { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - } - $con->beginTransaction(); - - // Add publisher records - // --------------------- - - $scholastic = new Publisher(); - $scholastic->setName("Scholastic"); - // do not save, will do later to test cascade - - $morrow = new Publisher(); - $morrow->setName("William Morrow"); - $morrow->save($con); - $morrow_id = $morrow->getId(); - - $penguin = new Publisher(); - $penguin->setName("Penguin"); - $penguin->save(); - $penguin_id = $penguin->getId(); - - $vintage = new Publisher(); - $vintage->setName("Vintage"); - $vintage->save($con); - $vintage_id = $vintage->getId(); - - $rowling = new Author(); - $rowling->setFirstName("J.K."); - $rowling->setLastName("Rowling"); - // no save() - - $stephenson = new Author(); - $stephenson->setFirstName("Neal"); - $stephenson->setLastName("Stephenson"); - $stephenson->save($con); - $stephenson_id = $stephenson->getId(); - - $byron = new Author(); - $byron->setFirstName("George"); - $byron->setLastName("Byron"); - $byron->save($con); - $byron_id = $byron->getId(); - - $grass = new Author(); - $grass->setFirstName("Gunter"); - $grass->setLastName("Grass"); - $grass->save($con); - $grass_id = $grass->getId(); - - $phoenix = new Book(); - $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); - $phoenix->setISBN("043935806X"); - $phoenix->setAuthor($rowling); - $phoenix->setPublisher($scholastic); - $phoenix->setPrice(10.99); - $phoenix->save($con); - $phoenix_id = $phoenix->getId(); - - $qs = new Book(); - $qs->setISBN("0380977427"); - $qs->setTitle("Quicksilver"); - $qs->setPrice(11.99); - $qs->setAuthor($stephenson); - $qs->setPublisher($morrow); - $qs->save($con); - $qs_id = $qs->getId(); - - $dj = new Book(); - $dj->setISBN("0140422161"); - $dj->setTitle("Don Juan"); - $dj->setPrice(12.99); - $dj->setAuthor($byron); - $dj->setPublisher($penguin); - $dj->save($con); - $dj_id = $dj->getId(); - - $td = new Book(); - $td->setISBN("067972575X"); - $td->setTitle("The Tin Drum"); - $td->setPrice(13.99); - $td->setAuthor($grass); - $td->setPublisher($vintage); - $td->save($con); - $td_id = $td->getId(); - - $r1 = new Review(); - $r1->setBook($phoenix); - $r1->setReviewedBy("Washington Post"); - $r1->setRecommended(true); - $r1->setReviewDate(time()); - $r1->save($con); - $r1_id = $r1->getId(); - - $r2 = new Review(); - $r2->setBook($phoenix); - $r2->setReviewedBy("New York Times"); - $r2->setRecommended(false); - $r2->setReviewDate(time()); - $r2->save($con); - $r2_id = $r2->getId(); - - $blob_path = _LOB_SAMPLE_FILE_PATH . '/tin_drum.gif'; - $clob_path = _LOB_SAMPLE_FILE_PATH . '/tin_drum.txt'; - - $m1 = new Media(); - $m1->setBook($td); - $m1->setCoverImage(file_get_contents($blob_path)); - // CLOB is broken in PDO OCI, see http://pecl.php.net/bugs/bug.php?id=7943 - if (get_class(Propel::getDB()) != "DBOracle") { - $m1->setExcerpt(file_get_contents($clob_path)); - } - $m1->save($con); - - // Add book list records - // --------------------- - // (this is for many-to-many tests) - - $blc1 = new BookClubList(); - $blc1->setGroupLeader("Crazyleggs"); - $blc1->setTheme("Happiness"); - - $brel1 = new BookListRel(); - $brel1->setBook($phoenix); - - $brel2 = new BookListRel(); - $brel2->setBook($dj); - - $blc1->addBookListRel($brel1); - $blc1->addBookListRel($brel2); - - $blc1->save(); - - $bemp1 = new BookstoreEmployee(); - $bemp1->setName("John"); - $bemp1->setJobTitle("Manager"); - - $bemp2 = new BookstoreEmployee(); - $bemp2->setName("Pieter"); - $bemp2->setJobTitle("Clerk"); - $bemp2->setSupervisor($bemp1); - $bemp2->save($con); - - $role = new AcctAccessRole(); - $role->setName("Admin"); - - $bempacct = new BookstoreEmployeeAccount(); - $bempacct->setBookstoreEmployee($bemp1); - $bempacct->setAcctAccessRole($role); - $bempacct->setLogin("john"); - $bempacct->setPassword("johnp4ss"); - $bempacct->save($con); - - // Add bookstores - - $store = new Bookstore(); - $store->setStoreName("Amazon"); - $store->setPopulationServed(5000000000); // world population - $store->setTotalBooks(300); - $store->save($con); - - $store = new Bookstore(); - $store->setStoreName("Local Store"); - $store->setPopulationServed(20); - $store->setTotalBooks(500000); - $store->save($con); - - $con->commit(); - } - - public static function populateOpinionFavorite($con = null) - { - if($con === null) { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - } - $con->beginTransaction(); - - $book1 = BookPeer::doSelectOne(new Criteria(), $con); - $reader1 = new BookReader(); - $reader1->save($con); - - $bo = new BookOpinion(); - $bo->setBook($book1); - $bo->setBookReader($reader1); - $bo->save($con); - - $rf = new ReaderFavorite(); - $rf->setBookOpinion($bo); - $rf->save($con); - - $con->commit(); - } - - public static function depopulate($con = null) - { - if($con === null) { - $con = Propel::getConnection(BookPeer::DATABASE_NAME); - } - $con->beginTransaction(); - AuthorPeer::doDeleteAll($con); - BookstorePeer::doDeleteAll($con); - BookstoreContestPeer::doDeleteAll($con); - BookstoreContestEntryPeer::doDeleteAll($con); - BookstoreEmployeePeer::doDeleteAll($con); - BookstoreEmployeeAccountPeer::doDeleteAll($con); - BookstoreSalePeer::doDeleteAll($con); - BookClubListPeer::doDeleteAll($con); - BookOpinionPeer::doDeleteAll($con); - BookReaderPeer::doDeleteAll($con); - BookListRelPeer::doDeleteAll($con); - BookPeer::doDeleteAll($con); - ContestPeer::doDeleteAll($con); - CustomerPeer::doDeleteAll($con); - MediaPeer::doDeleteAll($con); - PublisherPeer::doDeleteAll($con); - ReaderFavoritePeer::doDeleteAll($con); - ReviewPeer::doDeleteAll($con); - $con->commit(); - } - -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreEmptyTestBase.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreEmptyTestBase.php deleted file mode 100644 index 08efab6a8..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreEmptyTestBase.php +++ /dev/null @@ -1,38 +0,0 @@ - -con); - } - - /** - * This is run after each unit test. It empties the database. - */ - protected function tearDown() - { - BookstoreDataPopulator::depopulate($this->con); - parent::tearDown(); - } - -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreTestBase.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreTestBase.php deleted file mode 100644 index 4ea139e6d..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/BookstoreTestBase.php +++ /dev/null @@ -1,47 +0,0 @@ -con = Propel::getConnection(BookPeer::DATABASE_NAME); - $this->con->beginTransaction(); - } - - /** - * This is run after each unit test. It empties the database. - */ - protected function tearDown() - { - parent::tearDown(); - // Only commit if the transaction hasn't failed. - // This is because tearDown() is also executed on a failed tests, - // and we don't want to call PropelPDO::commit() in that case - // since it will trigger an exception on its own - // ('Cannot commit because a nested transaction was rolled back') - if ($this->con->isCommitable()) { - $this->con->commit(); - } - } -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php deleted file mode 100644 index 222c0eb50..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php +++ /dev/null @@ -1,146 +0,0 @@ -getTitle()] = array($node->getLeftValue(), $node->getRightValue(), $node->getLevel()); - } - return $tree; - } - - /** - * Tree used for tests - * t1 - * | \ - * t2 t3 - * | \ - * t4 t5 - * | \ - * t6 t7 - */ - protected function initTree() - { - Table9Peer::doDeleteAll(); - $ret = array(); - // shuffling the results so the db order is not the natural one - $fixtures = array( - 't2' => array(2, 3, 1), - 't5' => array(7, 12, 2), - 't4' => array(5, 6, 2), - 't7' => array(10, 11, 3), - 't1' => array(1, 14, 0), - 't6' => array(8, 9, 3), - 't3' => array(4, 13, 1), - ); - /* in correct order, this is: - 't1' => array(1, 14, 0), - 't2' => array(2, 3, 1), - 't3' => array(4, 13, 1), - 't4' => array(5, 6, 2), - 't5' => array(7, 12, 2), - 't6' => array(8, 9, 3), - 't7' => array(10, 11, 3), - */ - foreach ($fixtures as $key => $data) { - $t = new PublicTable9(); - $t->setTitle($key); - $t->setLeftValue($data[0]); - $t->setRightValue($data[1]); - $t->setLevel($data[2]); - $t->save(); - $ret[$key]= $t; - } - // reordering the results in the fixtures - ksort($ret); - return array_values($ret); - } - - protected function dumpTree() - { - $c = new Criteria(); - $c->addAscendingOrderBycolumn(Table9Peer::TITLE); - return $this->dumpNodes(Table9Peer::doSelect($c)); - } - - /** - * Tree used for tests - * Scope 1 - * t1 - * | \ - * t2 t3 - * | \ - * t4 t5 - * | \ - * t6 t7 - * Scope 2 - * t8 - * | \ - * t9 t10 - */ - protected function initTreeWithScope() - { - Table10Peer::doDeleteAll(); - $ret = array(); - $fixtures = array( - 't1' => array(1, 14, 0, 1), - 't2' => array(2, 3, 1, 1), - 't3' => array(4, 13, 1, 1), - 't4' => array(5, 6, 2, 1), - 't5' => array(7, 12, 2, 1), - 't6' => array(8, 9, 3, 1), - 't7' => array(10, 11, 3, 1), - 't8' => array(1, 6, 0, 2), - 't9' => array(2, 3, 1, 2), - 't10' => array(4, 5, 1, 2), - ); - foreach ($fixtures as $key => $data) { - $t = new PublicTable10(); - $t->setTitle($key); - $t->setLeftValue($data[0]); - $t->setRightValue($data[1]); - $t->setLevel($data[2]); - $t->setScopeValue($data[3]); - $t->save(); - $ret []= $t; - } - return $ret; - } - - protected function dumpTreeWithScope($scope) - { - $c = new Criteria(); - $c->add(Table10Peer::SCOPE_COL, $scope); - $c->addAscendingOrderBycolumn(Table10Peer::TITLE); - return $this->dumpNodes(Table10Peer::doSelect($c)); - } -} - -// we need this class to test protected methods -class PublicTable9 extends Table9 -{ - public $hasParentNode = null; - public $parentNode = null; - public $hasPrevSibling = null; - public $prevSibling = null; - public $hasNextSibling = null; - public $nextSibling = null; -} - -class PublicTable10 extends Table10 -{ - public $hasParentNode = null; - public $parentNode = null; -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php deleted file mode 100644 index 2af39debe..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php +++ /dev/null @@ -1,104 +0,0 @@ -setRank(1); - $t1->setTitle('row1'); - $t1->save(); - $t2 = new Table11(); - $t2->setRank(4); - $t2->setTitle('row4'); - $t2->save(); - $t3 = new Table11(); - $t3->setRank(2); - $t3->setTitle('row2'); - $t3->save(); - $t4 = new Table11(); - $t4->setRank(3); - $t4->setTitle('row3'); - $t4->save(); - } - - protected function populateTable12() - { - /* List used for tests - scope=1 scope=2 - row1 row5 - row2 row6 - row3 - row4 - */ - Table12Peer::doDeleteAll(); - $t1 = new Table12(); - $t1->setRank(1); - $t1->setScopeValue(1); - $t1->setTitle('row1'); - $t1->save(); - $t2 = new Table12(); - $t2->setRank(4); - $t2->setScopeValue(1); - $t2->setTitle('row4'); - $t2->save(); - $t3 = new Table12(); - $t3->setRank(2); - $t3->setScopeValue(1); - $t3->setTitle('row2'); - $t3->save(); - $t4 = new Table12(); - $t4->setRank(1); - $t4->setScopeValue(2); - $t4->setTitle('row5'); - $t4->save(); - $t5 = new Table12(); - $t5->setRank(3); - $t5->setScopeValue(1); - $t5->setTitle('row3'); - $t5->save(); - $t6 = new Table12(); - $t6->setRank(2); - $t6->setScopeValue(2); - $t6->setTitle('row6'); - $t6->save(); - } - - protected function getFixturesArray() - { - $c = new Criteria(); - $c->addAscendingOrderByColumn(Table11Peer::RANK_COL); - $ts = Table11Peer::doSelect($c); - $ret = array(); - foreach ($ts as $t) { - $ret[$t->getRank()] = $t->getTitle(); - } - return $ret; - } - - protected function getFixturesArrayWithScope($scope = null) - { - $c = new Criteria(); - if ($scope !== null) { - $c->add(Table12Peer::SCOPE_COL, $scope); - } - $c->addAscendingOrderByColumn(Table12Peer::RANK_COL); - $ts = Table12Peer::doSelect($c); - $ret = array(); - foreach ($ts as $t) { - $ret[$t->getRank()] = $t->getTitle(); - } - return $ret; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/DonothingBehavior.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/DonothingBehavior.php deleted file mode 100644 index 2b6f2fb97..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/DonothingBehavior.php +++ /dev/null @@ -1,13 +0,0 @@ -setFirstName('PreInsertedFirstname'); - return true; - } - - public function postInsert(PropelPDO $con = null) - { - parent::postInsert($con); - $this->setLastName('PostInsertedLastName'); - } - - public function preUpdate(PropelPDO $con = null) - { - parent::preUpdate($con); - $this->setFirstName('PreUpdatedFirstname'); - return true; - } - - public function postUpdate(PropelPDO $con = null) - { - parent::postUpdate($con); - $this->setLastName('PostUpdatedLastName'); - } - - public function preSave(PropelPDO $con = null) - { - parent::preSave($con); - $this->setEmail("pre@save.com"); - return true; - } - - public function postSave(PropelPDO $con = null) - { - parent::postSave($con); - $this->setAge(115); - } - - public function preDelete(PropelPDO $con = null) - { - parent::preDelete($con); - $this->setFirstName("Pre-Deleted"); - return true; - } - - public function postDelete(PropelPDO $con = null) - { - parent::postDelete($con); - $this->setLastName("Post-Deleted"); - } -} - -class TestAuthorDeleteFalse extends TestAuthor -{ - public function preDelete(PropelPDO $con = null) - { - parent::preDelete($con); - $this->setFirstName("Pre-Deleted"); - return false; - } -} -class TestAuthorSaveFalse extends TestAuthor -{ - public function preSave(PropelPDO $con = null) - { - parent::preSave($con); - $this->setEmail("pre@save.com"); - return false; - } - -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/Testallhooksbehavior.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/Testallhooksbehavior.php deleted file mode 100644 index 4a44c2323..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/behavior/Testallhooksbehavior.php +++ /dev/null @@ -1,183 +0,0 @@ -tableModifier)) - { - $this->tableModifier = new TestAllHooksTableModifier($this); - } - return $this->tableModifier; - } - - public function getObjectBuilderModifier() - { - if (is_null($this->objectBuilderModifier)) - { - $this->objectBuilderModifier = new TestAllHooksObjectBuilderModifier($this); - } - return $this->objectBuilderModifier; - } - - public function getPeerBuilderModifier() - { - if (is_null($this->peerBuilderModifier)) - { - $this->peerBuilderModifier = new TestAllHooksPeerBuilderModifier($this); - } - return $this->peerBuilderModifier; - } - - public function getQueryBuilderModifier() - { - if (is_null($this->queryBuilderModifier)) - { - $this->queryBuilderModifier = new TestAllHooksQueryBuilderModifier($this); - } - return $this->queryBuilderModifier; - } -} - -class TestAllHooksTableModifier -{ - protected $behavior, $table; - - public function __construct($behavior) - { - $this->behavior = $behavior; - $this->table = $behavior->getTable(); - } - - public function modifyTable() - { - $this->table->addColumn(array( - 'name' => 'test', - 'type' => 'TIMESTAMP' - )); - } -} - -class TestAllHooksObjectBuilderModifier -{ - public function objectAttributes($builder) - { - return 'public $customAttribute = 1;'; - } - - public function preSave($builder) - { - return '$this->preSave = 1;$this->preSaveIsAfterSave = isset($affectedRows);$this->preSaveBuilder="' . get_class($builder) . '";'; - } - - public function postSave($builder) - { - return '$this->postSave = 1;$this->postSaveIsAfterSave = isset($affectedRows);$this->postSaveBuilder="' . get_class($builder) . '";'; - } - - public function preInsert($builder) - { - return '$this->preInsert = 1;$this->preInsertIsAfterSave = isset($affectedRows);$this->preInsertBuilder="' . get_class($builder) . '";'; - } - - public function postInsert($builder) - { - return '$this->postInsert = 1;$this->postInsertIsAfterSave = isset($affectedRows);$this->postInsertBuilder="' . get_class($builder) . '";'; - } - - public function preUpdate($builder) - { - return '$this->preUpdate = 1;$this->preUpdateIsAfterSave = isset($affectedRows);$this->preUpdateBuilder="' . get_class($builder) . '";'; - } - - public function postUpdate($builder) - { - return '$this->postUpdate = 1;$this->postUpdateIsAfterSave = isset($affectedRows);$this->postUpdateBuilder="' . get_class($builder) . '";'; - } - - public function preDelete($builder) - { - return '$this->preDelete = 1;$this->preDeleteIsBeforeDelete = isset(Table3Peer::$instances[$this->id]);$this->preDeleteBuilder="' . get_class($builder) . '";'; - } - - public function postDelete($builder) - { - return '$this->postDelete = 1;$this->postDeleteIsBeforeDelete = isset(Table3Peer::$instances[$this->id]);$this->postDeleteBuilder="' . get_class($builder) . '";'; - } - - public function objectMethods($builder) - { - return 'public function hello() { return "' . get_class($builder) .'"; }'; - } - - public function objectCall($builder) - { - return 'if ($name == "foo") return "bar";'; - } - - public function objectFilter(&$string, $builder) - { - $string .= 'class testObjectFilter { const FOO = "' . get_class($builder) . '"; }'; - } -} - -class TestAllHooksPeerBuilderModifier -{ - public function staticAttributes($builder) - { - return 'public static $customStaticAttribute = 1;public static $staticAttributeBuilder = "' . get_class($builder) . '";'; - } - - public function staticMethods($builder) - { - return 'public static function hello() { return "' . get_class($builder) . '"; }'; - } - - public function preSelect($builder) - { - return '$con->preSelect = "' . get_class($builder) . '";'; - } - - public function peerFilter(&$string, $builder) - { - $string .= 'class testPeerFilter { const FOO = "' . get_class($builder) . '"; }'; - } -} - -class TestAllHooksQueryBuilderModifier -{ - public function preSelectQuery($builder) - { - return '// foo'; - } - - public function preDeleteQuery($builder) - { - return '// foo'; - } - - public function postDeleteQuery($builder) - { - return '// foo'; - } - - public function preUpdateQuery($builder) - { - return '// foo'; - } - - public function postUpdateQuery($builder) - { - return '// foo'; - } -} \ No newline at end of file diff --git a/airtime_mvc/library/propel/test/tools/helpers/bookstore/validator/ISBNValidator.php b/airtime_mvc/library/propel/test/tools/helpers/bookstore/validator/ISBNValidator.php deleted file mode 100644 index 690c81a40..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/bookstore/validator/ISBNValidator.php +++ /dev/null @@ -1,29 +0,0 @@ - - * @version $Revision: 1612 $ - * @package propel.validator - */ -class ISBNValidator implements BasicValidator -{ - const NOT_ISBN_REGEXP = '/[^0-9A-Z]/'; - - /** - * Whether the passed string matches regular expression. - */ - public function isValid (ValidatorMap $map, $str) - { - return !(preg_match(self::NOT_ISBN_REGEXP, $str)); - } -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/cms/CmsDataPopulator.php b/airtime_mvc/library/propel/test/tools/helpers/cms/CmsDataPopulator.php deleted file mode 100644 index 2a05f3ff3..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/cms/CmsDataPopulator.php +++ /dev/null @@ -1,143 +0,0 @@ - - */ -class CmsDataPopulator { - - public static function populate($con = null) - { - if($con === null) - { - $con = Propel::getConnection(PagePeer::DATABASE_NAME); - } - $con->beginTransaction(); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 1,194,'home')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 2,5,'school')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 6,43,'education')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 44,45,'simulator')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 46,47,'ac')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 3,4,'history')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 7,14,'master-mariner')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 8,9,'education')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 48,85,'courses')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 98,101,'contact')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 10,11,'entrance')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 104,191,'intra')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 102,103,'services')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 12,13,'competency')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 15,22,'watchkeeping-officer')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 16,17,'education')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 18,19,'entrance')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 20,21,'competency')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 31,38,'watchkeeping-engineer')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 32,33,'education')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 34,35,'entrance')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 36,37,'competency')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 39,40,'practice')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 86,97,'news')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 95,96,'2007-02')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 99,100,'personnel')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 87,88,'2007-06')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 49,50,'nautical')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 51,52,'radiotechnical')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 53,54,'resourcemgmt')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 57,58,'safety')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 59,60,'firstaid')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 61,62,'sar')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 67,84,'upcoming')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 65,66,'languages')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 55,56,'cargomgmt')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 119,120,'timetable')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 63,64,'boaters')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 105,118,'bulletinboard')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 106,107,'sdf')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 41,42,'fristaende')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 23,30,'ingenj')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 24,25,'utbildn')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 26,27,'ansokn')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 93,94,'utexaminerade')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 89,92,'Massan')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 192,193,'lankar')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 68,69,'FRB')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 70,71,'pelastautumis')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 72,73,'CCM')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 74,75,'sjukvard')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 121,188,'Veckoscheman')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 134,135,'VS3VSVsjukv')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 122,123,'sjoarb')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 130,131,'fysik1')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 140,141,'kemi')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 76,77,'inr')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 78,79,'forare')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 144,145,'AlexandraYH2')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 132,133,'AlexandraVS2')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 80,81,'Maskin')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 126,127,'forstahjalp')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 136,137,'Juridik')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 142,143,'mate')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 82,83,'basic')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 124,125,'mask')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 108,109,'magnus')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 138,139,'sjosakerhet')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 28,29,'pate')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 148,149,'eng')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 146,147,'forstahjalpYH1')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 110,111,'kortoverlevnadskurs')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 158,159,'kortoverlevnadskurs')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 128,129,'metall')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 152,153,'fysik')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 156,157,'fardplan')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 154,155,'astro')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 90,91,'utstallare')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 150,151,'eng')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 160,161,'ent')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 162,163,'juridik')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 168,169,'svenska')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 164,165,'matemat')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 166,167,'operativa')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 170,171,'plan')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 172,173,'src')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 112,113,'sjukv')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 174,175,'matemati')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 176,177,'fysiikka')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 114,115,'hantv')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 116,117,'CCM')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 178,179,'haveri')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 180,181,'FRB')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 182,183,'kemia')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 184,185,'vaktrutiner')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 189,190,'laroplan')"); - $con->exec("INSERT INTO Page (ScopeId, LeftChild, RightChild, Title) VALUES (1, 186,187,'SSOkurs')"); - - $con->exec("INSERT INTO Category (LeftChild, RightChild, Title) VALUES (1, 8, 'Cat_1')"); - $con->exec("INSERT INTO Category (LeftChild, RightChild, Title) VALUES (2, 7, 'Cat_1_1')"); - $con->exec("INSERT INTO Category (LeftChild, RightChild, Title) VALUES (3, 6, 'Cat_1_1_1')"); - $con->exec("INSERT INTO Category (LeftChild, RightChild, Title) VALUES (4, 5, 'Cat_1_1_1_1')"); - - $con->commit(); - } - - public static function depopulate($con = null) - { - if($con === null) - { - $con = Propel::getConnection(PagePeer::DATABASE_NAME); - } - $con->beginTransaction(); - $con->exec("DELETE FROM Page"); - $con->exec("DELETE FROM Category"); - - $con->commit(); - } -} diff --git a/airtime_mvc/library/propel/test/tools/helpers/cms/CmsTestBase.php b/airtime_mvc/library/propel/test/tools/helpers/cms/CmsTestBase.php deleted file mode 100644 index 0d9c73791..000000000 --- a/airtime_mvc/library/propel/test/tools/helpers/cms/CmsTestBase.php +++ /dev/null @@ -1,45 +0,0 @@ -con = Propel::getConnection(PagePeer::DATABASE_NAME); - $this->con->beginTransaction(); - CmsDataPopulator::depopulate($this->con); - CmsDataPopulator::populate($this->con); - } - - /** - * This is run after each unit test. It empties the database. - */ - protected function tearDown() - { - CmsDataPopulator::depopulate($this->con); - $this->con->commit(); - parent::tearDown(); - } - -} diff --git a/airtime_mvc/library/propel/test/tools/phing/DefineTask.php b/airtime_mvc/library/propel/test/tools/phing/DefineTask.php deleted file mode 100644 index ef6f208be..000000000 --- a/airtime_mvc/library/propel/test/tools/phing/DefineTask.php +++ /dev/null @@ -1,58 +0,0 @@ -name = $v; - } - - /** - * Sets the value for the constant. - * @param string $v - */ - public function setValue($v) { - $this->value = $v; - } - - public function main() { - if (!isset($this->name) || !isset($this->value)) { - throw new BuildException("Both name and value params are required.", $this->getLocation()); - } - $const = strtoupper($this->name); - if (defined($const)) { - $this->log("The constant $const has already been defined!", Project::MSG_ERR); - } else { - define($const, $this->value); - $this->log("Defined $const with value " . var_export($this->value, true), Project::MSG_INFO); - } - } -} diff --git a/airtime_mvc/library/propel/test/tree-test.php b/airtime_mvc/library/propel/test/tree-test.php deleted file mode 100644 index c807f32e9..000000000 --- a/airtime_mvc/library/propel/test/tree-test.php +++ /dev/null @@ -1,426 +0,0 @@ -"; - -error_reporting(E_ALL); - -$conf_path = realpath(dirname(__FILE__) . '/fixtures/treetest/build/conf/treetest-conf.php'); -if (!file_exists($conf_path)) { - echo "Make sure that you specify properties in conf/treetest.properties and " - ."build propel before running this script."; - exit; -} - -// Add PHP_CLASSPATH, if set -if (getenv("PHP_CLASSPATH")) { - set_include_path(getenv("PHP_CLASSPATH") . PATH_SEPARATOR . get_include_path()); -} - - // Add build/classes/ and classes/ to path -set_include_path( - realpath(dirname(__FILE__) . '/fixtures/treetest/build/classes') . PATH_SEPARATOR . - dirname(__FILE__) . '/../runtime/classes' . PATH_SEPARATOR . - get_include_path() -); - - -// Require classes. -require_once 'propel/Propel.php'; -require_once 'treetest/TestNodePeer.php'; - -function dumpTree($node, $querydb = false, $con = null) -{ - $opts = array('querydb' => $querydb, - 'con' => $con); - - $node->setIteratorOptions('pre', $opts); - - $indent = 0; - $lastLevel = $node->getNodeLevel(); - - foreach ($node as $n) - { - $nodeLevel = $n->getNodeLevel(); - $indent += $nodeLevel - $lastLevel; - echo str_repeat(' ', $indent); - echo $n->getNodePath() . " -> " . $n->getLabel(); - echo "\n"; - $lastLevel = $nodeLevel; - } -} - -try { - // Initialize Propel - Propel::init($conf_path); -} catch (Exception $e) { - die("Error initializing propel: ". $e->__toString()); -} - -try { - - $nodeKeySep = TestNodePeer::NPATH_SEP; - - echo "\nCreating initial tree:\n"; - echo "-------------------------------------\n"; - - $a = new Test(); - $a->setLabel("a"); - $a = TestNodePeer::createNewRootNode($a); - echo "Created 'a' as new root\n"; - - $b = new TestNode(); - $b->setLabel('b'); - $a->addChildNode($b); - echo "Added 'b' as first child of 'a'\n"; - - $c = new TestNode(); - $c->setLabel('c'); - $a->addChildNode($c); - echo "Added 'c' as second child of 'a'\n"; - - $f = new TestNode(); - $f->setLabel('f'); - $b->addChildNode($f); - echo "Added 'f' as first child of 'b'\n"; - - $d = new TestNode(); - $d->setLabel('d'); - $b->addChildNode($d, $f); - echo "Added 'd' as first child of 'b' before 'f' (insert before first child test - f is now second child)\n"; - - $e = new TestNode(); - $e->setLabel('e'); - $b->addChildNode($e, $f); - echo "Added 'e' as second child of 'b' before 'f' (insert before last child test - f is now third child)\n"; - - $g = new TestNode(); - $g->setLabel('g'); - $c->addChildNode($g); - echo "Added 'g' as first child of 'c'\n"; - - $h = new TestNode(); - $h->setLabel('h'); - $c->addChildNode($h); - echo "Added 'h' as second child of 'c'\n"; - - $i = new TestNode(); - $i->setLabel('i'); - $d->addChildNode($i); - echo "Added 'i' as first child of 'd'\n"; - - $j = new TestNode(); - $j->setLabel('j'); - $f->addChildNode($j); - echo "Added 'j' as first child of 'f'\n"; - - $k = new TestNode(); - $k->setLabel('k'); - $j->addChildNode($k); - echo "Added 'k' as first child of 'j'\n"; - - $l = new TestNode(); - $l->setLabel('l'); - $j->addChildNode($l); - echo "Added 'l' as second child of 'j'\n"; - - dumpTree($a); - - - echo "\n\nDeleting 'd' node sub-tree:\n"; - echo "-------------------------------------\n"; - - $d->delete(); - - dumpTree($a); - - - echo "\n\nMove node tests:\n"; - echo "-------------------------------------\n"; - - echo "Move 'j' sub-tree to 'b' before 'e' (move tree/insert before first child test):\n"; - $b->addChildNode($j, $e); - dumpTree($a); - - echo "\nMove 'j' sub-tree to 'c' (move tree after last child test):\n"; - $c->addChildNode($j); - dumpTree($a); - - echo "\nMove 'j' sub-tree to 'g' (move tree to first child test):\n"; - $g->addChildNode($j); - dumpTree($a); - - - echo "\n\nCreating new (in-memory) sub-tree:\n"; - echo "-------------------------------------\n"; - - $m = new TestNode(); - $m->setLabel('m'); - echo "Created 'm' as root of new sub-tree\n"; - - $n = new TestNode(); - $n->setLabel('n'); - $m->addChildNode($n); - echo "Added 'n' as first child of 'm'\n"; - - $o = new TestNode(); - $o->setLabel('o'); - $m->addChildNode($o); - echo "Added 'o' as second child of 'm'\n"; - - $r = new TestNode(); - $r->setLabel('r'); - $n->addChildNode($r); - echo "Added 'r' as first child of 'n'\n"; - - $p = new TestNode(); - $p->setLabel('p'); - $n->addChildNode($p, $r); - echo "Added 'p' as first child of 'n' before 'r' (insert before first child test - r is now second child)\n"; - - $q = new TestNode(); - $q->setLabel('q'); - $n->addChildNode($q, $r); - echo "Added 'q' as second child of 'n' before 'r' (insert before last child test - r is now third child)\n"; - - $s = new TestNode(); - $s->setLabel('s'); - $o->addChildNode($s); - echo "Added 's' as first child of 'o'\n"; - - $t = new TestNode(); - $t->setLabel('t'); - $o->addChildNode($t); - echo "Added 't' as second child of 'o'\n"; - - $u = new TestNode(); - $u->setLabel('u'); - $p->addChildNode($u); - echo "Added 'u' as first child of 'p'\n"; - - $v = new TestNode(); - $v->setLabel('v'); - $r->addChildNode($v); - echo "Added 'v' as first child of 'r'\n"; - - $w = new TestNode(); - $w->setLabel('w'); - $v->addChildNode($w); - echo "Added 'w' as first child of 'v'\n"; - - $x = new TestNode(); - $x->setLabel('x'); - $v->addChildNode($x); - echo "Added 'x' as second child of 'v'\n"; - - dumpTree($m); - - - echo "\n\nDeleting in-memory 'p' node sub-tree:\n"; - echo "-------------------------------------\n"; - - $p->delete(); - - dumpTree($m); - - - echo "\n\nMove in-memory node tests:\n"; - echo "-------------------------------------\n"; - - echo "Move 'v' sub-tree to 'n' before 'q' (move tree/insert before first child test):\n"; - $n->addChildNode($v, $q); - dumpTree($m); - - echo "\nMove 'v' sub-tree to 'o' (move tree after last child test):\n"; - $o->addChildNode($v); - dumpTree($m); - - echo "\nMove 'v' sub-tree to 's' (move tree to first child test):\n"; - $s->addChildNode($v); - dumpTree($m); - - - echo "\n\nAdd in-memory 'm' sub-tree to 'a':\n"; - echo "-------------------------------------\n"; - - $a->addChildNode($m); - - dumpTree($a); - - - echo "\n\nInsert new root node 'z' and retrieve descendants on demand (via querydb param in iterator):\n"; - echo "-------------------------------------\n"; - $z = new Test(); - $z->setLabel("z"); - $z = TestNodePeer::insertNewRootNode($z); - - dumpTree($z, true); - -} catch (Exception $e) { - die("Error creating initial tree: " . $e->__toString()); -} - -try { - - echo "\n\nTest retrieveRootNode() (without descendants)\n"; - echo "-------------------------------------\n"; - $root = TestNodePeer::retrieveRootNode(false); - dumpTree($root); - - - echo "\n\nTest retrieveRootNode() (with descendants)\n"; - echo "-------------------------------------\n"; - $root = TestNodePeer::retrieveRootNode(true); - dumpTree($root); - - $m_addr = array(1,1,3); - - echo "\n\nTest retrieveNodeByNP() for 'm' (without descendants)\n"; - echo "-------------------------------------\n"; - $node = TestNodePeer::retrieveNodeByNP(implode($nodeKeySep, $m_addr), false, false); - dumpTree($node); - - - echo "\n\nTest retrieveNodeByNP() for 'm' (with descendants)\n"; - echo "-------------------------------------\n"; - $node = TestNodePeer::retrieveNodeByNP(implode($nodeKeySep, $m_addr), false, true); - dumpTree($node); - - - echo "\n\nTest getAncestors() for 'x' in one query:\n"; - echo "-------------------------------------\n"; - - $criteria = new Criteria(); - $criteria->add(TestPeer::LABEL, 'x', Criteria::EQUAL); - - $nodes = TestNodePeer::retrieveNodes($criteria, true, false); - $ancestors = $nodes[0]->getAncestors(false); - - foreach ($ancestors as $ancestor) - echo $ancestor->getNodePath() . " -> " . $ancestor->getLabel() . "\n"; - - - echo "\n\nTest retrieveNodeByNP() for 'o' (with ancestors and descendants in one query):\n"; - echo "-------------------------------------\n"; - - $o_addr = array(1,1,3,2); - - $node = TestNodePeer::retrieveNodeByNP(implode($nodeKeySep, $o_addr), true, true); - - echo "ancestors:\n"; - foreach ($node->getAncestors(false) as $ancestor) - echo $ancestor->getNodePath() . " -> " . $ancestor->getLabel() . "\n"; - - echo "\ndescendants:\n"; - dumpTree($node); - - - echo "\n\nTest retrieveNodes() between 'b' and 'g' (without descendants)\n"; - echo "-------------------------------------\n"; - - $criteria = new Criteria(); - $criteria->add(TestPeer::LABEL, 'b', Criteria::GREATER_EQUAL); - $criteria->addAnd(TestPeer::LABEL, 'g', Criteria::LESS_EQUAL); - $criteria->addAscendingOrderByColumn(TestPeer::LABEL); - - $nodes = TestNodePeer::retrieveNodes($criteria, false, false); - - foreach ($nodes as $node) - echo $node->getNodePath() . " -> " . $node->getLabel() . "\n"; - - - echo "\n\nTest retrieveNodes() between 'b' and 'g' (with descendants)\n"; - echo "-------------------------------------\n"; - - $criteria = new Criteria(); - $criteria->add(TestPeer::LABEL, 'b', Criteria::GREATER_EQUAL); - $criteria->addAnd(TestPeer::LABEL, 'g', Criteria::LESS_EQUAL); - $criteria->addAscendingOrderByColumn(TestPeer::LABEL); - - $nodes = TestNodePeer::retrieveNodes($criteria, false, true); - - foreach ($nodes as $node) - { - dumpTree($node); - echo "\n"; - } - - -} catch (Exception $e) { - die("Error retrieving nodes: " . $e->__toString()); -} - -try { - - echo "\nCreating new tree:\n"; - echo "-------------------------------------\n"; - - $a = new Test(); - $a->setLabel("a"); - $a = TestNodePeer::createNewRootNode($a); - echo "Created 'a' as new root\n"; - - echo "\nAdding 10 child nodes:\n"; - echo "-------------------------------------\n"; - - $b = new TestNode(); - $b->setLabel('b'); - $a->addChildNode($b); - - $c = new TestNode(); - $c->setLabel('c'); - $a->addChildNode($c); - - $d = new TestNode(); - $d->setLabel('d'); - $a->addChildNode($d); - - $e = new TestNode(); - $e->setLabel('e'); - $a->addChildNode($e); - - $f = new TestNode(); - $f->setLabel('f'); - $a->addChildNode($f); - - $g = new TestNode(); - $g->setLabel('g'); - $a->addChildNode($g); - - $h = new TestNode(); - $h->setLabel('h'); - $a->addChildNode($h); - - $i = new TestNode(); - $i->setLabel('i'); - $a->addChildNode($i); - - $j = new TestNode(); - $j->setLabel('j'); - $a->addChildNode($j); - - $k = new TestNode(); - $k->setLabel('k'); - $a->addChildNode($k); - - echo "\ndescendants:\n"; - dumpTree($a); - - echo "\nRetrieving last node:\n"; - echo "-------------------------------------\n"; - - $last = $a->getLastChildNode(true); - echo "Last child node is '" . $last->getLabel() . "' (" . $last->getNodePath() . ")\n"; - -} catch (Exception $e) { - die("Error creating tree with > 10 nodes: " . $e->__toString()); -} - -if (!isset($argc)) echo "";