partkeepr

fork of partkeepr
git clone https://git.e1e0.net/partkeepr.git
Log | Files | Refs | Submodules | README | LICENSE

commit 1db3fe97138cbcc43858fe3aec5a96fd6037cfc7
parent 79b646bf4308bef5b938c0068c502023c5ba2fca
Author: Timo A. Hummel <felicitus@felicitus.org>
Date:   Mon, 25 Apr 2016 12:33:29 +0200

Merge pull request #655 from partkeepr/analysis-zEAZ2O

Applied fixes from StyleCI
Diffstat:
Mapp/AppKernel.php | 24++++++++++++++----------
Mapp/PartKeeprRequirements.php | 69++++++++++++++++++++++++++++++++++++---------------------------------
Mapp/SetupAppKernel.php | 6+++---
Mapp/SymfonyRequirements.php | 15+++++++--------
Mapp/autoload.php | 6+++---
Mapp/check.php | 18+++++++++---------
Msrc/PartKeepr/ApiDocBundle/DependencyInjection/PartKeeprApiDocExtension.php | 8+++-----
Msrc/PartKeepr/ApiDocBundle/Extractor/ApiDocExtractor.php | 14++++++--------
Msrc/PartKeepr/AuthBundle/Action/ChangePasswordAction.php | 26++++++++++++--------------
Msrc/PartKeepr/AuthBundle/Action/DeletePreferenceAction.php | 18++++++++----------
Msrc/PartKeepr/AuthBundle/Action/DeleteUserAction.php | 12++++++------
Msrc/PartKeepr/AuthBundle/Action/GetPreferencesAction.php | 10+++++-----
Msrc/PartKeepr/AuthBundle/Action/LoginAction.php | 15+++++++--------
Msrc/PartKeepr/AuthBundle/Action/PostUserAction.php | 15+++++++--------
Msrc/PartKeepr/AuthBundle/Action/PutUserAction.php | 18+++++++++---------
Msrc/PartKeepr/AuthBundle/Action/SetPreferenceAction.php | 16++++++++--------
Msrc/PartKeepr/AuthBundle/Command/ProtectUserCommand.php | 17++++++++---------
Msrc/PartKeepr/AuthBundle/Command/UnprotectUserCommand.php | 18++++++++----------
Msrc/PartKeepr/AuthBundle/Controller/DefaultController.php | 18+++++++++---------
Msrc/PartKeepr/AuthBundle/DataFixtures/LoadUserData.php | 15+++++++++------
Msrc/PartKeepr/AuthBundle/DependencyInjection/Configuration.php | 2+-
Msrc/PartKeepr/AuthBundle/DependencyInjection/PartKeeprAuthExtension.php | 2+-
Msrc/PartKeepr/AuthBundle/Entity/FOSUser.php | 1+
Msrc/PartKeepr/AuthBundle/Entity/User.php | 60+++++++++++++++++++++++++++++++++---------------------------
Msrc/PartKeepr/AuthBundle/Entity/UserPreference.php | 21+++++++++++----------
Msrc/PartKeepr/AuthBundle/Entity/UserProvider.php | 6++++--
Msrc/PartKeepr/AuthBundle/Exceptions/OldPasswordWrongException.php | 5+++--
Msrc/PartKeepr/AuthBundle/Exceptions/PasswordChangeNotAllowedException.php | 5+++--
Msrc/PartKeepr/AuthBundle/Exceptions/UserLimitReachedException.php | 5+++--
Msrc/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php | 5+++--
Msrc/PartKeepr/AuthBundle/Exceptions/UserProtectedException.php | 3++-
Msrc/PartKeepr/AuthBundle/PartKeeprAuthBundle.php | 1+
Msrc/PartKeepr/AuthBundle/Response/LoginResponse.php | 16+++++++---------
Msrc/PartKeepr/AuthBundle/Security/Authentication/AuthenticationProviderManager.php | 7++++---
Msrc/PartKeepr/AuthBundle/Security/EntryPoint/NullEntryPoint.php | 3++-
Msrc/PartKeepr/AuthBundle/Security/User/LegacyUserProvider.php | 9+++++----
Msrc/PartKeepr/AuthBundle/Services/UserPreferenceService.php | 40+++++++++++++++++++++-------------------
Msrc/PartKeepr/AuthBundle/Services/UserService.php | 64++++++++++++++++++++++++++++++++++------------------------------
Msrc/PartKeepr/AuthBundle/Tests/Controller/DefaultControllerTest.php | 20+++++++++-----------
Msrc/PartKeepr/AuthBundle/Tests/LegacyAuthTest.php | 35++++++++++++++++++-----------------
Msrc/PartKeepr/AuthBundle/Tests/Services/UserPreferenceServiceTest.php | 40++++++++++++++++++++--------------------
Msrc/PartKeepr/AuthBundle/Tests/UserPreferenceTest.php | 47+++++++++++++++++++++++------------------------
Msrc/PartKeepr/AuthBundle/Tests/UserTest.php | 163+++++++++++++++++++++++++++++++++++++++----------------------------------------
Msrc/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5Hash.php | 6+++---
Msrc/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5HashValidator.php | 4++--
Msrc/PartKeepr/AuthBundle/Validator/Constraints/Username.php | 8++++----
Msrc/PartKeepr/AuthBundle/Validator/Constraints/UsernameValidator.php | 4++--
Msrc/PartKeepr/CategoryBundle/Action/GetRootNodeAction.php | 11++++++-----
Msrc/PartKeepr/CategoryBundle/Action/MoveAction.php | 12++++++------
Msrc/PartKeepr/CategoryBundle/DataFixtures/AbstractCategoryDataLoader.php | 14+++++++-------
Msrc/PartKeepr/CategoryBundle/DependencyInjection/PartKeeprCategoryExtension.php | 2+-
Msrc/PartKeepr/CategoryBundle/Entity/AbstractCategory.php | 51++++++++++++++++++++++++++++++++-------------------
Msrc/PartKeepr/CategoryBundle/Entity/CategoryPathInterface.php | 7++++---
Msrc/PartKeepr/CategoryBundle/EventListener/RootCategoryListener.php | 6++----
Msrc/PartKeepr/CategoryBundle/Exception/MissingParentCategoryException.php | 2+-
Msrc/PartKeepr/CategoryBundle/Exception/OnlySingleRootNodeAllowedException.php | 6++----
Msrc/PartKeepr/CategoryBundle/Exception/RootMayNotBeDeletedException.php | 5+++--
Msrc/PartKeepr/CategoryBundle/Exception/RootMayNotBeMovedException.php | 2+-
Msrc/PartKeepr/CategoryBundle/Exception/RootNodeNotFoundException.php | 6+++---
Msrc/PartKeepr/CategoryBundle/PartKeeprCategoryBundle.php | 1+
Msrc/PartKeepr/CategoryBundle/Services/CategoryService.php | 18++++++++++--------
Msrc/PartKeepr/CategoryBundle/Tests/AbstractCategoryCreateTest.php | 66++++++++++++++++++++++++++++++++++--------------------------------
Msrc/PartKeepr/CategoryBundle/Tests/AbstractMoveCategoryTest.php | 36++++++++++++++++++------------------
Msrc/PartKeepr/CoreBundle/Action/SystemNoticeAcknowledgeAction.php | 10+++++-----
Msrc/PartKeepr/CoreBundle/Command/CheckForUpdatesCommand.php | 7++++---
Msrc/PartKeepr/CoreBundle/Command/ClearCronLoggerCommand.php | 8++++----
Msrc/PartKeepr/CoreBundle/Command/UpdateCategoryPathCommand.php | 19++++++++++---------
Msrc/PartKeepr/CoreBundle/Controller/DefaultController.php | 19++++++++++---------
Msrc/PartKeepr/CoreBundle/DependencyInjection/Configuration.php | 5+++--
Msrc/PartKeepr/CoreBundle/DependencyInjection/PartKeeprCoreExtension.php | 8++++----
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/BaseMigration.php | 9+++++----
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20150608120000.php | 5++---
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20150708120022.php | 95+++++++++++++++++++++++++++++++++++++++----------------------------------------
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20150724174030.php | 2+-
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20151001180120.php | 9++++-----
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20151002183125.php | 4+---
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20151031163951.php | 5++---
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20151208162723.php | 5++---
Msrc/PartKeepr/CoreBundle/DoctrineMigrations/Version20160103145302.php | 17++++++++---------
Msrc/PartKeepr/CoreBundle/Entity/BaseEntity.php | 44++++++++++++++++++++++++--------------------
Msrc/PartKeepr/CoreBundle/Entity/SystemNotice.php | 38+++++++++++++++++++++-----------------
Msrc/PartKeepr/CoreBundle/Exceptions/TranslatableException.php | 8+++++---
Msrc/PartKeepr/CoreBundle/PartKeeprCoreBundle.php | 1+
Msrc/PartKeepr/CoreBundle/PartKeeprVersion.php | 1+
Msrc/PartKeepr/CoreBundle/Services/SystemNoticeService.php | 3++-
Msrc/PartKeepr/CoreBundle/Services/SystemService.php | 123++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/PartKeepr/CoreBundle/Services/VersionService.php | 38++++++++++++++++++--------------------
Msrc/PartKeepr/CoreBundle/System/OperatingSystem.php | 45+++++++++++++++++++++++----------------------
Msrc/PartKeepr/CoreBundle/System/SystemInformationRecord.php | 7++++---
Msrc/PartKeepr/CoreBundle/Tests/SetupWebTestCase.php | 29+++++++++++++----------------
Msrc/PartKeepr/CoreBundle/Tests/SystemInformationTest.php | 21+++++++++++----------
Msrc/PartKeepr/CoreBundle/Tests/SystemNoticeTest.php | 20++++++++++----------
Msrc/PartKeepr/CoreBundle/Tests/VersionServiceTest.php | 19++++++++++---------
Msrc/PartKeepr/CoreBundle/Tests/WebTestCase.php | 10+++-------
Msrc/PartKeepr/CronLoggerBundle/Command/RunCronsCommand.php | 5+++--
Msrc/PartKeepr/CronLoggerBundle/Controller/CronRunnerController.php | 9+++++----
Msrc/PartKeepr/CronLoggerBundle/DependencyInjection/PartKeeprCronLoggerExtension.php | 4++--
Msrc/PartKeepr/CronLoggerBundle/Entity/CronLogger.php | 13++++++++-----
Msrc/PartKeepr/CronLoggerBundle/PartKeeprCronLoggerBundle.php | 2+-
Msrc/PartKeepr/CronLoggerBundle/Services/CronLoggerService.php | 26+++++++++++++-------------
Msrc/PartKeepr/CronLoggerBundle/Tests/CronLoggerTest.php | 19++++++++++---------
Msrc/PartKeepr/DistributorBundle/Entity/Distributor.php | 61+++++++++++++++++++++++++++++++++++--------------------------
Msrc/PartKeepr/DistributorBundle/PartKeeprDistributorBundle.php | 1+
Msrc/PartKeepr/DistributorBundle/Tests/DataFixtures/DistributorDataLoader.php | 5+++--
Msrc/PartKeepr/DoctrineReflectionBundle/Annotation/IgnoreIds.php | 1+
Msrc/PartKeepr/DoctrineReflectionBundle/Annotation/TargetService.php | 1+
Msrc/PartKeepr/DoctrineReflectionBundle/Annotation/VirtualField.php | 1+
Msrc/PartKeepr/DoctrineReflectionBundle/Command/GenerateEntityCommand.php | 10+++++-----
Msrc/PartKeepr/DoctrineReflectionBundle/DependencyInjection/Configuration.php | 2+-
Msrc/PartKeepr/DoctrineReflectionBundle/DependencyInjection/PartKeeprDoctrineReflectionExtension.php | 6+++---
Msrc/PartKeepr/DoctrineReflectionBundle/Exception/ExceptionWrapperHandler.php | 10+++++-----
Msrc/PartKeepr/DoctrineReflectionBundle/Filter/AdvancedSearchFilter.php | 180++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/PartKeepr/DoctrineReflectionBundle/Services/ReflectionService.php | 159++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/PartKeepr/ExportBundle/Controller/ExportController.php | 18++++++++++--------
Msrc/PartKeepr/ExportBundle/DependencyInjection/Compiler/CsvFormatPass.php | 5+++--
Msrc/PartKeepr/ExportBundle/DependencyInjection/Compiler/XmlExcelFormatPass.php | 5+++--
Msrc/PartKeepr/ExportBundle/EventListener/AbstractResponderViewListener.php | 18+++++++-----------
Msrc/PartKeepr/ExportBundle/EventListener/CsvResponderViewListener.php | 9+++++----
Msrc/PartKeepr/ExportBundle/EventListener/XmlExcelResponderViewListener.php | 2+-
Msrc/PartKeepr/ExportBundle/PartKeeprExportBundle.php | 2+-
Msrc/PartKeepr/FootprintBundle/Controller/FootprintAttachmentController.php | 5+++--
Msrc/PartKeepr/FootprintBundle/Controller/FootprintImageController.php | 5+++--
Msrc/PartKeepr/FootprintBundle/DataFixtures/CategoryDataLoader.php | 9++++++---
Msrc/PartKeepr/FootprintBundle/DependencyInjection/PartKeeprFootprintExtension.php | 6+++---
Msrc/PartKeepr/FootprintBundle/Entity/Footprint.php | 43+++++++++++++++++++++++--------------------
Msrc/PartKeepr/FootprintBundle/Entity/FootprintAttachment.php | 14++++++++------
Msrc/PartKeepr/FootprintBundle/Entity/FootprintCategory.php | 17++++++++++-------
Msrc/PartKeepr/FootprintBundle/Entity/FootprintImage.php | 12+++++++-----
Msrc/PartKeepr/FootprintBundle/Listeners/CategoryPathListener.php | 6++++--
Msrc/PartKeepr/FootprintBundle/PartKeeprFootprintBundle.php | 1+
Msrc/PartKeepr/FootprintBundle/Tests/CategoryCreateTest.php | 4++--
Msrc/PartKeepr/FootprintBundle/Tests/MoveActionTest.php | 3++-
Msrc/PartKeepr/FrontendBundle/Controller/IndexController.php | 58++++++++++++++++++++++++++++++----------------------------
Msrc/PartKeepr/FrontendBundle/PartKeeprFrontendBundle.php | 3+--
Msrc/PartKeepr/ImageBundle/Controller/ImageController.php | 56+++++++++++++++++++++++++++-----------------------------
Msrc/PartKeepr/ImageBundle/Controller/TemporaryImageController.php | 29+++++++++++++++--------------
Msrc/PartKeepr/ImageBundle/DependencyInjection/PartKeeprImageExtension.php | 5+++--
Msrc/PartKeepr/ImageBundle/Entity/CachedImage.php | 17+++++++++--------
Msrc/PartKeepr/ImageBundle/Entity/Image.php | 24++++++++++++------------
Msrc/PartKeepr/ImageBundle/Entity/TempImage.php | 4++--
Msrc/PartKeepr/ImageBundle/PartKeeprImageBundle.php | 1+
Msrc/PartKeepr/ImageBundle/Response/ImageResponse.php | 22++++++++++++----------
Msrc/PartKeepr/ImageBundle/Response/TemporaryImageUploadResponse.php | 11++++++-----
Msrc/PartKeepr/ImageBundle/Services/ImageService.php | 33+++++++++++++++++----------------
Msrc/PartKeepr/ImageBundle/Tests/ImageControllerTest.php | 26+++++++++++++-------------
Msrc/PartKeepr/ManufacturerBundle/Controller/ManufacturerIcLogoController.php | 5+++--
Msrc/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php | 61+++++++++++++++++++++++++++++++++++--------------------------
Msrc/PartKeepr/ManufacturerBundle/Entity/ManufacturerICLogo.php | 15++++++++-------
Msrc/PartKeepr/ManufacturerBundle/PartKeeprManufacturerBundle.php | 1+
Msrc/PartKeepr/ManufacturerBundle/Tests/DataFixtures/ManufacturerDataLoader.php | 6+++---
Msrc/PartKeepr/MimetypeIconsBundle/DependencyInjection/PartKeeprMimetypeIconsExtension.php | 5+++--
Msrc/PartKeepr/MimetypeIconsBundle/Services/MimetypeIconService.php | 10+++++-----
Msrc/PartKeepr/PartBundle/Action/AddStockAction.php | 21+++++++++++----------
Msrc/PartKeepr/PartBundle/Action/PartPutAction.php | 18+++++++++---------
Msrc/PartKeepr/PartBundle/Action/PostAction.php | 10++++------
Msrc/PartKeepr/PartBundle/Action/RemoveStockAction.php | 18++++++++++--------
Msrc/PartKeepr/PartBundle/Action/SetDefaultUnitAction.php | 13++++++-------
Msrc/PartKeepr/PartBundle/Action/SetStockAction.php | 19++++++++++---------
Msrc/PartKeepr/PartBundle/Controller/PartAttachmentController.php | 5+++--
Msrc/PartKeepr/PartBundle/Controller/PartController.php | 28+++++++++++++++-------------
Msrc/PartKeepr/PartBundle/DataFixtures/CategoryDataLoader.php | 9++++++---
Msrc/PartKeepr/PartBundle/DataFixtures/PartDataLoader.php | 23+++++++++++------------
Msrc/PartKeepr/PartBundle/DependencyInjection/PartKeeprPartExtension.php | 2+-
Msrc/PartKeepr/PartBundle/Entity/Part.php | 224+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Msrc/PartKeepr/PartBundle/Entity/PartAttachment.php | 25+++++++++++++++----------
Msrc/PartKeepr/PartBundle/Entity/PartCategory.php | 14++++++++------
Msrc/PartKeepr/PartBundle/Entity/PartDistributor.php | 35+++++++++++++++++++++--------------
Msrc/PartKeepr/PartBundle/Entity/PartImage.php | 12+++++++-----
Msrc/PartKeepr/PartBundle/Entity/PartManufacturer.php | 19+++++++++++--------
Msrc/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php | 249++++++++++++++++++++++++++++++++++++++++++-------------------------------------
Msrc/PartKeepr/PartBundle/Entity/PartParameter.php | 41++++++++++++++++++++++++-----------------
Msrc/PartKeepr/PartBundle/Exceptions/CategoryNotAssignedException.php | 5+++--
Msrc/PartKeepr/PartBundle/Exceptions/MinStockLevelOutOfRangeException.php | 6+++---
Msrc/PartKeepr/PartBundle/Exceptions/PackagingUnitOutOfRangeException.php | 6+++---
Msrc/PartKeepr/PartBundle/Exceptions/PartLimitExceededException.php | 4++--
Msrc/PartKeepr/PartBundle/Exceptions/StorageLocationNotAssignedException.php | 5+++--
Msrc/PartKeepr/PartBundle/Listeners/CategoryPathListener.php | 6++++--
Msrc/PartKeepr/PartBundle/Listeners/ImageAttachmentListener.php | 11++++++++---
Msrc/PartKeepr/PartBundle/Listeners/StockLevelListener.php | 7++++---
Msrc/PartKeepr/PartBundle/Services/PartMeasurementUnitService.php | 16++++++++--------
Msrc/PartKeepr/PartBundle/Services/PartService.php | 14+++++++-------
Msrc/PartKeepr/PartBundle/Tests/CategoryCreateTest.php | 5++---
Msrc/PartKeepr/PartBundle/Tests/Issues/DistributorAndManufacturerSearchTest.php | 77+++++++++++++++++++++++++++++++++++++++--------------------------------------
Msrc/PartKeepr/PartBundle/Tests/Issues/StockHistoryLostTest.php | 30++++++++++++++++--------------
Msrc/PartKeepr/PartBundle/Tests/MoveActionTest.php | 3++-
Msrc/PartKeepr/PartBundle/Tests/PartTest.php | 51++++++++++++++++++++++++++-------------------------
Msrc/PartKeepr/PartBundle/Tests/StockTest.php | 85++++++++++++++++++++++++++++++++++++++-----------------------------------------
Msrc/PartKeepr/ProjectBundle/Controller/ProjectAttachmentController.php | 5+++--
Msrc/PartKeepr/ProjectBundle/Controller/ProjectReportController.php | 94+++++++++++++++++++++++++++++++++++++++----------------------------------------
Msrc/PartKeepr/ProjectBundle/DataFixtures/ProjectFixtureLoader.php | 16++++++++--------
Msrc/PartKeepr/ProjectBundle/Entity/Project.php | 45+++++++++++++++++++++++++--------------------
Msrc/PartKeepr/ProjectBundle/Entity/ProjectAttachment.php | 15++++++++-------
Msrc/PartKeepr/ProjectBundle/Entity/ProjectPart.php | 35++++++++++++++++++++---------------
Msrc/PartKeepr/ProjectBundle/PartKeeprProjectBundle.php | 2+-
Msrc/PartKeepr/ProjectBundle/Tests/ProjectTest.php | 137+++++++++++++++++++++++++++++++++++++++----------------------------------------
Msrc/PartKeepr/RESTBundle/DependencyInjection/PartKeeprRESTExtension.php | 6+++---
Msrc/PartKeepr/RESTBundle/Request/ParamReader.php | 6+++---
Msrc/PartKeepr/SetupBundle/Command/ImportFootprintsCommand.php | 10+++++-----
Msrc/PartKeepr/SetupBundle/Command/ImportManufacturersCommand.php | 10+++++-----
Msrc/PartKeepr/SetupBundle/Command/ImportSiPrefixesCommand.php | 10+++++-----
Msrc/PartKeepr/SetupBundle/Command/ImportUnitsCommand.php | 10+++++-----
Msrc/PartKeepr/SetupBundle/Command/SetupDefaultPartUnitCommand.php | 10+++++-----
Msrc/PartKeepr/SetupBundle/Command/UpdateConfigCommand.php | 7++++---
Msrc/PartKeepr/SetupBundle/Controller/AdminUserSetupController.php | 34+++++++++++++++++-----------------
Msrc/PartKeepr/SetupBundle/Controller/CacheWarmupSetupController.php | 66+++++++++++++++++++++++++++++++++---------------------------------
Msrc/PartKeepr/SetupBundle/Controller/ExistingConfigParserController.php | 95++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/PartKeepr/SetupBundle/Controller/ExistingUserSetupController.php | 26++++++++++++++------------
Msrc/PartKeepr/SetupBundle/Controller/FileMigrationController.php | 55++++++++++++++++++++++++++++---------------------------
Msrc/PartKeepr/SetupBundle/Controller/FootprintSetupController.php | 22+++++++++++-----------
Msrc/PartKeepr/SetupBundle/Controller/ManufacturerSetupController.php | 25+++++++++++++------------
Msrc/PartKeepr/SetupBundle/Controller/PartUnitSetupController.php | 24+++++++++++++-----------
Msrc/PartKeepr/SetupBundle/Controller/SchemaMigrationSetupController.php | 18++++++++----------
Msrc/PartKeepr/SetupBundle/Controller/SchemaSetupController.php | 21+++++++++++----------
Msrc/PartKeepr/SetupBundle/Controller/SetupBaseController.php | 45++++++++++++++++++++++++---------------------
Msrc/PartKeepr/SetupBundle/Controller/SetupController.php | 64++++++++++++++++++++++++++++++++--------------------------------
Msrc/PartKeepr/SetupBundle/Controller/SiPrefixSetupController.php | 27++++++++++++---------------
Msrc/PartKeepr/SetupBundle/Controller/UnitSetupController.php | 22+++++++++++-----------
Msrc/PartKeepr/SetupBundle/DependencyInjection/PartKeeprSetupExtension.php | 6+++---
Msrc/PartKeepr/SetupBundle/PartKeeprSetupBundle.php | 2+-
Msrc/PartKeepr/SetupBundle/Services/ConfigSetupService.php | 151++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/PartKeepr/SetupBundle/Services/FootprintSetupService.php | 35+++++++++++++++++------------------
Msrc/PartKeepr/SetupBundle/Services/ManufacturerSetupService.php | 18++++++++----------
Msrc/PartKeepr/SetupBundle/Services/PartUnitSetupService.php | 15+++++++--------
Msrc/PartKeepr/SetupBundle/Services/SiPrefixSetupService.php | 20++++++++++----------
Msrc/PartKeepr/SetupBundle/Services/UnitSetupService.php | 33+++++++++++++++++----------------
Msrc/PartKeepr/SetupBundle/Tests/ExistingUsersSetupTest.php | 52++++++++++++++++++++++++++--------------------------
Msrc/PartKeepr/SetupBundle/Visitor/ConfigVisitor.php | 19++++++++++---------
Msrc/PartKeepr/SetupBundle/Visitor/LegacyConfigVisitor.php | 15+++++++--------
Msrc/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php | 33+++++++++++++++++++--------------
Msrc/PartKeepr/SiPrefixBundle/PartKeeprSiPrefixBundle.php | 4++--
Msrc/PartKeepr/SiPrefixBundle/Tests/Model/SiPrefixTest.php | 37+++++++++++++++++++++----------------
Msrc/PartKeepr/StatisticBundle/Command/CreateStatisticSnapshotCommand.php | 7++++---
Msrc/PartKeepr/StatisticBundle/Controller/StatisticController.php | 44++++++++++++++++++++++++--------------------
Msrc/PartKeepr/StatisticBundle/DependencyInjection/PartKeeprStatisticExtension.php | 2+-
Msrc/PartKeepr/StatisticBundle/Entity/StatisticSnapshot.php | 229++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Msrc/PartKeepr/StatisticBundle/Entity/StatisticSnapshotUnit.php | 168++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Msrc/PartKeepr/StatisticBundle/PartKeeprStatisticBundle.php | 1+
Msrc/PartKeepr/StatisticBundle/Services/StatisticService.php | 112++++++++++++++++++++++++++++++++++++++++----------------------------------------
Msrc/PartKeepr/StockBundle/Entity/StockEntry.php | 26+++++++++++++++-----------
Msrc/PartKeepr/StockBundle/PartKeeprStockBundle.php | 2+-
Msrc/PartKeepr/StorageLocationBundle/Controller/StorageLocationImageController.php | 5+++--
Msrc/PartKeepr/StorageLocationBundle/DataFixtures/CategoryDataLoader.php | 9++++++---
Msrc/PartKeepr/StorageLocationBundle/DataFixtures/StorageLocationLoader.php | 7++++---
Msrc/PartKeepr/StorageLocationBundle/DependencyInjection/PartKeeprStorageLocationExtension.php | 6+++---
Msrc/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php | 29+++++++++++++++++------------
Msrc/PartKeepr/StorageLocationBundle/Entity/StorageLocationCategory.php | 16++++++++++------
Msrc/PartKeepr/StorageLocationBundle/Entity/StorageLocationImage.php | 12+++++++-----
Msrc/PartKeepr/StorageLocationBundle/Listeners/CategoryPathListener.php | 6++++--
Msrc/PartKeepr/StorageLocationBundle/PartKeeprStorageLocationBundle.php | 1+
Msrc/PartKeepr/StorageLocationBundle/Tests/CategoryCreateTest.php | 5++---
Msrc/PartKeepr/StorageLocationBundle/Tests/MoveActionTest.php | 3++-
Msrc/PartKeepr/TipOfTheDayBundle/Action/GetTipHistoryCollectionAction.php | 11++++++-----
Msrc/PartKeepr/TipOfTheDayBundle/Action/MarkTipReadAction.php | 9+++++----
Msrc/PartKeepr/TipOfTheDayBundle/Action/MarkTipsAsUnreadAction.php | 11++++++-----
Msrc/PartKeepr/TipOfTheDayBundle/Command/SyncTipsCommand.php | 7+++----
Msrc/PartKeepr/TipOfTheDayBundle/DataFixtures/TipOfTheDayLoader.php | 7+++----
Msrc/PartKeepr/TipOfTheDayBundle/DependencyInjection/PartKeeprTipOfTheDayExtension.php | 2+-
Msrc/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDay.php | 8+++++---
Msrc/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDayHistory.php | 11+++++++----
Msrc/PartKeepr/TipOfTheDayBundle/PartKeeprTipOfTheDayBundle.php | 3++-
Msrc/PartKeepr/TipOfTheDayBundle/Services/TipOfTheDayService.php | 10+++++-----
Msrc/PartKeepr/TipOfTheDayBundle/Tests/SyncTipsTest.php | 11++++++-----
Msrc/PartKeepr/TipOfTheDayBundle/Tests/TipOfTheDayTest.php | 42+++++++++++++++++++++---------------------
Msrc/PartKeepr/UnitBundle/Entity/Unit.php | 25+++++++++++++++----------
Msrc/PartKeepr/UnitBundle/Tests/Model/UnitTest.php | 14+++++++-------
Msrc/PartKeepr/UploadedFileBundle/Annotation/UploadedFile.php | 1+
Msrc/PartKeepr/UploadedFileBundle/Annotation/UploadedFileCollection.php | 1+
Msrc/PartKeepr/UploadedFileBundle/Controller/FileController.php | 37+++++++++++++++++--------------------
Msrc/PartKeepr/UploadedFileBundle/Controller/TemporaryFileController.php | 35++++++++++++++++++-----------------
Msrc/PartKeepr/UploadedFileBundle/DependencyInjection/PartKeeprUploadedFileExtension.php | 8++++----
Msrc/PartKeepr/UploadedFileBundle/Entity/TempUploadedFile.php | 3++-
Msrc/PartKeepr/UploadedFileBundle/Entity/UploadedFile.php | 67++++++++++++++++++++++++++++++++++++++-----------------------------
Msrc/PartKeepr/UploadedFileBundle/EventListener/FileRemovalListener.php | 11+++--------
Msrc/PartKeepr/UploadedFileBundle/EventListener/TemporaryFileEventListener.php | 7+++----
Msrc/PartKeepr/UploadedFileBundle/Exceptions/DiskSpaceExhaustedException.php | 3++-
Msrc/PartKeepr/UploadedFileBundle/PartKeeprUploadedFileBundle.php | 5++---
Msrc/PartKeepr/UploadedFileBundle/Services/UploadedFileService.php | 38+++++++++++++++++++-------------------
Msrc/PartKeepr/UploadedFileBundle/Tests/FileControllerTest.php | 38++++++++++++++++++++------------------
Msrc/PartKeepr/UploadedFileBundle/Tests/TemporaryFileControllerTest.php | 123+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mweb/app.php | 4++--
Mweb/app_dev.php | 4++--
Mweb/setup/tests/check-php-prerequisites.php | 6+++---
Mweb/setup/tests/check-php.php | 2+-
Mweb/setup/tests/check.php | 17++++++++---------
284 files changed, 3498 insertions(+), 3201 deletions(-)

diff --git a/app/AppKernel.php b/app/AppKernel.php @@ -8,7 +8,7 @@ class AppKernel extends Kernel public function registerBundles() { // Base 3rd party bundles required for PartKeepr operation - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), @@ -31,11 +31,11 @@ class AppKernel extends Kernel new JMS\TranslationBundle\JMSTranslationBundle(), new \PartKeepr\RemoteFileLoader\PartKeeprRemoteFileLoaderBundle(), new \FR3D\LdapBundle\FR3DLdapBundle(), - new Knp\Bundle\GaufretteBundle\KnpGaufretteBundle() - ); + new Knp\Bundle\GaufretteBundle\KnpGaufretteBundle(), + ]; // Developer bundles - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Liip\FunctionalTestBundle\LiipFunctionalTestBundle(); @@ -64,7 +64,6 @@ class AppKernel extends Kernel $bundles[] = new PartKeepr\ExportBundle\PartKeeprExportBundle(); $bundles[] = new PartKeepr\StatisticBundle\PartKeeprStatisticBundle(); - return array_merge($bundles, $this->getCustomBundles()); } @@ -76,7 +75,7 @@ class AppKernel extends Kernel { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); - if ($this->getEnvironment() !== "test") { + if ($this->getEnvironment() !== 'test') { $customConfig = __DIR__.'/config/config_custom.yml'; if (file_exists($customConfig)) { @@ -88,19 +87,22 @@ class AppKernel extends Kernel /** * Returns any custom bundles for a custom setup. Override this * method in a custom AppKernel. + * * @return array */ - public function getCustomBundles () { + public function getCustomBundles() + { return []; } /** - * Override to allow different cache environments set by the environment variable PARTKEEPR_ENVIRONMENT + * Override to allow different cache environments set by the environment variable PARTKEEPR_ENVIRONMENT. + * * @return string */ public function getCacheDir() { - $environment = getenv("PARTKEEPR_ENVIRONMENT"); + $environment = getenv('PARTKEEPR_ENVIRONMENT'); if ($environment === false) { $environment = $this->environment; @@ -113,11 +115,13 @@ class AppKernel extends Kernel * Override to avoid stripping comments. * * @see https://github.com/partkeepr/PartKeepr/issues/438 + * * @param string $source * * @return string */ - public static function stripComments($source) { + public static function stripComments($source) + { return $source; } } diff --git a/app/PartKeeprRequirements.php b/app/PartKeeprRequirements.php @@ -10,67 +10,67 @@ class PartKeeprRequirements extends SymfonyRequirements parent::__construct(); $this->addRequirement( - ini_get("allow_url_fopen") || function_exists("curl_init"), + ini_get('allow_url_fopen') || function_exists('curl_init'), sprintf('No way to remotely load files detected'), sprintf('Either set <strong>allow_url_fopen=true</strong> or install the cURL extension')); $this->addRequirement( - function_exists("imagecreate"), + function_exists('imagecreate'), sprintf('GD library not found'), sprintf('Install the GD library extension')); $this->addRequirement( - function_exists("curl_init"), + function_exists('curl_init'), sprintf('CURL library not found'), sprintf('Install the CURL library extension')); - $this->addPhpIniRequirement("memory_limit", $this->getBytesIniSetting("memory_limit") > 128000000, + $this->addPhpIniRequirement('memory_limit', $this->getBytesIniSetting('memory_limit') > 128000000, false, - "Memory Limit too small", - sprintf("The php.ini memory_limit directive must be set to 128MB or higher. Your limit is set to %s", - ini_get("memory_limit"))); + 'Memory Limit too small', + sprintf('The php.ini memory_limit directive must be set to 128MB or higher. Your limit is set to %s', + ini_get('memory_limit'))); - $this->checkWritable(realpath(dirname(__FILE__)."/../data/")); - $this->checkWritable(realpath(dirname(__FILE__)."/../app/")); - $this->checkWritable(realpath(dirname(__FILE__)."/../web/")); + $this->checkWritable(realpath(dirname(__FILE__).'/../data/')); + $this->checkWritable(realpath(dirname(__FILE__).'/../app/')); + $this->checkWritable(realpath(dirname(__FILE__).'/../web/')); $this->addRecommendation( - function_exists("apc_fetch"), + function_exists('apc_fetch'), sprintf('PHP APCu cache not found'), sprintf('For best performance install the PHP APCu cache') ); - $this->addPhpIniRecommendation("max_execution_time", - ini_get("max_execution_time") > 30, + $this->addPhpIniRecommendation('max_execution_time', + ini_get('max_execution_time') > 30, true, sprintf('Maximum Execution Time might be too low'), sprintf('Your maximum execution time is set to %d seconds, which might be too low for low-end systems. If you encounter problems, please increase the value.', - ini_get("max_execution_time")) + ini_get('max_execution_time')) ); $this->addRequirement( - function_exists("mb_convert_case"), + function_exists('mb_convert_case'), sprintf('The PHP function mb_convert_case does not exist.'), sprintf('Please compile PHP with the mbstring functions in case you are using Gentoo, or install php-mbstring on RedHat, Fedora or CentOS.') ); - if (ini_get("opcache.enable")) { - if (version_compare(phpversion(), "7.0", "<")) { - $this->addPhpIniRequirement("opcache.save_comments", 1, + if (ini_get('opcache.enable')) { + if (version_compare(phpversion(), '7.0', '<')) { + $this->addPhpIniRequirement('opcache.save_comments', 1, false, - "opcache.save_comments must be on", - sprintf("The php.ini opcache.save_comments directive must be set to 1.")); + 'opcache.save_comments must be on', + sprintf('The php.ini opcache.save_comments directive must be set to 1.')); - $this->addPhpIniRequirement("opcache.load_comments", 1, + $this->addPhpIniRequirement('opcache.load_comments', 1, false, - "opcache.load_comments must be on", - sprintf("The php.ini opcache.load_comments directive must be set to 1.")); + 'opcache.load_comments must be on', + sprintf('The php.ini opcache.load_comments directive must be set to 1.')); } } } /** - * Checks if a path is writable. If not, generates a requirement + * Checks if a path is writable. If not, generates a requirement. * * @param $path string The path to check */ @@ -98,7 +98,7 @@ class PartKeeprRequirements extends SymfonyRequirements */ protected function getBytesIniSetting($setting) { - return (int)$this->returnBytes(ini_get($setting)); + return (int) $this->returnBytes(ini_get($setting)); } /** @@ -133,28 +133,31 @@ class PartKeeprRequirements extends SymfonyRequirements * * @param string $dir The directory to check * - * @return boolean True if the path is writable * @throws \Exception If the directory is not writable + * + * @return bool True if the path is writable */ protected function isWritableRecursive($dir) { if (!is_writable($dir)) { - throw new \Exception($dir." is not writable."); + throw new \Exception($dir.' is not writable.'); } $folder = opendir($dir); while ($file = readdir($folder)) { if ($file != '.' && $file != '..') { - if (!is_writable($dir."/".$file)) { + if (!is_writable($dir.'/'.$file)) { closedir($folder); - throw new \Exception($dir."/".$file." is not writable."); + throw new \Exception($dir.'/'.$file.' is not writable.'); } else { // Skip hidden directories - if ((is_dir($dir."/".$file)) && ($file[0]=='.')) continue; - if (is_dir($dir."/".$file)) { - if (!$this->isWritableRecursive($dir."/".$file)) { + if ((is_dir($dir.'/'.$file)) && ($file[0] == '.')) { + continue; + } + if (is_dir($dir.'/'.$file)) { + if (!$this->isWritableRecursive($dir.'/'.$file)) { closedir($folder); - throw new \Exception($dir."/".$file." is not writable."); + throw new \Exception($dir.'/'.$file.' is not writable.'); } } } diff --git a/app/SetupAppKernel.php b/app/SetupAppKernel.php @@ -11,7 +11,7 @@ class SetupAppKernel extends Kernel public function registerBundles() { // Base 3rd party bundles required for PartKeepr operation - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), @@ -19,10 +19,10 @@ class SetupAppKernel extends Kernel new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(), - ); + ]; // Developer bundles - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Liip\FunctionalTestBundle\LiipFunctionalTestBundle(); diff --git a/app/SymfonyRequirements.php b/app/SymfonyRequirements.php @@ -168,7 +168,7 @@ class PhpIniRequirement extends Requirement */ class RequirementCollection implements IteratorAggregate { - private $requirements = array(); + private $requirements = []; /** * Gets the current RequirementCollection as an Iterator. @@ -279,7 +279,7 @@ class RequirementCollection implements IteratorAggregate */ public function getRequirements() { - $array = array(); + $array = []; foreach ($this->requirements as $req) { if (!$req->isOptional()) { $array[] = $req; @@ -296,7 +296,7 @@ class RequirementCollection implements IteratorAggregate */ public function getFailedRequirements() { - $array = array(); + $array = []; foreach ($this->requirements as $req) { if (!$req->isFulfilled() && !$req->isOptional()) { $array[] = $req; @@ -313,7 +313,7 @@ class RequirementCollection implements IteratorAggregate */ public function getRecommendations() { - $array = array(); + $array = []; foreach ($this->requirements as $req) { if ($req->isOptional()) { $array[] = $req; @@ -330,7 +330,7 @@ class RequirementCollection implements IteratorAggregate */ public function getFailedRecommendations() { - $array = array(); + $array = []; foreach ($this->requirements as $req) { if (!$req->isFulfilled() && $req->isOptional()) { $array[] = $req; @@ -432,7 +432,7 @@ class SymfonyRequirements extends RequirementCollection ); if (version_compare($installedPhpVersion, self::REQUIRED_PHP_VERSION, '>=')) { - $timezones = array(); + $timezones = []; foreach (DateTimeZone::listAbbreviations() as $abbreviations) { foreach ($abbreviations as $abbreviation) { $timezones[$abbreviation['timezone_id']] = true; @@ -697,8 +697,7 @@ class SymfonyRequirements extends RequirementCollection || (extension_loaded('xcache') && ini_get('xcache.cacher')) || - (extension_loaded('wincache') && ini_get('wincache.ocenabled')) - ; + (extension_loaded('wincache') && ini_get('wincache.ocenabled')); $this->addRecommendation( $accelerator, diff --git a/app/autoload.php b/app/autoload.php @@ -1,13 +1,13 @@ <?php -use Doctrine\Common\Annotations\AnnotationRegistry; use Composer\Autoload\ClassLoader; +use Doctrine\Common\Annotations\AnnotationRegistry; /** - * @var $loader ClassLoader + * @var ClassLoader */ $loader = require __DIR__.'/../vendor/autoload.php'; -AnnotationRegistry::registerLoader(array($loader, 'loadClass')); +AnnotationRegistry::registerLoader([$loader, 'loadClass']); return $loader; diff --git a/app/check.php b/app/check.php @@ -19,7 +19,7 @@ echo PHP_EOL.PHP_EOL; echo '> Checking Symfony requirements:'.PHP_EOL.' '; -$messages = array(); +$messages = []; foreach ($symfonyRequirements->getRequirements() as $req) { /** @var $req Requirement */ if ($helpText = get_error_message($req, $lineSize)) { @@ -99,15 +99,15 @@ function echo_title($title, $style = null) function echo_style($style, $message) { // ANSI color codes - $styles = array( - 'reset' => "\033[0m", - 'red' => "\033[31m", - 'green' => "\033[32m", - 'yellow' => "\033[33m", - 'error' => "\033[37;41m", + $styles = [ + 'reset' => "\033[0m", + 'red' => "\033[31m", + 'green' => "\033[32m", + 'yellow' => "\033[33m", + 'error' => "\033[37;41m", 'success' => "\033[37;42m", - 'title' => "\033[34m", - ); + 'title' => "\033[34m", + ]; $supports = has_color_support(); echo($supports ? $styles[$style] : '').$message.($supports ? $styles['reset'] : ''); diff --git a/src/PartKeepr/ApiDocBundle/DependencyInjection/PartKeeprApiDocExtension.php b/src/PartKeepr/ApiDocBundle/DependencyInjection/PartKeeprApiDocExtension.php @@ -1,16 +1,14 @@ <?php - namespace PartKeepr\ApiDocBundle\DependencyInjection; - -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/ApiDocBundle/Extractor/ApiDocExtractor.php b/src/PartKeepr/ApiDocBundle/Extractor/ApiDocExtractor.php @@ -1,21 +1,20 @@ <?php -namespace PartKeepr\ApiDocBundle\Extractor; +namespace PartKeepr\ApiDocBundle\Extractor; -use Symfony\Component\Routing\Route; use Nelmio\ApiDocBundle\Annotation\ApiDoc; +use Symfony\Component\Routing\Route; class ApiDocExtractor extends \Nelmio\ApiDocBundle\Extractor\ApiDocExtractor { /** - * * Parses annotations for a given method, and adds new information to the given ApiDoc * annotation. Useful to extract information from the FOSRestBundle annotations. * * This method has been adjusted so that it can read annotations from the parent class. * - * @param ApiDoc $annotation - * @param Route $route + * @param ApiDoc $annotation + * @param Route $route * @param \ReflectionMethod $method */ protected function parseAnnotations(ApiDoc $annotation, Route $route, \ReflectionMethod $method) @@ -25,7 +24,7 @@ class ApiDocExtractor extends \Nelmio\ApiDocBundle\Extractor\ApiDocExtractor $declaringClass = $method->getDeclaringClass(); $parentClass = $declaringClass->getParentClass(); - $parentAnnotations = array(); + $parentAnnotations = []; if ($parentClass && $parentClass->hasMethod($method->getShortName())) { $parentMethod = $parentClass->getMethod($method->getShortName()); @@ -38,4 +37,4 @@ class ApiDocExtractor extends \Nelmio\ApiDocBundle\Extractor\ApiDocExtractor $handler->handle($annotation, $allAnnotations, $route, $method); } } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/AuthBundle/Action/ChangePasswordAction.php b/src/PartKeepr/AuthBundle/Action/ChangePasswordAction.php @@ -1,16 +1,14 @@ <?php -namespace PartKeepr\AuthBundle\Action; +namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; use FOS\UserBundle\Model\UserManagerInterface; use FOS\UserBundle\Util\UserManipulator; -use PartKeepr\AuthBundle\Entity\User; use PartKeepr\AuthBundle\Exceptions\OldPasswordWrongException; use PartKeepr\AuthBundle\Exceptions\PasswordChangeNotAllowedException; use PartKeepr\AuthBundle\Services\UserService; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Encoder\EncoderFactory; @@ -59,44 +57,44 @@ class ChangePasswordAction public function __invoke(Request $request) { - if ($this->container->hasParameter("partkeepr.auth.allow_password_change") && - $this->container->getParameter("partkeepr.auth.allow_password_change") === false) { + if ($this->container->hasParameter('partkeepr.auth.allow_password_change') && + $this->container->getParameter('partkeepr.auth.allow_password_change') === false) { throw new PasswordChangeNotAllowedException(); } $user = $this->userService->getUser(); - if (!$request->request->has("oldpassword") && !$request->request->has("newpassword")) { - throw new \Exception("old password and new password need to be specified"); + if (!$request->request->has('oldpassword') && !$request->request->has('newpassword')) { + throw new \Exception('old password and new password need to be specified'); } $FOSUser = $this->userManager->findUserByUsername($user->getUsername()); if ($FOSUser !== null) { $encoder = $this->encoderFactory->getEncoder($FOSUser); - $encoded_pass = $encoder->encodePassword($request->request->get("oldpassword"), $FOSUser->getSalt()); + $encoded_pass = $encoder->encodePassword($request->request->get('oldpassword'), $FOSUser->getSalt()); if ($FOSUser->getPassword() != $encoded_pass) { throw new OldPasswordWrongException(); } - $this->userManipulator->changePassword($user->getUsername(), $request->request->get("newpassword")); + $this->userManipulator->changePassword($user->getUsername(), $request->request->get('newpassword')); } else { if ($user->isLegacy()) { - if ($user->getPassword() !== md5($request->request->get("oldpassword"))) { + if ($user->getPassword() !== md5($request->request->get('oldpassword'))) { throw new OldPasswordWrongException(); } - $user->setNewPassword($request->request->get("newpassword")); + $user->setNewPassword($request->request->get('newpassword')); $this->userService->syncData($user); } else { - throw new \Exception("Cannot change password for LDAP users"); + throw new \Exception('Cannot change password for LDAP users'); } } - $user->setPassword(""); - $user->setNewPassword(""); + $user->setPassword(''); + $user->setNewPassword(''); return $user; } diff --git a/src/PartKeepr/AuthBundle/Action/DeletePreferenceAction.php b/src/PartKeepr/AuthBundle/Action/DeletePreferenceAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -6,11 +7,10 @@ use Dunglas\ApiBundle\Exception\RuntimeException; use PartKeepr\AuthBundle\Services\UserPreferenceService; use PartKeepr\AuthBundle\Services\UserService; use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException; -use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\Request; /** - * Returns the tree root node + * Returns the tree root node. */ class DeletePreferenceAction { @@ -39,21 +39,19 @@ class DeletePreferenceAction * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * @throws \Exception If the format is invalid - * + * @throws \Exception If the format is invalid * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request) { $user = $this->userService->getUser(); - if ($request->request->has("preferenceKey")) { - $this->userPreferenceService->deletePreference($user, $request->request->get("preferenceKey")); + if ($request->request->has('preferenceKey')) { + $this->userPreferenceService->deletePreference($user, $request->request->get('preferenceKey')); } else { - throw new \Exception("Invalid format"); + throw new \Exception('Invalid format'); } - - return; } } diff --git a/src/PartKeepr/AuthBundle/Action/DeleteUserAction.php b/src/PartKeepr/AuthBundle/Action/DeleteUserAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -12,7 +13,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** - * Custom API action deleting an user + * Custom API action deleting an user. */ class DeleteUserAction { @@ -46,21 +47,21 @@ class DeleteUserAction /** * Returns an item to delete. * - * @param Request $request + * @param Request $request * @param string|int $id * - * @return mixed - * * @throws NotFoundHttpException * @throws RuntimeException * @throws UserProtectedException + * + * @return mixed */ public function __invoke(Request $request, $id) { list($resourceType) = $this->extractAttributes($request); /** - * @var User $item + * @var User */ $item = $this->getItem($this->dataProvider, $resourceType, $id); @@ -71,7 +72,6 @@ class DeleteUserAction $this->userService->deleteFOSUser($item); $this->userPreferenceService->deletePreferences($item); - return $item; } } diff --git a/src/PartKeepr/AuthBundle/Action/GetPreferencesAction.php b/src/PartKeepr/AuthBundle/Action/GetPreferencesAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -7,13 +8,12 @@ use Dunglas\ApiBundle\Exception\RuntimeException; use PartKeepr\AuthBundle\Services\UserPreferenceService; use PartKeepr\AuthBundle\Services\UserService; use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException; -use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Serializer\Serializer; /** - * Returns the tree root node + * Returns the tree root node. */ class GetPreferencesAction { @@ -49,9 +49,9 @@ class GetPreferencesAction * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request) { @@ -61,7 +61,7 @@ class GetPreferencesAction list($resourceType) = $this->extractAttributes($request); - /** + /* * @var ResourceInterface $resourceType */ $serializedData = $this->serializer->normalize( diff --git a/src/PartKeepr/AuthBundle/Action/LoginAction.php b/src/PartKeepr/AuthBundle/Action/LoginAction.php @@ -1,9 +1,7 @@ <?php - namespace PartKeepr\AuthBundle\Action; - use Dunglas\ApiBundle\Action\ActionUtilTrait; use PartKeepr\AuthBundle\Services\UserPreferenceService; use PartKeepr\AuthBundle\Services\UserService; @@ -39,18 +37,19 @@ class LoginAction $this->userPreferenceService = $userPreferenceService; } - public function __invoke (Request $request) { + public function __invoke(Request $request) + { $user = $this->userService->getUser(); $userPreferences = $this->userPreferenceService->getPreferences($user); - $arrayUserPreferences = array(); + $arrayUserPreferences = []; foreach ($userPreferences as $userPreference) { - $arrayUserPreferences[] = array( - "preferenceKey" => $userPreference->getPreferenceKey(), - "preferenceValue" => $userPreference->getPreferenceValue() - ); + $arrayUserPreferences[] = [ + 'preferenceKey' => $userPreference->getPreferenceKey(), + 'preferenceValue' => $userPreference->getPreferenceValue(), + ]; } $user->setInitialUserPreferences(json_encode($arrayUserPreferences)); diff --git a/src/PartKeepr/AuthBundle/Action/PostUserAction.php b/src/PartKeepr/AuthBundle/Action/PostUserAction.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\AuthBundle\Action; +namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; use Dunglas\ApiBundle\Api\ResourceInterface; @@ -47,16 +47,16 @@ class PostUserAction * * @param Request $request * - * @return mixed - * * @throws NotFoundHttpException * @throws RuntimeException * @throws UserLimitReachedException + * + * @return mixed */ public function __invoke(Request $request) { /** - * @var $resourceType ResourceInterface + * @var ResourceInterface */ list($resourceType, $format) = $this->extractAttributes($request); @@ -64,9 +64,8 @@ class PostUserAction throw new UserLimitReachedException(); } /** - * @var User $data + * @var User */ - $data = $this->serializer->deserialize( $request->getContent(), $resourceType->getEntityClass(), @@ -78,8 +77,8 @@ class PostUserAction $data->setLegacy(false); $this->userService->syncData($data); - $data->setNewPassword(""); - $data->setPassword(""); + $data->setNewPassword(''); + $data->setPassword(''); return $data; } diff --git a/src/PartKeepr/AuthBundle/Action/PutUserAction.php b/src/PartKeepr/AuthBundle/Action/PutUserAction.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\AuthBundle\Action; +namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; use Dunglas\ApiBundle\Api\ResourceInterface; @@ -46,25 +46,25 @@ class PutUserAction /** * Create a new item. * - * @param Request $request + * @param Request $request * @param string|int $id * - * @return mixed - * * @throws NotFoundHttpException * @throws RuntimeException * @throws UserProtectedException * @throws UserLimitReachedException + * + * @return mixed */ public function __invoke(Request $request, $id) { - /** - * @var $resourceType ResourceInterface + /** + * @var ResourceInterface */ list($resourceType, $format) = $this->extractAttributes($request); /** - * @var User $data + * @var User */ $data = $this->getItem($this->dataProvider, $resourceType, $id); @@ -89,8 +89,8 @@ class PutUserAction } $this->userService->syncData($data); - $data->setNewPassword(""); - $data->setPassword(""); + $data->setNewPassword(''); + $data->setPassword(''); $data->setLegacy(false); return $data; diff --git a/src/PartKeepr/AuthBundle/Action/SetPreferenceAction.php b/src/PartKeepr/AuthBundle/Action/SetPreferenceAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -7,13 +8,12 @@ use Dunglas\ApiBundle\Exception\RuntimeException; use PartKeepr\AuthBundle\Services\UserPreferenceService; use PartKeepr\AuthBundle\Services\UserService; use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException; -use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Serializer\Serializer; /** - * Returns the tree root node + * Returns the tree root node. */ class SetPreferenceAction { @@ -49,10 +49,10 @@ class SetPreferenceAction * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * @throws \Exception If the format is invalid - * + * @throws \Exception If the format is invalid * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request) { @@ -60,16 +60,16 @@ class SetPreferenceAction $data = json_decode($request->getContent()); - if (property_exists($data, "preferenceKey") && property_exists($data, "preferenceValue")) { + if (property_exists($data, 'preferenceKey') && property_exists($data, 'preferenceValue')) { $preference = $this->userPreferenceService->setPreference($user, $data->preferenceKey, $data->preferenceValue); } else { - throw new \Exception("Invalid format"); + throw new \Exception('Invalid format'); } list($resourceType) = $this->extractAttributes($request); - /** + /* * @var ResourceInterface $resourceType */ diff --git a/src/PartKeepr/AuthBundle/Command/ProtectUserCommand.php b/src/PartKeepr/AuthBundle/Command/ProtectUserCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -12,26 +13,24 @@ class ProtectUserCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:user:protect'); - $this->setDescription("Protects a given user against changes"); - $this->addArgument("username", InputArgument::REQUIRED, "The username to protect against changes"); + $this->setDescription('Protects a given user against changes'); + $this->addArgument('username', InputArgument::REQUIRED, 'The username to protect against changes'); } public function execute(InputInterface $input, OutputInterface $output) { - $userService = $this->getContainer()->get("partkeepr.userservice"); + $userService = $this->getContainer()->get('partkeepr.userservice'); - $fosUser = $this->getContainer()->get("fos_user.user_manager")->findUserByUsername( - $input->getArgument("username") + $fosUser = $this->getContainer()->get('fos_user.user_manager')->findUserByUsername( + $input->getArgument('username') ); if ($fosUser === null) { - $output->writeln(sprintf("User %s not found", $input->getArgument("username"))); + $output->writeln(sprintf('User %s not found', $input->getArgument('username'))); } else { $user = $userService->getProxyUser($fosUser->getUsername(), $userService->getBuiltinProvider(), true); $userService->protect($user); - $output->writeln(sprintf("User %s protected against changes", $input->getArgument("username"))); + $output->writeln(sprintf('User %s protected against changes', $input->getArgument('username'))); } } } - - diff --git a/src/PartKeepr/AuthBundle/Command/UnprotectUserCommand.php b/src/PartKeepr/AuthBundle/Command/UnprotectUserCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -6,33 +7,30 @@ use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class UnprotectUserCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:user:unprotect'); - $this->setDescription("Unprotects a given user against changes"); - $this->addArgument("username", InputArgument::REQUIRED, "The username to unprotect against changes"); + $this->setDescription('Unprotects a given user against changes'); + $this->addArgument('username', InputArgument::REQUIRED, 'The username to unprotect against changes'); } public function execute(InputInterface $input, OutputInterface $output) { - $userService = $this->getContainer()->get("partkeepr.userservice"); + $userService = $this->getContainer()->get('partkeepr.userservice'); - $fosUser = $this->getContainer()->get("fos_user.user_manager")->findUserByUsername( - $input->getArgument("username") + $fosUser = $this->getContainer()->get('fos_user.user_manager')->findUserByUsername( + $input->getArgument('username') ); if ($fosUser === null) { - $output->writeln(sprintf("User %s not found", $input->getArgument("username"))); + $output->writeln(sprintf('User %s not found', $input->getArgument('username'))); } else { $user = $userService->getProxyUser($fosUser->getUsername(), $userService->getBuiltinProvider(), true); $userService->unprotect($user); - $output->writeln(sprintf("User %s unprotected against changes", $input->getArgument("username"))); + $output->writeln(sprintf('User %s unprotected against changes', $input->getArgument('username'))); } } } - - diff --git a/src/PartKeepr/AuthBundle/Controller/DefaultController.php b/src/PartKeepr/AuthBundle/Controller/DefaultController.php @@ -9,7 +9,6 @@ use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\Request\ParamFetcher; use PartKeepr\AuthBundle\Entity\FOSUser; use PartKeepr\AuthBundle\Entity\User; -use PartKeepr\AuthBundle\Response\LoginResponse; use PartKeepr\AuthBundle\Validator\Constraints\Username; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Routing; use Symfony\Component\HttpFoundation\Request; @@ -18,7 +17,7 @@ use Symfony\Component\HttpFoundation\Response; class DefaultController extends FOSRestController { /** - * Retrieves the salt for a given user + * Retrieves the salt for a given user. * * @Routing\Route("/api/users/getSalt", defaults={"method" = "post","_format" = "json"}) * @Routing\Method({"POST"}) @@ -34,16 +33,16 @@ class DefaultController extends FOSRestController $entityManager = $this->getDoctrine()->getManager(); /** - * @var $repository EntityRepository + * @var EntityRepository */ $repository = $entityManager->getRepository( 'PartKeepr\AuthBundle\Entity\FOSUser' ); /** - * @var $user FOSUser + * @var FOSUser */ - $user = $repository->findOneBy(array("username" => $paramFetcher->get("username"))); + $user = $repository->findOneBy(['username' => $paramFetcher->get('username')]); if ($user !== null) { return $user->getSalt(); @@ -53,16 +52,17 @@ class DefaultController extends FOSRestController } /** - * Logs out the user + * Logs out the user. * * @Routing\Route("/api/users/logout", defaults={"method" = "GET","_format" = "json"}) + * * @param Request $request */ - - public function logoutAction (Request $request) { + public function logoutAction(Request $request) + { $this->get('security.token_storage')->setToken(null); $request->getSession()->invalidate(); - return new Response("", 200); + return new Response('', 200); } } diff --git a/src/PartKeepr/AuthBundle/DataFixtures/LoadUserData.php b/src/PartKeepr/AuthBundle/DataFixtures/LoadUserData.php @@ -1,20 +1,23 @@ <?php + namespace PartKeepr\AuthBundle\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use PartKeepr\AuthBundle\Entity\FOSUser; -class LoadUserData extends AbstractFixture { - public function load (ObjectManager $manager) { +class LoadUserData extends AbstractFixture +{ + public function load(ObjectManager $manager) + { $admin = new FOSUser(); - $admin->setUsername("admin"); - $admin->setPassword("admin"); - $admin->setEmail("foo@bar.com"); + $admin->setUsername('admin'); + $admin->setPassword('admin'); + $admin->setEmail('foo@bar.com'); $manager->persist($admin); $manager->flush(); - $this->addReference("user.admin", $admin); + $this->addReference('user.admin', $admin); } } diff --git a/src/PartKeepr/AuthBundle/DependencyInjection/Configuration.php b/src/PartKeepr/AuthBundle/DependencyInjection/Configuration.php @@ -6,7 +6,7 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** - * This is the class that validates and merges configuration from your app/config files + * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ diff --git a/src/PartKeepr/AuthBundle/DependencyInjection/PartKeeprAuthExtension.php b/src/PartKeepr/AuthBundle/DependencyInjection/PartKeeprAuthExtension.php @@ -8,7 +8,7 @@ use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/AuthBundle/Entity/FOSUser.php b/src/PartKeepr/AuthBundle/Entity/FOSUser.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; diff --git a/src/PartKeepr/AuthBundle/Entity/User.php b/src/PartKeepr/AuthBundle/Entity/User.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; @@ -34,6 +35,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface /** * @Groups({"default"}) * @VirtualField(type="string") + * * @var string */ private $newPassword; @@ -42,6 +44,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface * @Assert\Email() * @Groups({"default"}) * @ORM\Column(length=255,nullable=true) + * * @var string */ private $email; @@ -52,11 +55,12 @@ class User extends BaseEntity implements UserInterface, EquatableInterface private $admin; /** - * Marks a user as a legacy user (=old md5 auth) + * Marks a user as a legacy user (=old md5 auth). + * * @ORM\Column(type="boolean") * @Groups({"default"}) * - * @var boolean + * @var bool */ private $legacy; @@ -77,7 +81,8 @@ class User extends BaseEntity implements UserInterface, EquatableInterface private $tipHistories; /** - * Holds the initial serialized user preferences + * Holds the initial serialized user preferences. + * * @VirtualField(type="string") * @Groups({"default"}) * @@ -86,7 +91,8 @@ class User extends BaseEntity implements UserInterface, EquatableInterface private $initialUserPreferences; /** - * Defines if the user is active + * Defines if the user is active. + * * @ORM\Column(type="boolean") * @Groups({"default"}) * @@ -96,6 +102,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface /** * Defines if the user is protected. Protection defines that the user may not be changed or removed. + * * @ORM\Column(type="boolean") * @Groups({"default"}) * @@ -127,17 +134,17 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Sets the admin flag + * Sets the admin flag. * - * @param boolean $bAdmin True if the user is an admin, false otherwise + * @param bool $bAdmin True if the user is an admin, false otherwise */ public function setAdmin($bAdmin) { - $this->admin = (boolean)$bAdmin; + $this->admin = (bool) $bAdmin; } /** - * @return boolean + * @return bool */ public function isProtected() { @@ -145,7 +152,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * @param boolean $protected + * @param bool $protected */ public function setProtected($protected) { @@ -153,9 +160,9 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Returns if the user is active + * Returns if the user is active. * - * @return boolean + * @return bool */ public function isActive() { @@ -163,9 +170,9 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Sets if the user is active + * Sets if the user is active. * - * @param boolean $active + * @param bool $active */ public function setActive($active) { @@ -221,7 +228,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Returns the authentification provider + * Returns the authentification provider. * * @return UserProvider */ @@ -231,7 +238,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Sets the authentification provider + * Sets the authentification provider. * * @param UserProvider $provider */ @@ -254,9 +261,9 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Returns the admin flag + * Returns the admin flag. * - * @return boolean True if the user is an admin + * @return bool True if the user is an admin */ public function isAdmin() { @@ -287,7 +294,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Sets the new password. Used for password changes + * Sets the new password. Used for password changes. * * @param string $password The new password */ @@ -303,7 +310,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface * * @param string $password The unhashed password * - * @return boolean true if the passwords match, false otherwise + * @return bool true if the passwords match, false otherwise */ public function comparePassword($password) { @@ -316,7 +323,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface * * @param string $hashedPassword The md5-hashed password * - * @return boolean true if the passwords match, false otherwise + * @return bool true if the passwords match, false otherwise */ public function compareHashedPassword($hashedPassword) { @@ -332,11 +339,11 @@ class User extends BaseEntity implements UserInterface, EquatableInterface */ public function updateSeen() { - $this->lastSeen = new \DateTime("now"); + $this->lastSeen = new \DateTime('now'); } /** - * Returns if the user is a legacy user + * Returns if the user is a legacy user. * * @return bool */ @@ -346,7 +353,7 @@ class User extends BaseEntity implements UserInterface, EquatableInterface } /** - * Marks a user as a legacy user + * Marks a user as a legacy user. * * @param bool|true $legacy */ @@ -367,22 +374,21 @@ class User extends BaseEntity implements UserInterface, EquatableInterface public function getRoles() { - return array(); + return []; } public function getSalt() { - return ""; + return ''; } public function eraseCredentials() { - } public function isEqualTo(UserInterface $user) { - if (!$user instanceof User) { + if (!$user instanceof self) { return false; } diff --git a/src/PartKeepr/AuthBundle/Entity/UserPreference.php b/src/PartKeepr/AuthBundle/Entity/UserPreference.php @@ -1,8 +1,8 @@ <?php + namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\AuthBundle\Entity\User; use PartKeepr\DoctrineReflectionBundle\Annotation\IgnoreIds; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use Symfony\Component\Serializer\Annotation\Groups; @@ -22,7 +22,8 @@ use Symfony\Component\Serializer\Annotation\Groups; class UserPreference { /** - * Defines the key of the user preference + * Defines the key of the user preference. + * * @ORM\Column(type="string",length=255) * @ORM\Id() * @@ -44,7 +45,8 @@ class UserPreference private $preferenceValue; /** - * Defines the user + * Defines the user. + * * @ORM\ManyToOne(targetEntity="PartKeepr\AuthBundle\Entity\User") * @ORM\Id() * @@ -52,9 +54,8 @@ class UserPreference */ private $user; - /** - * Sets the user for this entry + * Sets the user for this entry. * * @param \PartKeepr\AuthBundle\Entity\User $user */ @@ -64,7 +65,7 @@ class UserPreference } /** - * Returns the user associated with this entry + * Returns the user associated with this entry. * * @return \PartKeepr\AuthBundle\Entity\User */ @@ -74,7 +75,7 @@ class UserPreference } /** - * Sets the key for this user preference + * Sets the key for this user preference. * * @param string $key The key name */ @@ -84,7 +85,7 @@ class UserPreference } /** - * Returns the key of this entry + * Returns the key of this entry. * * @return string */ @@ -94,7 +95,7 @@ class UserPreference } /** - * Sets the value for this entry + * Sets the value for this entry. * * @param mixed $value */ @@ -104,7 +105,7 @@ class UserPreference } /** - * Returns the value for this entry + * Returns the value for this entry. * * @return mixed The value */ diff --git a/src/PartKeepr/AuthBundle/Entity/UserProvider.php b/src/PartKeepr/AuthBundle/Entity/UserProvider.php @@ -1,9 +1,10 @@ <?php + namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -18,6 +19,7 @@ class UserProvider extends BaseEntity /** * @ORM\Column(type="string", length=255) * @Groups({"default"}) + * * @var string */ private $type; @@ -25,6 +27,7 @@ class UserProvider extends BaseEntity /** * @ORM\Column(type="boolean") * @Groups({"default"}) + * * @var bool */ private $editable; @@ -65,5 +68,4 @@ class UserProvider extends BaseEntity { $this->type = $type; } - } diff --git a/src/PartKeepr/AuthBundle/Exceptions/OldPasswordWrongException.php b/src/PartKeepr/AuthBundle/Exceptions/OldPasswordWrongException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\AuthBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * Is thrown when the user specified a wrong old password + * Is thrown when the user specified a wrong old password. */ class OldPasswordWrongException extends TranslatableException { public function getMessageKey() { - return "Old password is wrong"; + return 'Old password is wrong'; } } diff --git a/src/PartKeepr/AuthBundle/Exceptions/PasswordChangeNotAllowedException.php b/src/PartKeepr/AuthBundle/Exceptions/PasswordChangeNotAllowedException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\AuthBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * Is thrown when the user may not change their password + * Is thrown when the user may not change their password. */ class PasswordChangeNotAllowedException extends TranslatableException { public function getMessageKey() { - return "Password change not allowed by the administrator"; + return 'Password change not allowed by the administrator'; } } diff --git a/src/PartKeepr/AuthBundle/Exceptions/UserLimitReachedException.php b/src/PartKeepr/AuthBundle/Exceptions/UserLimitReachedException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\AuthBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * Is thrown when the configured user limit is reached + * Is thrown when the configured user limit is reached. */ class UserLimitReachedException extends TranslatableException { public function getMessageKey() { - return "The maximum number of users is reached"; + return 'The maximum number of users is reached'; } } diff --git a/src/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php b/src/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\AuthBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * Is thrown when the user preference couldn't be found + * Is thrown when the user preference couldn't be found. */ class UserPreferenceNotFoundException extends TranslatableException { public function getMessageKey() { - return "The requested user preference was not found"; + return 'The requested user preference was not found'; } } diff --git a/src/PartKeepr/AuthBundle/Exceptions/UserProtectedException.php b/src/PartKeepr/AuthBundle/Exceptions/UserProtectedException.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; @@ -7,6 +8,6 @@ class UserProtectedException extends TranslatableException { public function getMessageKey() { - return "User is protected against changes"; + return 'User is protected against changes'; } } diff --git a/src/PartKeepr/AuthBundle/PartKeeprAuthBundle.php b/src/PartKeepr/AuthBundle/PartKeeprAuthBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/AuthBundle/Response/LoginResponse.php b/src/PartKeepr/AuthBundle/Response/LoginResponse.php @@ -1,29 +1,28 @@ <?php + namespace PartKeepr\AuthBundle\Response; use PartKeepr\AuthBundle\Entity\UserPreference; /** - * Class LoginResponse + * Class LoginResponse. * * Defines the login response for use with the REST API. - * - * @package PartKeepr\AuthBundle\Response */ -class LoginResponse { - +class LoginResponse +{ /** - * Holds the session id + * Holds the session id. */ public $sessionId; /** - * Holds the username + * Holds the username. */ public $username; /** - * Defines if the current user is an administrator + * Defines if the current user is an administrator. */ public $isAdmin; @@ -31,5 +30,4 @@ class LoginResponse { * @var UserPreference[] The user preferences */ public $userPreferences; - } diff --git a/src/PartKeepr/AuthBundle/Security/Authentication/AuthenticationProviderManager.php b/src/PartKeepr/AuthBundle/Security/Authentication/AuthenticationProviderManager.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Security\Authentication; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -13,7 +14,7 @@ use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\ProviderNotFoundException; /** - * Class AuthenticationProviderManager + * Class AuthenticationProviderManager. * * Re-implementation of the Symfony AuthenticationProviderManager to store the authentication provider in * a token property. @@ -51,7 +52,7 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface } $this->providers = $providers; - $this->eraseCredentials = (bool)$eraseCredentials; + $this->eraseCredentials = (bool) $eraseCredentials; } public function setEventDispatcher(EventDispatcherInterface $dispatcher) @@ -76,7 +77,7 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface $result = $provider->authenticate($token); if (null !== $result) { - $result->setAttribute("provider", get_class($provider)); + $result->setAttribute('provider', get_class($provider)); break; } } catch (AccountStatusException $e) { diff --git a/src/PartKeepr/AuthBundle/Security/EntryPoint/NullEntryPoint.php b/src/PartKeepr/AuthBundle/Security/EntryPoint/NullEntryPoint.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Security\EntryPoint; use Symfony\Component\HttpFoundation\Request; @@ -7,7 +8,7 @@ use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; /** - * Implements a NullEntryPoint to avoid that the user is being asked for their password in HTTP Basic Auth Scenarios + * Implements a NullEntryPoint to avoid that the user is being asked for their password in HTTP Basic Auth Scenarios. */ class NullEntryPoint implements AuthenticationEntryPointInterface { diff --git a/src/PartKeepr/AuthBundle/Security/User/LegacyUserProvider.php b/src/PartKeepr/AuthBundle/Security/User/LegacyUserProvider.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\AuthBundle\Security\User; +namespace PartKeepr\AuthBundle\Security\User; use Doctrine\ORM\EntityManager; use PartKeepr\AuthBundle\Entity\User; @@ -16,15 +16,16 @@ class LegacyUserProvider implements UserProviderInterface */ private $entityManager; - public function __construct (EntityManager $entityManager) { + public function __construct(EntityManager $entityManager) + { $this->entityManager = $entityManager; } public function loadUserByUsername($username) { - $repository = $this->entityManager->getRepository("PartKeepr\\AuthBundle\\Entity\\User"); + $repository = $this->entityManager->getRepository('PartKeepr\\AuthBundle\\Entity\\User'); - $user = $repository->findOneBy(array("username" => $username, "legacy" => true)); + $user = $repository->findOneBy(['username' => $username, 'legacy' => true]); if ($user !== null) { return $user; diff --git a/src/PartKeepr/AuthBundle/Services/UserPreferenceService.php b/src/PartKeepr/AuthBundle/Services/UserPreferenceService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Services; use Doctrine\ORM\EntityManager; @@ -31,11 +32,11 @@ class UserPreferenceService public function setPreference(User $user, $key, $value) { $dql = 'SELECT up FROM PartKeepr\AuthBundle\Entity\UserPreference up WHERE up.user = :user AND '; - $dql .= "up.preferenceKey = :key"; + $dql .= 'up.preferenceKey = :key'; $query = $this->entityManager->createQuery($dql); - $query->setParameter("user", $user); - $query->setParameter("key", $key); + $query->setParameter('user', $user); + $query->setParameter('key', $key); try { $userPreference = $query->getSingleResult(); @@ -55,13 +56,14 @@ class UserPreferenceService } /** - * Returns a specific preference value for the given user + * Returns a specific preference value for the given user. * * @param User $user The user to retrieve the preference for * @param string $key The preference key to retrieve * - * @return string The preference string - * @throws \PartKeepr\AuthBundle\Exceptions\UserPreferenceNotFoundException Thrown if the preference key was not found + * @throws \PartKeepr\AuthBundle\Exceptions\UserPreferenceNotFoundException Thrown if the preference key was not found + * + * @return string The preference string */ public function getPreferenceValue(User $user, $key) { @@ -71,7 +73,7 @@ class UserPreferenceService } /** - * Returns all preferences for the given user + * Returns all preferences for the given user. * * @param \PartKeepr\AuthBundle\Entity\User $user The user * @@ -82,28 +84,29 @@ class UserPreferenceService $dql = "SELECT up FROM PartKeepr\AuthBundle\Entity\UserPreference up WHERE up.user = :user"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("user", $user); + $query->setParameter('user', $user); return $query->getResult(); } /** - * Returns a specific preference object for the given user + * Returns a specific preference object for the given user. * * @param \PartKeepr\AuthBundle\Entity\User $user The user to retrieve the preference for * @param string $key The preference key to retrieve * - * @return UserPreference The preference object - * @throws \PartKeepr\AuthBundle\Exceptions\UserPreferenceNotFoundException Thrown if the preference key was not found + * @throws \PartKeepr\AuthBundle\Exceptions\UserPreferenceNotFoundException Thrown if the preference key was not found + * + * @return UserPreference The preference object */ public function getPreference(User $user, $key) { $dql = "SELECT up FROM PartKeepr\AuthBundle\Entity\UserPreference up WHERE up.user = :user AND "; - $dql .= "up.preferenceKey = :key"; + $dql .= 'up.preferenceKey = :key'; $query = $this->entityManager->createQuery($dql); - $query->setParameter("user", $user); - $query->setParameter("key", $key); + $query->setParameter('user', $user); + $query->setParameter('key', $key); try { $up = $query->getSingleResult(); @@ -123,11 +126,11 @@ class UserPreferenceService public function deletePreference(User $user, $key) { $dql = "DELETE FROM PartKeepr\AuthBundle\Entity\UserPreference up WHERE up.user = :user AND "; - $dql .= "up.preferenceKey = :key"; + $dql .= 'up.preferenceKey = :key'; $query = $this->entityManager->createQuery($dql); - $query->setParameter("user", $user); - $query->setParameter("key", $key); + $query->setParameter('user', $user); + $query->setParameter('key', $key); $query->execute(); } @@ -142,9 +145,8 @@ class UserPreferenceService $dql = "DELETE FROM PartKeepr\AuthBundle\Entity\UserPreference up WHERE up.user = :user"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("user", $user); + $query->setParameter('user', $user); $query->execute(); } - } diff --git a/src/PartKeepr/AuthBundle/Services/UserService.php b/src/PartKeepr/AuthBundle/Services/UserService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Services; use Doctrine\ORM\EntityManager; @@ -33,13 +34,13 @@ class UserService private $userManager; /** - * The maximum number of users allowed + * The maximum number of users allowed. * * @var int|bool */ private $userLimit; - const BUILTIN_PROVIDER = "Builtin"; + const BUILTIN_PROVIDER = 'Builtin'; public function __construct( TokenStorage $tokenStorage, @@ -62,7 +63,7 @@ class UserService */ public function getUser() { - $tokenProvider = $this->tokenStorage->getToken()->getAttribute("provider"); + $tokenProvider = $this->tokenStorage->getToken()->getAttribute('provider'); $provider = $this->getProvider($tokenProvider); $username = $this->tokenStorage->getToken()->getUsername(); @@ -87,19 +88,20 @@ class UserService return self::BUILTIN_PROVIDER; break; case 'FR3D\LdapBundle\Security\Authentication\LdapAuthenticationProvider': - return "LDAP"; + return 'LDAP'; break; default: - throw new \Exception("Unknown provider ".$providerClass); + throw new \Exception('Unknown provider '.$providerClass); } } /** - * Syncronizes the data of the given user with the FOSRestBundle + * Syncronizes the data of the given user with the FOSRestBundle. * - * @throws \Exception If the password was not set * * @param $user + * + * @throws \Exception If the password was not set */ public function syncData(User $user) { @@ -110,29 +112,29 @@ class UserService $FOSUser = $this->userManager->findUserByUsername($user->getUsername()); if ($FOSUser === null) { - - if ($user->getNewPassword() == "") { - throw new \Exception("Password must be set"); + if ($user->getNewPassword() == '') { + throw new \Exception('Password must be set'); } - $FOSUser = $this->userManipulator->create($user->getUsername(), $user->getNewPassword(), "", true, false); + $FOSUser = $this->userManipulator->create($user->getUsername(), $user->getNewPassword(), '', true, false); $user->setLegacy(false); } - if ($user->getNewPassword() != "") { + if ($user->getNewPassword() != '') { $this->userManipulator->changePassword($user->getUsername(), $user->getNewPassword()); } - $FOSUser->setEmail($user->getEmail()); $FOSUser->setEnabled($user->isActive()); } /** - * Deletes an user from the FOSUser system + * Deletes an user from the FOSUser system. + * * @param User $user */ - public function deleteFOSUser (User $user) { - if ($user->getProvider()->getType() !== self::BUILTIN_PROVIDER) { + public function deleteFOSUser(User $user) + { + if ($user->getProvider()->getType() !== self::BUILTIN_PROVIDER) { return; } @@ -145,7 +147,7 @@ class UserService public function getProviderByType($type) { - $provider = $this->entityManager->getRepository("PartKeeprAuthBundle:UserProvider")->findOneBy(array("type" => $type)); + $provider = $this->entityManager->getRepository('PartKeeprAuthBundle:UserProvider')->findOneBy(['type' => $type]); if ($provider !== null) { return $provider; @@ -174,25 +176,26 @@ class UserService * * @param $username * @param $provider - * @param bool|false $create If set to true + * @param bool|false $create If set to true * - * @return mixed|User * @throws NoResultException * @throws \Doctrine\ORM\NonUniqueResultException + * + * @return mixed|User */ public function getProxyUser($username, UserProvider $provider, $create = false) { /** - * @var QueryBuilder $queryBuilder + * @var QueryBuilder */ $queryBuilder = $this->entityManager->createQueryBuilder(); - $queryBuilder->select("u") - ->from("PartKeeprAuthBundle:User", "u") - ->where("u.provider = :provider") - ->andWhere("u.username = :username") - ->setParameter("provider", $provider) - ->setParameter("username", $username); + $queryBuilder->select('u') + ->from('PartKeeprAuthBundle:User', 'u') + ->where('u.provider = :provider') + ->andWhere('u.username = :username') + ->setParameter('provider', $provider) + ->setParameter('username', $username); $query = $queryBuilder->getQuery(); @@ -207,7 +210,6 @@ class UserService return $this->createProxyUser($username, $provider); } } - } private function createProxyUser($username, $provider) @@ -245,19 +247,21 @@ class UserService } /** - * Returns the number of users present in the system + * Returns the number of users present in the system. + * * @return mixed */ public function getUserCount() { - $dql = "SELECT COUNT(u) FROM PartKeepr\\AuthBundle\\Entity\\FOSUser u WHERE u.enabled = 1"; + $dql = 'SELECT COUNT(u) FROM PartKeepr\\AuthBundle\\Entity\\FOSUser u WHERE u.enabled = 1'; $query = $this->entityManager->createQuery($dql); return $query->getSingleScalarResult(); } /** - * Checks if the amount of users is exceeded + * Checks if the amount of users is exceeded. + * * @return bool */ public function checkUserLimit() diff --git a/src/PartKeepr/AuthBundle/Tests/Controller/DefaultControllerTest.php b/src/PartKeepr/AuthBundle/Tests/Controller/DefaultControllerTest.php @@ -3,8 +3,8 @@ namespace PartKeepr\AuthBundle\Tests\Controller; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; -use PartKeepr\CoreBundle\Tests\WebTestCase; use PartKeepr\AuthBundle\Entity\FOSUser; +use PartKeepr\CoreBundle\Tests\WebTestCase; class DefaultControllerTest extends WebTestCase { @@ -16,9 +16,9 @@ class DefaultControllerTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\AuthBundle\DataFixtures\LoadUserData', - ) + ] )->getReferenceRepository(); } @@ -26,24 +26,22 @@ class DefaultControllerTest extends WebTestCase { $client = static::createClient(); - $request = array("username" => "admin"); - + $request = ['username' => 'admin']; $client->request( 'POST', '/api/users/getSalt', - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); - $response = json_decode($client->getResponse()->getContent()); - $admin = $this->fixtures->getReference("user.admin"); + $admin = $this->fixtures->getReference('user.admin'); - /** + /* * @var FOSUser $admin */ diff --git a/src/PartKeepr/AuthBundle/Tests/LegacyAuthTest.php b/src/PartKeepr/AuthBundle/Tests/LegacyAuthTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Tests; use PartKeepr\AuthBundle\Entity\User; @@ -8,36 +9,36 @@ class LegacyAuthTest extends WebTestCase { public function setUp() { - $this->loadFixtures(array()); + $this->loadFixtures([]); } - public function testLegacyAuth () { - $user = new User("foobar"); - $user->setPassword(md5("admin")); + public function testLegacyAuth() + { + $user = new User('foobar'); + $user->setPassword(md5('admin')); $user->setLegacy(true); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($user); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($user); - $client = static::makeClient(false, array( - 'PHP_AUTH_USER' => "foobar", - 'PHP_AUTH_PW' => "admin" - ) + $client = static::makeClient(false, [ + 'PHP_AUTH_USER' => 'foobar', + 'PHP_AUTH_PW' => 'admin', + ] ); - $client->request("GET", "/api/system_status"); + $client->request('GET', '/api/system_status'); $this->assertEquals(200, $client->getResponse()->getStatusCode()); - $client = static::makeClient(false, array( - 'PHP_AUTH_USER' => "foobar", - 'PHP_AUTH_PW' => "admin2" - ) + $client = static::makeClient(false, [ + 'PHP_AUTH_USER' => 'foobar', + 'PHP_AUTH_PW' => 'admin2', + ] ); - $client->request("GET", "/api/system_status"); + $client->request('GET', '/api/system_status'); $this->assertEquals(401, $client->getResponse()->getStatusCode()); - } } diff --git a/src/PartKeepr/AuthBundle/Tests/Services/UserPreferenceServiceTest.php b/src/PartKeepr/AuthBundle/Tests/Services/UserPreferenceServiceTest.php @@ -1,63 +1,63 @@ <?php + namespace PartKeepr\AuthBundle\Tests\Services; -use PartKeepr\CoreBundle\Tests\WebTestCase; use PartKeepr\AuthBundle\Entity\User; +use PartKeepr\CoreBundle\Tests\WebTestCase; class UserPreferenceServiceTest extends WebTestCase { public function testBasics() { - $service = $this->getContainer()->get("partkeepr.user_preference_service"); - $userService = $this->getContainer()->get("partkeepr.userservice"); + $service = $this->getContainer()->get('partkeepr.user_preference_service'); + $userService = $this->getContainer()->get('partkeepr.userservice'); /** - * @var User $user + * @var User */ - $user = $userService->getProxyUser("admin", $userService->getBuiltinProvider(), true); + $user = $userService->getProxyUser('admin', $userService->getBuiltinProvider(), true); - $service->setPreference($user, "foo", "bar"); - $this->assertEquals("bar", $service->getPreferenceValue($user, "foo")); + $service->setPreference($user, 'foo', 'bar'); + $this->assertEquals('bar', $service->getPreferenceValue($user, 'foo')); $preferences = $service->getPreferences($user); - $this->assertInternalType("array", $preferences); + $this->assertInternalType('array', $preferences); $this->assertArrayHasKey(0, $preferences); $this->assertEquals(get_class($preferences[0]), "PartKeepr\AuthBundle\Entity\UserPreference"); - $this->assertEquals("bar", $preferences[0]->getPreferenceValue()); - $this->assertEquals("foo", $preferences[0]->getPreferenceKey()); + $this->assertEquals('bar', $preferences[0]->getPreferenceValue()); + $this->assertEquals('foo', $preferences[0]->getPreferenceKey()); $this->assertEquals($user, $preferences[0]->getUser()); - $preference = $service->getPreference($user, "foo"); + $preference = $service->getPreference($user, 'foo'); $this->assertEquals(get_class($preference), "PartKeepr\AuthBundle\Entity\UserPreference"); - $this->assertEquals("bar", $preference->getPreferenceValue()); - $this->assertEquals("foo", $preference->getPreferenceKey()); + $this->assertEquals('bar', $preference->getPreferenceValue()); + $this->assertEquals('foo', $preference->getPreferenceKey()); $this->assertEquals($user, $preference->getUser()); - $service->deletePreference($user, "foo"); + $service->deletePreference($user, 'foo'); $preferences = $service->getPreferences($user); $this->assertEquals(0, count($preferences)); - } public function testGetPreferenceException() { - $service = $this->getContainer()->get("partkeepr.user_preference_service"); - $userService = $this->getContainer()->get("partkeepr.userservice"); + $service = $this->getContainer()->get('partkeepr.user_preference_service'); + $userService = $this->getContainer()->get('partkeepr.userservice'); /** - * @var User $user + * @var User */ - $user = $this->getContainer()->get("partkeepr.userservice")->getProxyUser("admin", + $user = $this->getContainer()->get('partkeepr.userservice')->getProxyUser('admin', $userService->getBuiltinProvider(), true); $this->setExpectedException("PartKeepr\AuthBundle\Exceptions\UserPreferenceNotFoundException"); - $service->getPreference($user, "BLA"); + $service->getPreference($user, 'BLA'); } } diff --git a/src/PartKeepr/AuthBundle/Tests/UserPreferenceTest.php b/src/PartKeepr/AuthBundle/Tests/UserPreferenceTest.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\AuthBundle\Tests; +namespace PartKeepr\AuthBundle\Tests; use PartKeepr\CoreBundle\Tests\WebTestCase; @@ -9,9 +9,9 @@ class UserPreferenceTest extends WebTestCase public function setUp() { $this->loadFixtures( - array( + [ 'PartKeepr\AuthBundle\DataFixtures\LoadUserData', - ) + ] )->getReferenceRepository(); } @@ -19,47 +19,46 @@ class UserPreferenceTest extends WebTestCase { $client = static::makeClient(true); - $request = array( - "preferenceKey" => "foobar", - "preferenceValue" => "1234", - ); + $request = [ + 'preferenceKey' => 'foobar', + 'preferenceValue' => '1234', + ]; $client->request( 'POST', '/api/user_preferences', - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("object", $response, var_export($client->getResponse()->getContent(), true)); + $this->assertInternalType('object', $response, var_export($client->getResponse()->getContent(), true)); - $this->assertObjectHasAttribute("preferenceKey", $response); - $this->assertObjectHasAttribute("preferenceValue", $response); - $this->assertEquals("foobar", $response->preferenceKey); - $this->assertEquals("1234", $response->preferenceValue); + $this->assertObjectHasAttribute('preferenceKey', $response); + $this->assertObjectHasAttribute('preferenceValue', $response); + $this->assertEquals('foobar', $response->preferenceKey); + $this->assertEquals('1234', $response->preferenceValue); $client->request( 'GET', '/api/user_preferences', - array(), - array(), - array('CONTENT_TYPE' => 'application/json') + [], + [], + ['CONTENT_TYPE' => 'application/json'] ); $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("array", $response); + $this->assertInternalType('array', $response); $preference = $response[0]; - $this->assertObjectHasAttribute("preferenceKey", $preference); - $this->assertObjectHasAttribute("preferenceValue", $preference); - $this->assertEquals("foobar", $preference->preferenceKey); - $this->assertEquals("1234", $preference->preferenceValue); - + $this->assertObjectHasAttribute('preferenceKey', $preference); + $this->assertObjectHasAttribute('preferenceValue', $preference); + $this->assertEquals('foobar', $preference->preferenceKey); + $this->assertEquals('1234', $preference->preferenceValue); } } diff --git a/src/PartKeepr/AuthBundle/Tests/UserTest.php b/src/PartKeepr/AuthBundle/Tests/UserTest.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\AuthBundle\Tests; +namespace PartKeepr\AuthBundle\Tests; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -19,13 +19,12 @@ class UserTest extends WebTestCase public function setUp() { /** - * @var ORMExecutor $ormExecutor + * @var ORMExecutor */ $ormExecutor = $this->loadFixtures( - array( + [ 'PartKeepr\AuthBundle\DataFixtures\LoadUserData', - )); - + ]); $this->fixtures = $ormExecutor->getReferenceRepository(); } @@ -34,117 +33,116 @@ class UserTest extends WebTestCase { $client = static::makeClient(true); - $data = array( - "username" => "foobartest", - "newPassword" => "1234", - ); + $data = [ + 'username' => 'foobartest', + 'newPassword' => '1234', + ]; - $client->request("POST", "/api/users", array(), array(), array(), json_encode($data)); + $client->request('POST', '/api/users', [], [], [], json_encode($data)); $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(201, $client->getResponse()->getStatusCode()); - $this->assertEquals("foobartest", $response->{"username"}); - $this->assertEmpty($response->{"password"}); - $this->assertEmpty($response->{"newPassword"}); - $this->assertFalse($response->{"legacy"}); + $this->assertEquals('foobartest', $response->{'username'}); + $this->assertEmpty($response->{'password'}); + $this->assertEmpty($response->{'newPassword'}); + $this->assertFalse($response->{'legacy'}); } public function testChangeUserPassword() { - $builtinProvider = $this->getContainer()->get("partkeepr.userservice")->getBuiltinProvider(); + $builtinProvider = $this->getContainer()->get('partkeepr.userservice')->getBuiltinProvider(); - $user = new User("bernd"); - $user->setPassword(md5("admin")); + $user = new User('bernd'); + $user->setPassword(md5('admin')); $user->setLegacy(true); $user->setProvider($builtinProvider); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($user); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($user); $client = static::makeClient(true); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($user); - $client->request("GET", $iri); + $client->request('GET', $iri); $response = json_decode($client->getResponse()->getContent()); - $response->{"newPassword"} = "foobar"; + $response->{'newPassword'} = 'foobar'; - $client->request("PUT", $iri, array(), array(), array(), json_encode($response)); + $client->request('PUT', $iri, [], [], [], json_encode($response)); $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); - $this->assertEmpty($response->{"password"}); - $this->assertEmpty($response->{"newPassword"}); - $this->assertFalse($response->{"legacy"}); + $this->assertEmpty($response->{'password'}); + $this->assertEmpty($response->{'newPassword'}); + $this->assertFalse($response->{'legacy'}); } public function testSelfChangeUserPassword() { - $builtinProvider = $this->getContainer()->get("partkeepr.userservice")->getBuiltinProvider(); + $builtinProvider = $this->getContainer()->get('partkeepr.userservice')->getBuiltinProvider(); - $user = new User("bernd2"); - $user->setPassword(md5("admin")); + $user = new User('bernd2'); + $user->setPassword(md5('admin')); $user->setLegacy(true); $user->setProvider($builtinProvider); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($user); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($user); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($user); - $client = static::makeClient(false, array( - 'PHP_AUTH_USER' => "bernd2", - 'PHP_AUTH_PW' => "admin", - ) + $client = static::makeClient(false, [ + 'PHP_AUTH_USER' => 'bernd2', + 'PHP_AUTH_PW' => 'admin', + ] ); - $iriConverter = $this->getContainer()->get("api.iri_converter"); - $iri = $iriConverter->getIriFromItem($user)."/changePassword"; + $iriConverter = $this->getContainer()->get('api.iri_converter'); + $iri = $iriConverter->getIriFromItem($user).'/changePassword'; - $parameters = array( - "oldpassword" => "admin", - "newpassword" => "foobar", - ); + $parameters = [ + 'oldpassword' => 'admin', + 'newpassword' => 'foobar', + ]; - $client->request("PUT", $iri, $parameters); + $client->request('PUT', $iri, $parameters); $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); - $this->assertFalse($response->{"legacy"}); - $this->assertEmpty($response->{"password"}); - $this->assertEmpty($response->{"newPassword"}); - - $client = static::makeClient(false, array( - 'PHP_AUTH_USER' => "bernd2", - 'PHP_AUTH_PW' => "foobar", - ) + $this->assertFalse($response->{'legacy'}); + $this->assertEmpty($response->{'password'}); + $this->assertEmpty($response->{'newPassword'}); + + $client = static::makeClient(false, [ + 'PHP_AUTH_USER' => 'bernd2', + 'PHP_AUTH_PW' => 'foobar', + ] ); - $client->request("PUT", $iri, $parameters); + $client->request('PUT', $iri, $parameters); $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(500, $client->getResponse()->getStatusCode()); - $this->assertObjectHasAttribute("@type", $response); - $this->assertEquals("Error", $response->{"@type"}); + $this->assertObjectHasAttribute('@type', $response); + $this->assertEquals('Error', $response->{'@type'}); } public function testUserProtect() { /** - * @var FOSUser $fosUser + * @var FOSUser */ - $fosUser = $this->fixtures->getReference("user.admin"); - $userService = $this->getContainer()->get("partkeepr.userservice"); - + $fosUser = $this->fixtures->getReference('user.admin'); + $userService = $this->getContainer()->get('partkeepr.userservice'); $user = $userService->getProxyUser($fosUser->getUsername(), $userService->getBuiltinProvider(), true); - /** + /* * @var User $user */ $userService->protect($user); @@ -153,41 +151,40 @@ class UserTest extends WebTestCase $client = static::makeClient(true); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($user); $data = [ - "username" => "foo", + 'username' => 'foo', ]; - $client->request("PUT", $iri, array(), array(), array(), json_encode($data)); + $client->request('PUT', $iri, [], [], [], json_encode($data)); $response = json_decode($client->getResponse()->getContent()); $exception = new UserProtectedException(); $this->assertEquals(500, $client->getResponse()->getStatusCode()); - $this->assertObjectHasAttribute("hydra:description", $response); - $this->assertEquals($exception->getMessageKey(), $response->{"hydra:description"}); + $this->assertObjectHasAttribute('hydra:description', $response); + $this->assertEquals($exception->getMessageKey(), $response->{'hydra:description'}); - $client->request("DELETE", $iri); + $client->request('DELETE', $iri); $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(500, $client->getResponse()->getStatusCode()); - $this->assertObjectHasAttribute("hydra:description", $response); - $this->assertEquals($exception->getMessageKey(), $response->{"hydra:description"}); + $this->assertObjectHasAttribute('hydra:description', $response); + $this->assertEquals($exception->getMessageKey(), $response->{'hydra:description'}); } public function testUserUnprotect() { /** - * @var FOSUser $fosUser + * @var FOSUser */ - $fosUser = $this->fixtures->getReference("user.admin"); - $userService = $this->getContainer()->get("partkeepr.userservice"); - + $fosUser = $this->fixtures->getReference('user.admin'); + $userService = $this->getContainer()->get('partkeepr.userservice'); $user = $userService->getProxyUser($fosUser->getUsername(), $userService->getBuiltinProvider(), true); - /** + /* * @var User $user */ $userService->unprotect($user); @@ -206,27 +203,27 @@ class UserTest extends WebTestCase { $client = static::makeClient(true); - $data = array( - "username" => "preferenceuser", - "newPassword" => "1234", - ); + $data = [ + 'username' => 'preferenceuser', + 'newPassword' => '1234', + ]; - $client->request("POST", "/api/users", array(), array(), array(), json_encode($data)); + $client->request('POST', '/api/users', [], [], [], json_encode($data)); - $userPreferenceService = $this->getContainer()->get("partkeepr.user_preference_service"); - $userService = $this->getContainer()->get("partkeepr.userservice"); + $userPreferenceService = $this->getContainer()->get('partkeepr.user_preference_service'); + $userService = $this->getContainer()->get('partkeepr.userservice'); /** - * @var User $user + * @var User */ - $user = $userService->getProxyUser("preferenceuser", $userService->getBuiltinProvider(), true); + $user = $userService->getProxyUser('preferenceuser', $userService->getBuiltinProvider(), true); - $userPreferenceService->setPreference($user, "foo", "bar"); + $userPreferenceService->setPreference($user, 'foo', 'bar'); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($user); - $client->request("DELETE", $iri); + $client->request('DELETE', $iri); $this->assertEquals(204, $client->getResponse()->getStatusCode()); $this->assertEmpty($client->getResponse()->getContent()); diff --git a/src/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5Hash.php b/src/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5Hash.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; @@ -9,5 +10,5 @@ use Symfony\Component\Validator\Constraint; */ class PasswordMD5Hash extends Constraint { - public $message = "The password must be an MD5 hash of exactly 32 characters in length"; -}- \ No newline at end of file + public $message = 'The password must be an MD5 hash of exactly 32 characters in length'; +} diff --git a/src/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5HashValidator.php b/src/PartKeepr/AuthBundle/Validator/Constraints/PasswordMD5HashValidator.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; @@ -15,4 +16,4 @@ class PasswordMD5HashValidator extends ConstraintValidator ->addViolation(); } } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/AuthBundle/Validator/Constraints/Username.php b/src/PartKeepr/AuthBundle/Validator/Constraints/Username.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; @@ -7,7 +8,7 @@ use Symfony\Component\Validator\Constraint; * @Annotation * @Target({"PROPERTY", "METHOD", "ANNOTATION"}) */ - -class Username extends Constraint { +class Username extends Constraint +{ public $message = "The username must be 3-50 characters in length and may only contain the following characters: a-z, A-Z, 0-9, an underscore (_), a backslash (\), a slash (/), a dot (.) or a dash (-)"; -}- \ No newline at end of file +} diff --git a/src/PartKeepr/AuthBundle/Validator/Constraints/UsernameValidator.php b/src/PartKeepr/AuthBundle/Validator/Constraints/UsernameValidator.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\AuthBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; @@ -15,4 +16,4 @@ class UsernameValidator extends ConstraintValidator ->addViolation(); } } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/CategoryBundle/Action/GetRootNodeAction.php b/src/PartKeepr/CategoryBundle/Action/GetRootNodeAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -10,7 +11,7 @@ use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\Request; /** - * Returns the tree root node + * Returns the tree root node. */ class GetRootNodeAction { @@ -31,20 +32,20 @@ class GetRootNodeAction * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request) { list($resourceType) = $this->extractAttributes($request); - /** + /* * @var ResourceInterface $resourceType */ $repository = $this->manager->getRepository($resourceType->getEntityClass()); - /** + /* * @var $repository AbstractTreeRepository */ $rootNodes = $repository->getRootNodes(); diff --git a/src/PartKeepr/CategoryBundle/Action/MoveAction.php b/src/PartKeepr/CategoryBundle/Action/MoveAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -13,7 +14,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** - * Returns the tree root node + * Returns the tree root node. */ class MoveAction { @@ -49,9 +50,9 @@ class MoveAction * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException|RootNodeNotFoundException|RootMayNotBeMovedException|MissingParentCategoryException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -59,11 +60,10 @@ class MoveAction $entity = $this->getItem($this->dataProvider, $resourceType, $id); - $parentId = $request->request->get("parent"); + $parentId = $request->request->get('parent'); $parentEntity = $this->iriConverter->getItemFromIri($parentId); - if ($parentEntity === null) { throw new MissingParentCategoryException($parentId); } @@ -76,6 +76,6 @@ class MoveAction $this->registry->getManager()->flush(); - return new Response($request->request->get("parent")); + return new Response($request->request->get('parent')); } } diff --git a/src/PartKeepr/CategoryBundle/DataFixtures/AbstractCategoryDataLoader.php b/src/PartKeepr/CategoryBundle/DataFixtures/AbstractCategoryDataLoader.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; @@ -10,24 +11,24 @@ abstract class AbstractCategoryDataLoader extends AbstractFixture { $entityClass = $this->getEntityClass(); $rootNode = new $entityClass(); - $rootNode->setName("Root Node"); + $rootNode->setName('Root Node'); $firstCategory = new $entityClass(); $firstCategory->setParent($rootNode); - $firstCategory->setName("First Category"); + $firstCategory->setName('First Category'); $secondCategory = new $entityClass(); $secondCategory->setParent($firstCategory); - $secondCategory->setName("Second Category"); + $secondCategory->setName('Second Category'); $manager->persist($rootNode); $manager->persist($firstCategory); $manager->persist($secondCategory); $manager->flush(); - $this->addReference($this->getReferencePrefix() . ".root", $rootNode); - $this->addReference($this->getReferencePrefix() . ".first", $firstCategory); - $this->addReference($this->getReferencePrefix() . ".second", $secondCategory); + $this->addReference($this->getReferencePrefix().'.root', $rootNode); + $this->addReference($this->getReferencePrefix().'.first', $firstCategory); + $this->addReference($this->getReferencePrefix().'.second', $secondCategory); } /** @@ -39,5 +40,4 @@ abstract class AbstractCategoryDataLoader extends AbstractFixture * @return string Returns the prefix for the reference */ abstract protected function getReferencePrefix(); - } diff --git a/src/PartKeepr/CategoryBundle/DependencyInjection/PartKeeprCategoryExtension.php b/src/PartKeepr/CategoryBundle/DependencyInjection/PartKeeprCategoryExtension.php @@ -8,7 +8,7 @@ use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/CategoryBundle/Entity/AbstractCategory.php b/src/PartKeepr/CategoryBundle/Entity/AbstractCategory.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; @@ -8,7 +9,6 @@ use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** - * * @ORM\MappedSuperclass() * @ORM\Table(indexes={@ORM\Index(columns={"lft"}),@ORM\Index(columns={"rgt"})}) * @@ -20,33 +20,39 @@ use Symfony\Component\Serializer\Annotation\Groups; abstract class AbstractCategory extends BaseEntity { /** - * The parent category. This needs to be re-defined in the class with the proper relations + * The parent category. This needs to be re-defined in the class with the proper relations. + * * @var */ protected $parent; /** - * The "left" property of the nested set + * The "left" property of the nested set. + * * @ORM\Column(type="integer") * * @Gedmo\TreeLeft - * @var integer + * + * @var int */ private $lft; /** - * The "right" property of the nested set + * The "right" property of the nested set. + * * @ORM\Column(type="integer") * * @Gedmo\TreeRight - * @var integer + * + * @var int */ private $rgt; /** * @Gedmo\TreeLevel * @ORM\Column(name="lvl", type="integer") - * @var integer + * + * @var int */ private $lvl; @@ -57,7 +63,8 @@ abstract class AbstractCategory extends BaseEntity private $root; /** - * The name of the category + * The name of the category. + * * @ORM\Column(length=128) * @Groups({"default"}) * @@ -66,7 +73,8 @@ abstract class AbstractCategory extends BaseEntity private $name; /** - * The description of the category + * The description of the category. + * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) * @@ -76,16 +84,18 @@ abstract class AbstractCategory extends BaseEntity /** * @Groups({"default"}) + * * @var bool */ public $expanded = true; - public function __construct () { + public function __construct() + { $this->children = new ArrayCollection(); } /** - * Sets the name of this category + * Sets the name of this category. * * @param string $name The name to set */ @@ -95,7 +105,7 @@ abstract class AbstractCategory extends BaseEntity } /** - * Returns the name of this category + * Returns the name of this category. * * @return string The category name */ @@ -104,9 +114,8 @@ abstract class AbstractCategory extends BaseEntity return $this->name; } - /** - * Returns the level of this category + * Returns the level of this category. * * @return int */ @@ -116,7 +125,7 @@ abstract class AbstractCategory extends BaseEntity } /** - * Sets the description for this category + * Sets the description for this category. * * @param string $description The description of this category */ @@ -126,7 +135,7 @@ abstract class AbstractCategory extends BaseEntity } /** - * Returns the description of this category + * Returns the description of this category. * * @return string The description */ @@ -141,6 +150,7 @@ abstract class AbstractCategory extends BaseEntity * @return int The left value * * (non-PHPdoc) + * * @see DoctrineExtensions\NestedSet.Node::getLeftValue() */ public function getLeftValue() @@ -167,6 +177,7 @@ abstract class AbstractCategory extends BaseEntity * @return int The right value * * (non-PHPdoc) + * * @see DoctrineExtensions\NestedSet.Node::getRightValue() */ public function getRightValue() @@ -175,7 +186,7 @@ abstract class AbstractCategory extends BaseEntity } /** - * Sets the "right" value of the nested set + * Sets the "right" value of the nested set. * * @param $rgt int The right value * @@ -189,7 +200,8 @@ abstract class AbstractCategory extends BaseEntity } /** - * Sets the root of the tree + * Sets the root of the tree. + * * @param $root */ public function setRoot($root) @@ -198,7 +210,8 @@ abstract class AbstractCategory extends BaseEntity } /** - * Returns the root of the tree + * Returns the root of the tree. + * * @return mixed */ public function getRoot() diff --git a/src/PartKeepr/CategoryBundle/Entity/CategoryPathInterface.php b/src/PartKeepr/CategoryBundle/Entity/CategoryPathInterface.php @@ -1,20 +1,21 @@ <?php -namespace PartKeepr\CategoryBundle\Entity; +namespace PartKeepr\CategoryBundle\Entity; interface CategoryPathInterface { /** - * Sets the category path + * Sets the category path. * * @param string $categoryPath The category path */ public function setCategoryPath($categoryPath); /** - * Generates the category path + * Generates the category path. * * @param string $pathSeparator The path separator + * * @return string The category path */ public function generateCategoryPath($pathSeparator); diff --git a/src/PartKeepr/CategoryBundle/EventListener/RootCategoryListener.php b/src/PartKeepr/CategoryBundle/EventListener/RootCategoryListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\EventListener; use Doctrine\ORM\Event\OnFlushEventArgs; @@ -23,7 +24,7 @@ class RootCategoryListener extends ContainerAware } /** - * Checks that only one root category exists + * Checks that only one root category exists. * * @param OnFlushEventArgs $eventArgs The event arguments as given by Doctrine */ @@ -33,7 +34,6 @@ class RootCategoryListener extends ContainerAware $uow = $entityManager->getUnitOfWork(); foreach ($uow->getScheduledEntityInsertions() as $insertion) { - if (is_a($insertion, $this->container->get($this->service)->getEntityClass())) { $this->checkForRoot($insertion); } @@ -50,7 +50,6 @@ class RootCategoryListener extends ContainerAware $this->ensureRootStays($deletion); } } - } protected function ensureRootstays(AbstractCategory $category) @@ -70,7 +69,6 @@ class RootCategoryListener extends ContainerAware throw new OnlySingleRootNodeAllowedException(); } } catch (RootNodeNotFoundException $e) { - } } } diff --git a/src/PartKeepr/CategoryBundle/Exception/MissingParentCategoryException.php b/src/PartKeepr/CategoryBundle/Exception/MissingParentCategoryException.php @@ -1,7 +1,7 @@ <?php + namespace PartKeepr\CategoryBundle\Exception; class MissingParentCategoryException extends \Exception { - } diff --git a/src/PartKeepr/CategoryBundle/Exception/OnlySingleRootNodeAllowedException.php b/src/PartKeepr/CategoryBundle/Exception/OnlySingleRootNodeAllowedException.php @@ -1,13 +1,11 @@ <?php - namespace PartKeepr\CategoryBundle\Exception; - class OnlySingleRootNodeAllowedException extends \Exception { - public function __construct($message = "", $code = 0, \Exception $previous = null) + public function __construct($message = '', $code = 0, \Exception $previous = null) { - parent::__construct("There may be only one root node", $code, $previous); + parent::__construct('There may be only one root node', $code, $previous); } } diff --git a/src/PartKeepr/CategoryBundle/Exception/RootMayNotBeDeletedException.php b/src/PartKeepr/CategoryBundle/Exception/RootMayNotBeDeletedException.php @@ -1,10 +1,11 @@ <?php + namespace PartKeepr\CategoryBundle\Exception; class RootMayNotBeDeletedException extends \Exception { - public function __construct($message = "", $code = 0, \Exception $previous = null) + public function __construct($message = '', $code = 0, \Exception $previous = null) { - parent::__construct("The root node may not be deleted", $code, $previous); + parent::__construct('The root node may not be deleted', $code, $previous); } } diff --git a/src/PartKeepr/CategoryBundle/Exception/RootMayNotBeMovedException.php b/src/PartKeepr/CategoryBundle/Exception/RootMayNotBeMovedException.php @@ -1,7 +1,7 @@ <?php + namespace PartKeepr\CategoryBundle\Exception; class RootMayNotBeMovedException extends \Exception { - } diff --git a/src/PartKeepr/CategoryBundle/Exception/RootNodeNotFoundException.php b/src/PartKeepr/CategoryBundle/Exception/RootNodeNotFoundException.php @@ -1,12 +1,12 @@ <?php -namespace PartKeepr\CategoryBundle\Exception; +namespace PartKeepr\CategoryBundle\Exception; class RootNodeNotFoundException extends \Exception { - public function __construct($message = "", $code = 0, \Exception $previous = null) + public function __construct($message = '', $code = 0, \Exception $previous = null) { - $message = "Root Category not found"; + $message = 'Root Category not found'; parent::__construct($message, $code, $previous); } } diff --git a/src/PartKeepr/CategoryBundle/PartKeeprCategoryBundle.php b/src/PartKeepr/CategoryBundle/PartKeeprCategoryBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/CategoryBundle/Services/CategoryService.php b/src/PartKeepr/CategoryBundle/Services/CategoryService.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\CategoryBundle\Services; +namespace PartKeepr\CategoryBundle\Services; use Doctrine\ORM\EntityManager; use Gedmo\Tree\Entity\Repository\AbstractTreeRepository; @@ -29,10 +29,11 @@ class CategoryService } /** - * Returns the root node for a tree + * Returns the root node for a tree. * - * @return AbstractCategory * @throws RootNodeNotFoundException + * + * @return AbstractCategory */ public function getRootNode() { @@ -47,12 +48,13 @@ class CategoryService return $rootNode; } - public function getEntityClass () { + public function getEntityClass() + { return $this->entityClass; } /** - * Creates the root node for a tree if it doesn't exist + * Creates the root node for a tree if it doesn't exist. */ public function ensureRootNodeExists() { @@ -60,10 +62,10 @@ class CategoryService $this->getRootNode(); } catch (RootNodeNotFoundException $e) { /** - * @var AbstractCategory $rootNode + * @var AbstractCategory */ - $rootNode = new $this->entityClass; - $rootNode->setName("Root Category"); + $rootNode = new $this->entityClass(); + $rootNode->setName('Root Category'); $this->entityManager->persist($rootNode); $this->entityManager->flush(); diff --git a/src/PartKeepr/CategoryBundle/Tests/AbstractCategoryCreateTest.php b/src/PartKeepr/CategoryBundle/Tests/AbstractCategoryCreateTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CategoryBundle\Tests; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -15,83 +16,84 @@ abstract class AbstractCategoryCreateTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ $this->getFixtureLoaderClass(), - ) + ] )->getReferenceRepository(); } - public function testCreateCategory () { + public function testCreateCategory() + { $client = static::makeClient(true); - $rootCategory = $this->fixtures->getReference($this->getReferencePrefix().".root"); + $rootCategory = $this->fixtures->getReference($this->getReferencePrefix().'.root'); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); - $request = array( - "parent" => $iriConverter->getIriFromItem($rootCategory), - "name" => "test" - ); + $request = [ + 'parent' => $iriConverter->getIriFromItem($rootCategory), + 'name' => 'test', + ]; - $resource = $this->getContainer()->get("api.resource_collection")->getResourceForEntity($this->getResourceClass()); + $resource = $this->getContainer()->get('api.resource_collection')->getResourceForEntity($this->getResourceClass()); $iri = $iriConverter->getIriFromResource($resource); $client->request( 'POST', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $responseObject = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("object", $responseObject); + $this->assertInternalType('object', $responseObject); - $this->assertObjectHasAttribute("@id", $responseObject); - $this->assertObjectHasAttribute("name", $responseObject); - - $item = $iriConverter->getItemFromIri($responseObject->{"@id"}); + $this->assertObjectHasAttribute('@id', $responseObject); + $this->assertObjectHasAttribute('name', $responseObject); + $item = $iriConverter->getItemFromIri($responseObject->{'@id'}); $this->assertNotNull($item->getParent()); $this->assertEquals($item->getParent()->getId(), $rootCategory->getId()); } - public function testCreateRootCategory () { + public function testCreateRootCategory() + { $client = static::makeClient(true); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); - $request = array( - "name" => "test" - ); + $request = [ + 'name' => 'test', + ]; - $resource = $this->getContainer()->get("api.resource_collection")->getResourceForEntity($this->getResourceClass()); + $resource = $this->getContainer()->get('api.resource_collection')->getResourceForEntity($this->getResourceClass()); $iri = $iriConverter->getIriFromResource($resource); $client->request( 'POST', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $responseObject = json_decode($client->getResponse()->getContent()); - $this->assertObjectHasAttribute("@type", $responseObject); - $this->assertObjectHasAttribute("hydra:description", $responseObject); + $this->assertObjectHasAttribute('@type', $responseObject); + $this->assertObjectHasAttribute('hydra:description', $responseObject); - $this->assertEquals("There may be only one root node", $responseObject->{"hydra:description"}); + $this->assertEquals('There may be only one root node', $responseObject->{'hydra:description'}); } abstract public function getFixtureLoaderClass(); diff --git a/src/PartKeepr/CategoryBundle/Tests/AbstractMoveCategoryTest.php b/src/PartKeepr/CategoryBundle/Tests/AbstractMoveCategoryTest.php @@ -1,11 +1,11 @@ <?php -namespace PartKeepr\CategoryBundle\Tests; +namespace PartKeepr\CategoryBundle\Tests; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; use Dunglas\ApiBundle\Api\IriConverter; -use PartKeepr\CoreBundle\Tests\WebTestCase; use PartKeepr\CategoryBundle\Entity\AbstractCategory; +use PartKeepr\CoreBundle\Tests\WebTestCase; abstract class AbstractMoveCategoryTest extends WebTestCase { @@ -17,9 +17,9 @@ abstract class AbstractMoveCategoryTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ $this->getFixtureLoaderClass(), - ) + ] )->getReferenceRepository(); } @@ -28,37 +28,37 @@ abstract class AbstractMoveCategoryTest extends WebTestCase $client = static::makeClient(true); /** - * @var $secondCategory AbstractCategory - * @var $rootCategory AbstractCategory + * @var AbstractCategory + * @var $rootCategory AbstractCategory */ - $secondCategory = $this->fixtures->getReference($this->getReferencePrefix().".second"); - $rootCategory = $this->fixtures->getReference($this->getReferencePrefix().".root"); + $secondCategory = $this->fixtures->getReference($this->getReferencePrefix().'.second'); + $rootCategory = $this->fixtures->getReference($this->getReferencePrefix().'.root'); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($secondCategory); - $iri .= "/move"; + $iri .= '/move'; $targetIri = $iriConverter->getIriFromItem($rootCategory); - $request = array( - "parent" => $targetIri, - ); + $request = [ + 'parent' => $targetIri, + ]; $client->request( 'PUT', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $this->assertEquals($rootCategory->getId(), $secondCategory->getParent()->getId()); - $this->assertEquals("Root Node ➤ Second Category", $secondCategory->getCategoryPath()); + $this->assertEquals('Root Node ➤ Second Category', $secondCategory->getCategoryPath()); } abstract public function getFixtureLoaderClass(); diff --git a/src/PartKeepr/CoreBundle/Action/SystemNoticeAcknowledgeAction.php b/src/PartKeepr/CoreBundle/Action/SystemNoticeAcknowledgeAction.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\CoreBundle\Action; +namespace PartKeepr\CoreBundle\Action; use Doctrine\ORM\EntityManager; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -32,14 +32,14 @@ class SystemNoticeAcknowledgeAction } /** - * Sets the acknowledged flag for a system notice + * Sets the acknowledged flag for a system notice. * * @param Request $request The request * @param int $id The ID of the system notice * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -47,7 +47,7 @@ class SystemNoticeAcknowledgeAction $systemNotice = $this->getItem($this->dataProvider, $resourceType, $id); - /** + /* * @var $systemNotice SystemNotice */ $systemNotice->setAcknowledged(); diff --git a/src/PartKeepr/CoreBundle/Command/CheckForUpdatesCommand.php b/src/PartKeepr/CoreBundle/Command/CheckForUpdatesCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -11,12 +12,12 @@ class CheckForUpdatesCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:cron:versioncheck'); - $this->setDescription("Checks for PartKeepr updates"); + $this->setDescription('Checks for PartKeepr updates'); } public function execute(InputInterface $input, OutputInterface $output) { - $this->getContainer()->get("partkeepr.versionservice")->doVersionCheck(); - $this->getContainer()->get("partkeepr.cronlogger_service")->markCronRun("partkeepr:cron:versioncheck"); + $this->getContainer()->get('partkeepr.versionservice')->doVersionCheck(); + $this->getContainer()->get('partkeepr.cronlogger_service')->markCronRun('partkeepr:cron:versioncheck'); } } diff --git a/src/PartKeepr/CoreBundle/Command/ClearCronLoggerCommand.php b/src/PartKeepr/CoreBundle/Command/ClearCronLoggerCommand.php @@ -1,22 +1,22 @@ <?php + namespace PartKeepr\CoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class ClearCronLoggerCommand extends ContainerAwareCommand { - public function configure() + public function configure() { parent::configure(); $this->setName('partkeepr:cron:clear'); - $this->setDescription("Clears all cron logger entries"); + $this->setDescription('Clears all cron logger entries'); } public function execute(InputInterface $input, OutputInterface $output) { - $this->getContainer()->get("partkeepr.cronlogger_service")->clear(); + $this->getContainer()->get('partkeepr.cronlogger_service')->clear(); } } diff --git a/src/PartKeepr/CoreBundle/Command/UpdateCategoryPathCommand.php b/src/PartKeepr/CoreBundle/Command/UpdateCategoryPathCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Command; use Gedmo\Tree\Entity\Repository\NestedTreeRepository; @@ -13,16 +14,16 @@ class UpdateCategoryPathCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:update-category-paths'); - $this->setDescription("Updates the category paths for all category trees"); + $this->setDescription('Updates the category paths for all category trees'); } public function execute(InputInterface $input, OutputInterface $output) { - $entities = array( + $entities = [ 'PartKeepr\FootprintBundle\Entity\FootprintCategory', 'PartKeepr\PartBundle\Entity\PartCategory', 'PartKeepr\StorageLocationBundle\Entity\StorageLocationCategory', - ); + ]; foreach ($entities as $entity) { $this->regenerateCategoryPaths($entity); @@ -31,28 +32,28 @@ class UpdateCategoryPathCommand extends ContainerAwareCommand public function regenerateCategoryPaths($entity) { - $repository = $this->getContainer()->get("doctrine.orm.default_entity_manager")->getRepository($entity); + $repository = $this->getContainer()->get('doctrine.orm.default_entity_manager')->getRepository($entity); - /** + /* * @var $repository NestedTreeRepository */ $rootNodes = $repository->getRootNodes(); - $pathSeparator = $this->getContainer()->getParameter("partkeepr.category.path_separator"); + $pathSeparator = $this->getContainer()->getParameter('partkeepr.category.path_separator'); foreach ($rootNodes as $rootNode) { - /** + /* * @var $rootNode CategoryPathInterface */ $rootNode->setCategoryPath(uniqid()); } - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush(); foreach ($rootNodes as $rootNode) { $rootNode->setCategoryPath($rootNode->generateCategoryPath($pathSeparator)); } - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush(); } } diff --git a/src/PartKeepr/CoreBundle/Controller/DefaultController.php b/src/PartKeepr/CoreBundle/Controller/DefaultController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Controller; use FOS\RestBundle\Controller\Annotations\View; @@ -8,7 +9,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration as Routing; class DefaultController extends FOSRestController { /** - * Returns system status + * Returns system status. * * @Routing\Route("/api/system_status", defaults={"method" = "get","_format" = "json"}) * @View() @@ -17,11 +18,11 @@ class DefaultController extends FOSRestController */ public function getSystemStatusAction() { - return $this->get("partkeepr_systemservice")->getSystemStatus(); + return $this->get('partkeepr_systemservice')->getSystemStatus(); } /** - * Returns system information + * Returns system information. * * @Routing\Route("/api/system_information", defaults={"method" = "get","_format" = "json"}) * @View() @@ -30,11 +31,11 @@ class DefaultController extends FOSRestController */ public function getSystemInformationAction() { - return $this->get("partkeepr_systemservice")->getSystemInformation(); + return $this->get('partkeepr_systemservice')->getSystemInformation(); } /** - * Returns available disk space + * Returns available disk space. * * @Routing\Route("/api/disk_space", defaults={"method" = "get","_format" = "json"}) * @View() @@ -43,9 +44,9 @@ class DefaultController extends FOSRestController */ public function getDiskFreeSpaceAction() { - return array( - "disk_total" => $this->get("partkeepr_systemservice")->getTotalDiskSpace(), - "disk_used" => $this->get("partkeepr_systemservice")->getUsedDiskSpace(), - ); + return [ + 'disk_total' => $this->get('partkeepr_systemservice')->getTotalDiskSpace(), + 'disk_used' => $this->get('partkeepr_systemservice')->getUsedDiskSpace(), + ]; } } diff --git a/src/PartKeepr/CoreBundle/DependencyInjection/Configuration.php b/src/PartKeepr/CoreBundle/DependencyInjection/Configuration.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; @@ -27,9 +28,9 @@ class Configuration implements ConfigurationInterface ->info('The URI where tips are loaded from') ->end() ->arrayNode('required_cronjobs') - ->treatNullLike(array()) + ->treatNullLike([]) ->prototype('scalar')->end() - ->defaultValue(array('partkeepr:cron:synctips')) + ->defaultValue(['partkeepr:cron:synctips']) ->end() ->scalarNode('tip_of_the_day_list') ->cannotBeEmpty() diff --git a/src/PartKeepr/CoreBundle/DependencyInjection/PartKeeprCoreExtension.php b/src/PartKeepr/CoreBundle/DependencyInjection/PartKeeprCoreExtension.php @@ -8,7 +8,7 @@ use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ @@ -29,8 +29,8 @@ class PartKeeprCoreExtension extends Extension $container->setParameter('partkeepr.tip_of_the_day_list', $config['tip_of_the_day_list']); $container->setParameter('partkeepr.required_cronjobs', $config['required_cronjobs']); - foreach ($config["directories"] as $key => $value) { - $container->setParameter("partkeepr.directories.".$key, $value); + foreach ($config['directories'] as $key => $value) { + $container->setParameter('partkeepr.directories.'.$key, $value); } $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); @@ -40,6 +40,6 @@ class PartKeeprCoreExtension extends Extension public function getAlias() { - return "partkeepr"; + return 'partkeepr'; } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/BaseMigration.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/BaseMigration.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Migrations\AbstractMigration; @@ -27,12 +28,12 @@ abstract class BaseMigration extends AbstractMigration implements ContainerAware protected function performDatabaseUpgrade() { /** - * @var $entityManager EntityManager + * @var EntityManager */ - $entityManager = $this->container->get("doctrine")->getManager(); + $entityManager = $this->container->get('doctrine')->getManager(); $tool = new SchemaTool($entityManager); - $meta = $this->container->get("doctrine")->getManager()->getMetadataFactory()->getAllMetadata(); + $meta = $this->container->get('doctrine')->getManager()->getMetadataFactory()->getAllMetadata(); $tool->updateSchema($meta, true); } @@ -42,6 +43,6 @@ abstract class BaseMigration extends AbstractMigration implements ContainerAware */ protected function getEM() { - return $this->container->get("doctrine")->getManager(); + return $this->container->get('doctrine')->getManager(); } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150608120000.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150608120000.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\CoreBundle\DoctrineMigrations; +namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; @@ -11,7 +11,7 @@ class Version20150608120000 extends BaseMigration */ public function up(Schema $schema) { - $averagePriceFixSQL = "UPDATE Part SET averagePrice = 0 WHERE averagePrice IS NULL"; + $averagePriceFixSQL = 'UPDATE Part SET averagePrice = 0 WHERE averagePrice IS NULL'; $this->addSql($averagePriceFixSQL); } @@ -21,6 +21,5 @@ class Version20150608120000 extends BaseMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150708120022.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150708120022.php @@ -1,10 +1,11 @@ <?php + namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; /** - * Fixes the category trees due to the migration of doctrine2-nestedset to DoctrineExtensions + * Fixes the category trees due to the migration of doctrine2-nestedset to DoctrineExtensions. */ class Version20150708120022 extends BaseMigration { @@ -15,14 +16,13 @@ class Version20150708120022 extends BaseMigration { $this->performDatabaseUpgrade(); - $this->fixTree("PartCategory"); - $this->fixTree("FootprintCategory"); - $this->fixTree("StorageLocationCategory"); - - $this->createRootNode("partkeepr.part.category_service"); - $this->createRootNode("partkeepr.storage_location.category_service"); - $this->createRootNode("partkeepr.footprint.category_service"); + $this->fixTree('PartCategory'); + $this->fixTree('FootprintCategory'); + $this->fixTree('StorageLocationCategory'); + $this->createRootNode('partkeepr.part.category_service'); + $this->createRootNode('partkeepr.storage_location.category_service'); + $this->createRootNode('partkeepr.footprint.category_service'); } protected function createRootNode($service) @@ -31,7 +31,7 @@ class Version20150708120022 extends BaseMigration } /** - * Fixes the tree for a given table due to the migration of doctrine2-nestedset to DoctrineExtensions + * Fixes the tree for a given table due to the migration of doctrine2-nestedset to DoctrineExtensions. * * @param string $table The table name to fix * @@ -43,41 +43,41 @@ class Version20150708120022 extends BaseMigration $queryBuilder = $this->connection->createQueryBuilder(); $queryBuilder->update($table) - ->set("parent_id", ":parent") - ->set("root", ":root") - ->set("lvl", ":level") - ->where("id = :id"); + ->set('parent_id', ':parent') + ->set('root', ':root') + ->set('lvl', ':level') + ->where('id = :id'); foreach ($nodes as $node) { - $parent = $this->fetchParent($table, $node["id"]); - $level = $this->getLevel($table, $node["id"]); + $parent = $this->fetchParent($table, $node['id']); + $level = $this->getLevel($table, $node['id']); if ($parent !== false) { $this->connection->executeUpdate( $queryBuilder->getSQL(), - array( - ":parent" => $parent, - ":id" => $node["id"], - ":level" => $level, - ":root" => 1, - ) + [ + ':parent' => $parent, + ':id' => $node['id'], + ':level' => $level, + ':root' => 1, + ] ); } else { $this->connection->executeUpdate( $queryBuilder->getSQL(), - array( - ":parent" => null, - ":id" => $node["id"], - ":root" => 1, - ":level" => 0, - ) + [ + ':parent' => null, + ':id' => $node['id'], + ':root' => 1, + ':level' => 0, + ] ); } } } /** - * Fetches the parent node for a table and ID + * Fetches the parent node for a table and ID. * * @param $table * @param $id @@ -88,20 +88,20 @@ class Version20150708120022 extends BaseMigration { $queryBuilder = $this->connection->createQueryBuilder(); - $queryBuilder->select("parent.id") - ->from($table, "node") - ->from($table, "parent") - ->where("parent.lft < node.lft") - ->andWhere("parent.rgt > node.rgt") - ->andWhere("node.id = :nodeid") - ->orderBy("parent.rgt - parent.lft") + $queryBuilder->select('parent.id') + ->from($table, 'node') + ->from($table, 'parent') + ->where('parent.lft < node.lft') + ->andWhere('parent.rgt > node.rgt') + ->andWhere('node.id = :nodeid') + ->orderBy('parent.rgt - parent.lft') ->setMaxResults(1); - return $this->connection->fetchColumn($queryBuilder->getSQL(), array(":nodeid" => $id), 0); + return $this->connection->fetchColumn($queryBuilder->getSQL(), [':nodeid' => $id], 0); } /** - * Returns the node IDs for the table + * Returns the node IDs for the table. * * @param $table * @@ -111,15 +111,15 @@ class Version20150708120022 extends BaseMigration { $qb = $this->connection->createQueryBuilder(); - $qb->select("id") + $qb->select('id') ->from($table) - ->orderBy("id", "ASC"); + ->orderBy('id', 'ASC'); return $this->connection->fetchAll($qb->getSQL()); } /** - * Returns the level for a given table and ID + * Returns the level for a given table and ID. * * @param $table * @param $id @@ -130,14 +130,14 @@ class Version20150708120022 extends BaseMigration { $qb = $this->connection->createQueryBuilder(); - $qb->select("COUNT(*) AS level") - ->from($table, "node") - ->from($table, "parent") - ->where("node.lft > parent.lft") - ->andWhere("node.lft < parent.rgt") - ->andWhere("node.id = :nodeid"); + $qb->select('COUNT(*) AS level') + ->from($table, 'node') + ->from($table, 'parent') + ->where('node.lft > parent.lft') + ->andWhere('node.lft < parent.rgt') + ->andWhere('node.id = :nodeid'); - return $this->connection->fetchAssoc($qb->getSQL(), array(":nodeid" => $id))["level"]; + return $this->connection->fetchAssoc($qb->getSQL(), [':nodeid' => $id])['level']; } /** @@ -146,6 +146,5 @@ class Version20150708120022 extends BaseMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150724174030.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20150724174030.php @@ -27,7 +27,7 @@ class Version20150724174030 extends BaseMigration if (count($rootNodes) === 0) { // Ensure that the root category exists $rootNode = new StorageLocationCategory(); - $rootNode->setName("Root Node"); + $rootNode->setName('Root Node'); $this->getEM()->persist($rootNode); $this->getEM()->flush(); } else { diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151001180120.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151001180120.php @@ -1,11 +1,12 @@ <?php + namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use PartKeepr\AuthBundle\Entity\UserProvider; /** - * Attaches the builtin user provider to all existing users + * Attaches the builtin user provider to all existing users. */ class Version20151001180120 extends BaseMigration { @@ -20,11 +21,11 @@ class Version20151001180120 extends BaseMigration 'PartKeeprAuthBundle:UserProvider' ); - $builtinProvider = $userProviderRepository->findOneBy(array("type" => "Builtin")); + $builtinProvider = $userProviderRepository->findOneBy(['type' => 'Builtin']); if ($builtinProvider === null) { $builtinProvider = new UserProvider(); - $builtinProvider->setType("Builtin"); + $builtinProvider->setType('Builtin'); $this->getEM()->persist($builtinProvider); } @@ -44,7 +45,6 @@ class Version20151001180120 extends BaseMigration } $this->getEM()->flush(); - } /** @@ -53,6 +53,5 @@ class Version20151001180120 extends BaseMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151002183125.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151002183125.php @@ -5,7 +5,7 @@ namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; /** - * Re-saves all parts in order to re-generate the averagePrice and removals field + * Re-saves all parts in order to re-generate the averagePrice and removals field. */ class Version20151002183125 extends BaseMigration { @@ -26,7 +26,6 @@ class Version20151002183125 extends BaseMigration $part->recomputeStockLevels(); } - $this->getEM()->flush(); } @@ -36,6 +35,5 @@ class Version20151002183125 extends BaseMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151031163951.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151031163951.php @@ -2,11 +2,10 @@ namespace PartKeepr\CoreBundle\DoctrineMigrations; -use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** - * Ensures that each footprint has a category assigned + * Ensures that each footprint has a category assigned. */ class Version20151031163951 extends BaseMigration { @@ -19,7 +18,7 @@ class Version20151031163951 extends BaseMigration 'PartKeeprFootprintBundle:Footprint' ); - $rootNode = $this->getContainer()->get("partkeepr.footprint.category_service")->getRootNode(); + $rootNode = $this->getContainer()->get('partkeepr.footprint.category_service')->getRootNode(); $footprints = $footprintRepository->findAll(); diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151208162723.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20151208162723.php @@ -5,7 +5,7 @@ namespace PartKeepr\CoreBundle\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; /** - * Sets all present users to be active + * Sets all present users to be active. */ class Version20151208162723 extends BaseMigration { @@ -15,7 +15,7 @@ class Version20151208162723 extends BaseMigration public function up(Schema $schema) { $this->performDatabaseUpgrade(); - $activeUsersSQL = "UPDATE PartKeeprUser SET active = true"; + $activeUsersSQL = 'UPDATE PartKeeprUser SET active = true'; $this->addSql($activeUsersSQL); } @@ -25,6 +25,5 @@ class Version20151208162723 extends BaseMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20160103145302.php b/src/PartKeepr/CoreBundle/DoctrineMigrations/Version20160103145302.php @@ -6,7 +6,7 @@ use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** - * Drops legacy tables + * Drops legacy tables. */ class Version20160103145302 extends AbstractMigration { @@ -15,13 +15,13 @@ class Version20160103145302 extends AbstractMigration */ public function up(Schema $schema) { - $tablesToDrop = array( - "LastNotification", - "Event", - "Session", - "PrintingJobConfiguration", - "PrintingJob" - ); + $tablesToDrop = [ + 'LastNotification', + 'Event', + 'Session', + 'PrintingJobConfiguration', + 'PrintingJob', + ]; foreach ($tablesToDrop as $table) { if ($schema->hasTable($table)) { $schema->dropTable($table); @@ -35,6 +35,5 @@ class Version20160103145302 extends AbstractMigration public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs - } } diff --git a/src/PartKeepr/CoreBundle/Entity/BaseEntity.php b/src/PartKeepr/CoreBundle/Entity/BaseEntity.php @@ -1,25 +1,30 @@ <?php + namespace PartKeepr\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** @ORM\MappedSuperclass */ -abstract class BaseEntity { - /** - * @ORM\Id - * @ORM\Column(type="integer") - * @ORM\GeneratedValue(strategy="AUTO") - * @var integer - */ - private $id; - - /** - * Returns the ID of this object. - * @param none - * @return int The ID of this object - */ - public function getId () { - return $this->id; - } - -}- \ No newline at end of file +abstract class BaseEntity +{ + /** + * @ORM\Id + * @ORM\Column(type="integer") + * @ORM\GeneratedValue(strategy="AUTO") + * + * @var int + */ + private $id; + + /** + * Returns the ID of this object. + * + * @param none + * + * @return int The ID of this object + */ + public function getId() + { + return $this->id; + } +} diff --git a/src/PartKeepr/CoreBundle/Entity/SystemNotice.php b/src/PartKeepr/CoreBundle/Entity/SystemNotice.php @@ -1,13 +1,13 @@ <?php + namespace PartKeepr\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** - * Holds a system notice + * Holds a system notice. * * @ORM\Entity * @TargetService("/api/system_notices") @@ -17,6 +17,7 @@ class SystemNotice extends BaseEntity /** * @ORM\Column(type="datetime") * @Groups({"default"}) + * * @var \DateTime */ private $date; @@ -24,12 +25,13 @@ class SystemNotice extends BaseEntity /** * @ORM\Column(type="string") * @Groups({"default"}) + * * @var string */ private $title; /** - * The description of this notice + * The description of this notice. * * @ORM\Column(type="text") * @Groups({"default"}) @@ -39,16 +41,18 @@ class SystemNotice extends BaseEntity private $description; /** - * Defines if the system notice has been acknowledged + * Defines if the system notice has been acknowledged. + * * @ORM\Column(type="boolean") * @Groups({"default"}) * - * @var boolean + * @var bool */ private $acknowledged = false; /** * Specifies the type. This is required for unique notices which shouldn't pop up every time we create them. + * * @ORM\Column(type="string") * @Groups({"default"}) * @@ -57,7 +61,7 @@ class SystemNotice extends BaseEntity private $type; /** - * Sets the date and time for this entry + * Sets the date and time for this entry. * * @param \DateTime $date The date and time */ @@ -67,7 +71,7 @@ class SystemNotice extends BaseEntity } /** - * Returns the date and time for this entry + * Returns the date and time for this entry. * * @return \DateTime the date and time for this entry */ @@ -77,7 +81,7 @@ class SystemNotice extends BaseEntity } /** - * Sets the title for this entry + * Sets the title for this entry. * * @param string $title the title for this entry */ @@ -87,7 +91,7 @@ class SystemNotice extends BaseEntity } /** - * Returns the title for this entry + * Returns the title for this entry. * * @return string the title */ @@ -97,7 +101,7 @@ class SystemNotice extends BaseEntity } /** - * Sets the description + * Sets the description. * * @param string $description */ @@ -107,7 +111,7 @@ class SystemNotice extends BaseEntity } /** - * Returns the description + * Returns the description. * * @return string The description */ @@ -117,9 +121,9 @@ class SystemNotice extends BaseEntity } /** - * Sets the value of the acknowledged flag + * Sets the value of the acknowledged flag. * - * @param boolean $bAck True if the notice should be acknowledged (default), false otherwise + * @param bool $bAck True if the notice should be acknowledged (default), false otherwise */ public function setAcknowledged($bAck = true) { @@ -127,9 +131,9 @@ class SystemNotice extends BaseEntity } /** - * Returns the value of the acknowledged flag + * Returns the value of the acknowledged flag. * - * @return boolean true if this notice has been acknowledged, false otherwise + * @return bool true if this notice has been acknowledged, false otherwise */ public function isAcknowledged() { @@ -137,7 +141,7 @@ class SystemNotice extends BaseEntity } /** - * Sets the type of this entry + * Sets the type of this entry. * * @param string $type */ @@ -147,7 +151,7 @@ class SystemNotice extends BaseEntity } /** - * Returns the type of this entry + * Returns the type of this entry. * * @return string The type */ diff --git a/src/PartKeepr/CoreBundle/Exceptions/TranslatableException.php b/src/PartKeepr/CoreBundle/Exceptions/TranslatableException.php @@ -1,15 +1,17 @@ <?php -namespace PartKeepr\CoreBundle\Exceptions; +namespace PartKeepr\CoreBundle\Exceptions; abstract class TranslatableException extends \Exception { - public function __construct () { + public function __construct() + { parent::__construct($this->getMessageKey()); } /** - * Returns the translatable message + * Returns the translatable message. + * * @return mixed */ abstract public function getMessageKey(); diff --git a/src/PartKeepr/CoreBundle/PartKeeprCoreBundle.php b/src/PartKeepr/CoreBundle/PartKeeprCoreBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle; use PartKeepr\CoreBundle\DependencyInjection\PartKeeprCoreExtension; diff --git a/src/PartKeepr/CoreBundle/PartKeeprVersion.php b/src/PartKeepr/CoreBundle/PartKeeprVersion.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle; class PartKeeprVersion diff --git a/src/PartKeepr/CoreBundle/Services/SystemNoticeService.php b/src/PartKeepr/CoreBundle/Services/SystemNoticeService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Services; use Doctrine\ORM\EntityManager; @@ -22,7 +23,7 @@ class SystemNoticeService extends ContainerAware $dql = "SELECT sn FROM PartKeepr\CoreBundle\Entity\SystemNotice sn WHERE sn.type = :type"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("type", $type); + $query->setParameter('type', $type); try { $notice = $query->getSingleResult(); diff --git a/src/PartKeepr/CoreBundle/Services/SystemService.php b/src/PartKeepr/CoreBundle/Services/SystemService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Services; use Doctrine\Bundle\DoctrineBundle\Registry; @@ -51,55 +52,55 @@ class SystemService extends ContainerAware */ public function getSystemInformation() { - $aData = array(); + $aData = []; - $aData[] = new SystemInformationRecord("Doctrine ORM", ORMVersion::VERSION, "Libraries"); - $aData[] = new SystemInformationRecord("Doctrine DBAL", DBALVersion::VERSION, "Libraries"); + $aData[] = new SystemInformationRecord('Doctrine ORM', ORMVersion::VERSION, 'Libraries'); + $aData[] = new SystemInformationRecord('Doctrine DBAL', DBALVersion::VERSION, 'Libraries'); - $aData[] = new SystemInformationRecord("PHP Version", phpversion(), "System"); + $aData[] = new SystemInformationRecord('PHP Version', phpversion(), 'System'); $os = new OperatingSystem(); - $aData[] = new SystemInformationRecord("Operating System Type", $os->getPlatform(), "System"); - $aData[] = new SystemInformationRecord("Operating System Release", $os->getRelease(), "System"); + $aData[] = new SystemInformationRecord('Operating System Type', $os->getPlatform(), 'System'); + $aData[] = new SystemInformationRecord('Operating System Release', $os->getRelease(), 'System'); - $aData[] = new SystemInformationRecord("memory_limit", ini_get("memory_limit"), "PHP"); - $aData[] = new SystemInformationRecord("post_max_size", ini_get("post_max_size"), "PHP"); - $aData[] = new SystemInformationRecord("upload_max_filesize", ini_get("upload_max_filesize"), "PHP"); - $aData[] = new SystemInformationRecord("allow_url_fopen", ini_get("allow_url_fopen"), "PHP"); - $aData[] = new SystemInformationRecord("max_execution_time", ini_get("max_execution_time"), "PHP"); + $aData[] = new SystemInformationRecord('memory_limit', ini_get('memory_limit'), 'PHP'); + $aData[] = new SystemInformationRecord('post_max_size', ini_get('post_max_size'), 'PHP'); + $aData[] = new SystemInformationRecord('upload_max_filesize', ini_get('upload_max_filesize'), 'PHP'); + $aData[] = new SystemInformationRecord('allow_url_fopen', ini_get('allow_url_fopen'), 'PHP'); + $aData[] = new SystemInformationRecord('max_execution_time', ini_get('max_execution_time'), 'PHP'); $queryCache = get_class($this->entityManager->getConfiguration()->getQueryCacheImpl()); $metadataCache = get_class($this->entityManager->getConfiguration()->getMetadataCacheImpl()); - $aData[] = new SystemInformationRecord("Query Cache Implementation", $queryCache, "PHP"); - $aData[] = new SystemInformationRecord("Metadata Cache Implementation", $metadataCache, "PHP"); + $aData[] = new SystemInformationRecord('Query Cache Implementation', $queryCache, 'PHP'); + $aData[] = new SystemInformationRecord('Metadata Cache Implementation', $metadataCache, 'PHP'); $aData[] = new SystemInformationRecord( - "Disk Space (Total)", + 'Disk Space (Total)', $this->format_bytes($this->getTotalDiskSpace()), - "PartKeepr" + 'PartKeepr' ); $aData[] = new SystemInformationRecord( - "Disk Space (Free)", + 'Disk Space (Free)', $this->format_bytes($this->getFreeDiskSpace()), - "PartKeepr" + 'PartKeepr' ); $aData[] = new SystemInformationRecord( - "Disk Space (Used)", + 'Disk Space (Used)', $this->format_bytes($this->getUsedDiskSpace()), - "PartKeepr" + 'PartKeepr' ); $aData[] = new SystemInformationRecord( - "Data Directory", - realpath($this->container->getParameter("partkeepr.filesystem.data_directory")), - "PartKeepr" + 'Data Directory', + realpath($this->container->getParameter('partkeepr.filesystem.data_directory')), + 'PartKeepr' ); - $aData[] = new SystemInformationRecord("PartKeepr Version", $this->versionService->getVersion(), "PartKeepr"); + $aData[] = new SystemInformationRecord('PartKeepr Version', $this->versionService->getVersion(), 'PartKeepr'); return $aData; } @@ -113,20 +114,20 @@ class SystemService extends ContainerAware */ public function getSystemStatus() { - if ($this->container->getParameter("partkeepr.cronjob_check")) { + if ($this->container->getParameter('partkeepr.cronjob_check')) { $inactiveCronjobs = $this->cronLoggerService->getInactiveCronjobs( - $this->container->getParameter("partkeepr.required_cronjobs") + $this->container->getParameter('partkeepr.required_cronjobs') ); } else { // Skip cronjob tests - $inactiveCronjobs = array(); + $inactiveCronjobs = []; } - return array( - "inactiveCronjobCount" => count($inactiveCronjobs), - "inactiveCronjobs" => $inactiveCronjobs, - "schemaStatus" => $this->getSchemaStatus(), - ); + return [ + 'inactiveCronjobCount' => count($inactiveCronjobs), + 'inactiveCronjobs' => $inactiveCronjobs, + 'schemaStatus' => $this->getSchemaStatus(), + ]; } /** @@ -145,9 +146,9 @@ class SystemService extends ContainerAware $queries = $schemaTool->getUpdateSchemaSql($metadatas, true); if (count($queries) > 0) { - return "incomplete"; + return 'incomplete'; } else { - return "complete"; + return 'complete'; } } @@ -158,8 +159,8 @@ class SystemService extends ContainerAware */ public function getFreeDiskSpace() { - if ($this->container->getParameter("partkeepr.filesystem.quota") === false) { - return disk_free_space($this->container->getParameter("partkeepr.filesystem.data_directory")); + if ($this->container->getParameter('partkeepr.filesystem.quota') === false) { + return disk_free_space($this->container->getParameter('partkeepr.filesystem.data_directory')); } else { return $this->getTotalDiskSpace() - $this->getUsedDiskSpace(); } @@ -167,10 +168,10 @@ class SystemService extends ContainerAware public function getTotalDiskSpace() { - if ($this->container->getParameter("partkeepr.filesystem.quota") === false) { - return disk_total_space($this->container->getParameter("partkeepr.filesystem.data_directory")); + if ($this->container->getParameter('partkeepr.filesystem.quota') === false) { + return disk_total_space($this->container->getParameter('partkeepr.filesystem.data_directory')); } else { - return $this->container->getParameter("partkeepr.filesystem.quota"); + return $this->container->getParameter('partkeepr.filesystem.quota'); } } @@ -183,23 +184,23 @@ class SystemService extends ContainerAware */ public function getUsedDiskSpace() { - if ($this->container->getParameter("partkeepr.filesystem.quota") === false) { + if ($this->container->getParameter('partkeepr.filesystem.quota') === false) { return $this->getTotalDiskSpace() - $this->getFreeDiskSpace(); } - $fileEntities = array( + $fileEntities = [ 'PartKeepr\FootprintBundle\Entity\FootprintAttachment', 'PartKeepr\FootprintBundle\Entity\FootprintImage', 'PartKeepr\ManufacturerBundle\Entity\ManufacturerICLogo', 'PartKeepr\PartBundle\Entity\PartAttachment', 'PartKeepr\ProjectBundle\Entity\ProjectAttachment', 'PartKeepr\StorageLocationBundle\Entity\StorageLocationImage', - ); + ]; $size = 0; foreach ($fileEntities as $fileEntity) { - $qb = $this->container->get("doctrine.orm.default_entity_manager")->createQueryBuilder(); - $qb->select("SUM(a.size)")->from($fileEntity, "a"); + $qb = $this->container->get('doctrine.orm.default_entity_manager')->createQueryBuilder(); + $qb->select('SUM(a.size)')->from($fileEntity, 'a'); $size += $qb->getQuery()->getSingleScalarResult(); } @@ -243,22 +244,22 @@ class SystemService extends ContainerAware } /** - * Returns the effective size from a human-readable byte format. - * - * Example: - * getBytesFromHumanReadable("1M") will return 1048576. - * - * @param string $size_str The byte - * @return int The bytes - */ - public function getBytesFromHumanReadable ($size_str) - { - switch (substr ($size_str, -1)) - { - case 'M': case 'm': return (int)$size_str * 1048576; - case 'K': case 'k': return (int)$size_str * 1024; - case 'G': case 'g': return (int)$size_str * 1073741824; - default: return $size_str; - } - } + * Returns the effective size from a human-readable byte format. + * + * Example: + * getBytesFromHumanReadable("1M") will return 1048576. + * + * @param string $size_str The byte + * + * @return int The bytes + */ + public function getBytesFromHumanReadable($size_str) + { + switch (substr($size_str, -1)) { + case 'M': case 'm': return (int) $size_str * 1048576; + case 'K': case 'k': return (int) $size_str * 1024; + case 'G': case 'g': return (int) $size_str * 1073741824; + default: return $size_str; + } + } } diff --git a/src/PartKeepr/CoreBundle/Services/VersionService.php b/src/PartKeepr/CoreBundle/Services/VersionService.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\CoreBundle\Services; +namespace PartKeepr\CoreBundle\Services; use PartKeepr\CoreBundle\PartKeeprVersion; use PartKeepr\RemoteFileLoader\RemoteFileLoaderFactory; @@ -16,7 +16,7 @@ class VersionService /** * @var string */ - private $versionURI = "http://www.partkeepr.org/versions.json"; + private $versionURI = 'http://www.partkeepr.org/versions.json'; /** * @var TranslatorInterface @@ -39,8 +39,8 @@ class VersionService $this->translator = $translator; $this->remoteFileLoader = $remoteFileLoader; - if (PartKeeprVersion::PARTKEEPR_VERSION == "{V_GIT}") { - $this->setVersion("GIT development version"); + if (PartKeeprVersion::PARTKEEPR_VERSION == '{V_GIT}') { + $this->setVersion('GIT development version'); } else { $this->setVersion(PartKeeprVersion::PARTKEEPR_VERSION); } @@ -68,31 +68,29 @@ class VersionService */ public function doVersionCheck() { - if ($this->getVersion() === "{V_GIT}") { + if ($this->getVersion() === '{V_GIT}') { return; } - if (substr($this->getVersion(), 0, 17) === "partkeepr-nightly") { + if (substr($this->getVersion(), 0, 17) === 'partkeepr-nightly') { return; } $latestVersion = $this->getLatestVersion(); - if ($latestVersion === false) { return; } - if (version_compare($this->getVersion(), $latestVersion["version"], '<')) { + if (version_compare($this->getVersion(), $latestVersion['version'], '<')) { $this->systemNoticeService->createUniqueSystemNotice( - "PARTKEEPR_VERSION_".$latestVersion["version"], - $this->translator->trans("New PartKeepr Version %version% available", - array("%version%" => $latestVersion["version"])), - $this->translator->trans("PartKeepr Version %version% changelog:", array( - "%version%" => $latestVersion["version"]."\n\n". - $latestVersion["changelog"], - )) + 'PARTKEEPR_VERSION_'.$latestVersion['version'], + $this->translator->trans('New PartKeepr Version %version% available', + ['%version%' => $latestVersion['version']]), + $this->translator->trans('PartKeepr Version %version% changelog:', [ + '%version%' => $latestVersion['version']."\n\n". + $latestVersion['changelog'], + ]) ); - } } @@ -107,14 +105,14 @@ class VersionService $latestVersionEntry = $versions[0]; - if (!array_key_exists("version", $latestVersionEntry)) { + if (!array_key_exists('version', $latestVersionEntry)) { return false; } - if (!array_key_exists("changelog", $latestVersionEntry)) { - return array("version" => $latestVersionEntry["version"], "changelog" => ""); + if (!array_key_exists('changelog', $latestVersionEntry)) { + return ['version' => $latestVersionEntry['version'], 'changelog' => '']; } else { - return array("version" => $latestVersionEntry["version"], "changelog" => $latestVersionEntry["changelog"]); + return ['version' => $latestVersionEntry['version'], 'changelog' => $latestVersionEntry['changelog']]; } } } diff --git a/src/PartKeepr/CoreBundle/System/OperatingSystem.php b/src/PartKeepr/CoreBundle/System/OperatingSystem.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\System; class OperatingSystem @@ -11,68 +12,68 @@ class OperatingSystem */ public function getPlatform() { - if (function_exists("posix_uname")) { + if (function_exists('posix_uname')) { $data = posix_uname(); - if (array_key_exists("sysname", $data)) { - return $data["sysname"]; + if (array_key_exists('sysname', $data)) { + return $data['sysname']; } } - if (\PHP_OS == "WINNT") { - return "Windows"; + if (\PHP_OS == 'WINNT') { + return 'Windows'; } - return "unknown"; + return 'unknown'; } /** - * Returns the distribution + * Returns the distribution. * * @return string string */ public function getRelease() { switch (strtolower($this->getPlatform())) { - case "freebsd": - /** + case 'freebsd': + /* * Unfortunately, there's no text file on FreeBSD which tells us the release * number. Thus, we hope that "release" within posix_uname() is defined. */ - if (function_exists("posix_uname")) { + if (function_exists('posix_uname')) { $data = posix_uname(); - if (array_key_exists("release", $data)) { - return $data["release"]; + if (array_key_exists('release', $data)) { + return $data['release']; } } break; - case "darwin": - /** + case 'darwin': + /* * Mac stores its version number in a public readable plist file, which * is in XML format. */ $document = new \DomDocument(); - $document->load("/System/Library/CoreServices/SystemVersion.plist"); + $document->load('/System/Library/CoreServices/SystemVersion.plist'); $xpath = new \DOMXPath($document); - $entries = $xpath->query("/plist/dict/*"); + $entries = $xpath->query('/plist/dict/*'); - $previous = ""; + $previous = ''; foreach ($entries as $entry) { - if (strpos($previous, "ProductVersion") !== false) { + if (strpos($previous, 'ProductVersion') !== false) { return $entry->textContent; } $previous = $entry->textContent; } break; - case "linux": + case 'linux': return $this->getLinuxDistribution(); break; default: break; } - return "unknown"; + return 'unknown'; } /** @@ -89,11 +90,11 @@ class OperatingSystem /* Try executing lsb_release */ $release = @exec('lsb_release -d -s', $void, $retval); - if ($retval === 0 && $release !== "") { + if ($retval === 0 && $release !== '') { return $release; } //@todo we need better handling here - return "unknown"; + return 'unknown'; } } diff --git a/src/PartKeepr/CoreBundle/System/SystemInformationRecord.php b/src/PartKeepr/CoreBundle/System/SystemInformationRecord.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\System; /** @@ -21,21 +22,21 @@ namespace PartKeepr\CoreBundle\System; class SystemInformationRecord { /** - * Holds the category name + * Holds the category name. * * @var string */ public $category; /** - * Holds the name + * Holds the name. * * @var string */ public $name; /** - * Holds the value + * Holds the value. * * @var mixed */ diff --git a/src/PartKeepr/CoreBundle/Tests/SetupWebTestCase.php b/src/PartKeepr/CoreBundle/Tests/SetupWebTestCase.php @@ -3,21 +3,17 @@ * Created by PhpStorm. * User: felicitus * Date: 10/9/15 - * Time: 7:43 PM + * Time: 7:43 PM. */ - namespace PartKeepr\CoreBundle\Tests; - /** * Special WebTestCase which forces to load the AppKernel. This is because the base getKernelClass() method * does wildcard matching on *Kernel.php within the app/ directory, and on some systems it might happen that * SetupAppKernel gets loaded first, causing unit tests to fail. - * */ class SetupWebTestCase extends WebTestCase { - public function generateAndGetAuthKey() { $client = static::makeClient(); @@ -27,27 +23,28 @@ class SetupWebTestCase extends WebTestCase '/setup/generateAuthKey' ); - return $this->getContainer()->get("partkeepr.setup.config_service")->getAuthKey(); + return $this->getContainer()->get('partkeepr.setup.config_service')->getAuthKey(); } - public function getConfiguration ($authKey) { + public function getConfiguration($authKey) + { $client = static::makeClient(); - $voidConfig = array( - "authKey" => $authKey, - "values" => array() - ); + $voidConfig = [ + 'authKey' => $authKey, + 'values' => [], + ]; $client->request( 'POST', '/setup/parseExistingConfig', - array(), - array(), - array(), + [], + [], + [], json_encode($voidConfig) ); - $responseObj = json_decode($client->getResponse()->getContent(), true); + $responseObj = json_decode($client->getResponse()->getContent(), true); - return $responseObj["config"]; + return $responseObj['config']; } } diff --git a/src/PartKeepr/CoreBundle/Tests/SystemInformationTest.php b/src/PartKeepr/CoreBundle/Tests/SystemInformationTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Tests; class SystemInformationTest extends WebTestCase @@ -14,12 +15,12 @@ class SystemInformationTest extends WebTestCase $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("array", $response); + $this->assertInternalType('array', $response); - $this->assertInternalType("object", $response[0]); - $this->assertObjectHasAttribute("category", $response[0]); - $this->assertObjectHasAttribute("name", $response[0]); - $this->assertObjectHasAttribute("value", $response[0]); + $this->assertInternalType('object', $response[0]); + $this->assertObjectHasAttribute('category', $response[0]); + $this->assertObjectHasAttribute('name', $response[0]); + $this->assertObjectHasAttribute('value', $response[0]); } public function testSystemStatus() @@ -33,10 +34,10 @@ class SystemInformationTest extends WebTestCase $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("object", $response); - $this->assertObjectHasAttribute("inactiveCronjobCount", $response); - $this->assertObjectHasAttribute("inactiveCronjobs", $response); - $this->assertInternalType("array", $response->inactiveCronjobs); - $this->assertObjectHasAttribute("schemaStatus", $response); + $this->assertInternalType('object', $response); + $this->assertObjectHasAttribute('inactiveCronjobCount', $response); + $this->assertObjectHasAttribute('inactiveCronjobs', $response); + $this->assertInternalType('array', $response->inactiveCronjobs); + $this->assertObjectHasAttribute('schemaStatus', $response); } } diff --git a/src/PartKeepr/CoreBundle/Tests/SystemNoticeTest.php b/src/PartKeepr/CoreBundle/Tests/SystemNoticeTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Tests; use Dunglas\ApiBundle\Api\IriConverter; @@ -7,24 +8,23 @@ class SystemNoticeTest extends WebTestCase { public function setUp() { - $this->loadFixtures(array()); + $this->loadFixtures([]); } public function testSystemNotices() { $client = static::makeClient(true); - $systemNoticeService = $this->getContainer()->get("partkeepr.systemnoticeservice"); - $notice = $systemNoticeService->createUniqueSystemNotice("FOO", "BAR", "DING"); + $systemNoticeService = $this->getContainer()->get('partkeepr.systemnoticeservice'); + $notice = $systemNoticeService->createUniqueSystemNotice('FOO', 'BAR', 'DING'); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($notice); - $ackIri = $iri."/acknowledge"; - + $ackIri = $iri.'/acknowledge'; $client->request( 'GET', @@ -33,9 +33,9 @@ class SystemNoticeTest extends WebTestCase $response = json_decode($client->getResponse()->getContent()); - $this->assertEquals("FOO", $response->type); - $this->assertEquals("BAR", $response->title); - $this->assertEquals("DING", $response->description); + $this->assertEquals('FOO', $response->type); + $this->assertEquals('BAR', $response->title); + $this->assertEquals('DING', $response->description); $this->assertEquals(false, $response->acknowledged); $client->request( diff --git a/src/PartKeepr/CoreBundle/Tests/VersionServiceTest.php b/src/PartKeepr/CoreBundle/Tests/VersionServiceTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CoreBundle\Tests; use PartKeepr\CoreBundle\Services\VersionService; @@ -7,19 +8,19 @@ class VersionServiceTest extends WebTestCase { public function setUp() { - $this->loadFixtures(array()); + $this->loadFixtures([]); } public function testVersionService() { /** - * @var VersionService $versionService + * @var VersionService */ - $versionService = $this->getContainer()->get("partkeepr.versionservice"); + $versionService = $this->getContainer()->get('partkeepr.versionservice'); - $versionService->setVersion("0.1.8"); - $versionService->setVersionURI(__DIR__."/Fixtures/versions.json"); + $versionService->setVersion('0.1.8'); + $versionService->setVersionURI(__DIR__.'/Fixtures/versions.json'); $versionService->doVersionCheck(); @@ -32,11 +33,11 @@ class VersionServiceTest extends WebTestCase $response = json_decode($client->getResponse()->getContent()); - $this->assertObjectHasAttribute("hydra:member", $response); - $this->assertEquals(1, count($response->{"hydra:member"})); + $this->assertObjectHasAttribute('hydra:member', $response); + $this->assertEquals(1, count($response->{'hydra:member'})); - $versionEntry = $response->{"hydra:member"}[0]; + $versionEntry = $response->{'hydra:member'}[0]; - $this->assertEquals("New PartKeepr Version 0.1.9 available", $versionEntry->title); + $this->assertEquals('New PartKeepr Version 0.1.9 available', $versionEntry->title); } } diff --git a/src/PartKeepr/CoreBundle/Tests/WebTestCase.php b/src/PartKeepr/CoreBundle/Tests/WebTestCase.php @@ -3,21 +3,18 @@ * Created by PhpStorm. * User: felicitus * Date: 10/9/15 - * Time: 7:43 PM + * Time: 7:43 PM. */ - namespace PartKeepr\CoreBundle\Tests; - /** * Special WebTestCase which forces to load the AppKernel. This is because the base getKernelClass() method * does wildcard matching on *Kernel.php within the app/ directory, and on some systems it might happen that * SetupAppKernel gets loaded first, causing unit tests to fail. - * */ class WebTestCase extends \Liip\FunctionalTestBundle\Test\WebTestCase { - static protected function getKernelClass() + protected static function getKernelClass() { $dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : self::getPhpUnitXmlDir(); @@ -30,4 +27,4 @@ class WebTestCase extends \Liip\FunctionalTestBundle\Test\WebTestCase return $class; } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/CronLoggerBundle/Command/RunCronsCommand.php b/src/PartKeepr/CronLoggerBundle/Command/RunCronsCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CronLoggerBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -11,11 +12,11 @@ class RunCronsCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:cron:run'); - $this->setDescription("Runs all cron jobs"); + $this->setDescription('Runs all cron jobs'); } public function execute(InputInterface $input, OutputInterface $output) { - $this->getContainer()->get("partkeepr.cronlogger_service")->runCrons(); + $this->getContainer()->get('partkeepr.cronlogger_service')->runCrons(); } } diff --git a/src/PartKeepr/CronLoggerBundle/Controller/CronRunnerController.php b/src/PartKeepr/CronLoggerBundle/Controller/CronRunnerController.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\CronLoggerBundle\Controller; +namespace PartKeepr\CronLoggerBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; @@ -11,9 +11,10 @@ class CronRunnerController extends FOSRestController /** * @Route("/api/cron/run") */ - public function runCronsAction () { - $this->get("partkeepr.cronlogger_service")->runCrons(); + public function runCronsAction() + { + $this->get('partkeepr.cronlogger_service')->runCrons(); - return new Response("", 200); + return new Response('', 200); } } diff --git a/src/PartKeepr/CronLoggerBundle/DependencyInjection/PartKeeprCronLoggerExtension.php b/src/PartKeepr/CronLoggerBundle/DependencyInjection/PartKeeprCronLoggerExtension.php @@ -1,14 +1,14 @@ <?php + namespace PartKeepr\CronLoggerBundle\DependencyInjection; +use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader; -use Symfony\Component\Config\FileLocator; class PartKeeprCronLoggerExtension extends Extension { - /** * {@inheritdoc} */ diff --git a/src/PartKeepr/CronLoggerBundle/Entity/CronLogger.php b/src/PartKeepr/CronLoggerBundle/Entity/CronLogger.php @@ -1,11 +1,12 @@ <?php + namespace PartKeepr\CronLoggerBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\CoreBundle\Entity\BaseEntity; /** - * Holds a project attachment + * Holds a project attachment. * * @ORM\Table(uniqueConstraints={@ORM\UniqueConstraint(name="cronjob", columns={"cronjob"})}) * @ORM\Entity @@ -14,18 +15,20 @@ class CronLogger extends BaseEntity { /** * @ORM\Column(type="datetime") + * * @var \DateTime */ private $lastRunDate; /** * @ORM\Column(type="string") + * * @var string */ private $cronjob; /** - * Sets the last run date and time for this entry + * Sets the last run date and time for this entry. * * @param \DateTime $date The date and time */ @@ -35,7 +38,7 @@ class CronLogger extends BaseEntity } /** - * Returns the date and time for this entry + * Returns the date and time for this entry. * * @return \DateTime the date and time for this entry */ @@ -45,7 +48,7 @@ class CronLogger extends BaseEntity } /** - * Sets the cronjob for this entry + * Sets the cronjob for this entry. * * @param string $cronjob the title for this entry */ @@ -55,7 +58,7 @@ class CronLogger extends BaseEntity } /** - * Returns the cronjob for this entry + * Returns the cronjob for this entry. * * @return string the title */ diff --git a/src/PartKeepr/CronLoggerBundle/PartKeeprCronLoggerBundle.php b/src/PartKeepr/CronLoggerBundle/PartKeeprCronLoggerBundle.php @@ -1,9 +1,9 @@ <?php + namespace PartKeepr\CronLoggerBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprCronLoggerBundle extends Bundle { - } diff --git a/src/PartKeepr/CronLoggerBundle/Services/CronLoggerService.php b/src/PartKeepr/CronLoggerBundle/Services/CronLoggerService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CronLoggerBundle\Services; use Doctrine\ORM\EntityManager; @@ -27,7 +28,7 @@ class CronLoggerService } /** - * Marks a specific cronjob as ran + * Marks a specific cronjob as ran. * * @param string $cronjob The name of the cronjob * @@ -37,7 +38,7 @@ class CronLoggerService { $dql = "SELECT c FROM PartKeepr\CronLoggerBundle\Entity\CronLogger c WHERE c.cronjob = :cronjob"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("cronjob", $cronjob); + $query->setParameter('cronjob', $cronjob); try { $result = $query->getSingleResult(); @@ -55,7 +56,7 @@ class CronLoggerService } /** - * Returns a list of all inactive cronjobs + * Returns a list of all inactive cronjobs. * * @param none * @@ -64,32 +65,31 @@ class CronLoggerService public function getInactiveCronjobs($requiredCronjobs) { $dql = "SELECT c.cronjob FROM PartKeepr\CronLoggerBundle\Entity\CronLogger c WHERE c.cronjob = :cronjob"; - $dql .= " AND c.lastRunDate > :date"; + $dql .= ' AND c.lastRunDate > :date'; $query = $this->entityManager->createQuery($dql); $date = new \DateTime(); $date->sub(new \DateInterval('P1D')); - $query->setParameter("date", $date); + $query->setParameter('date', $date); - $failedCronjobs = array(); + $failedCronjobs = []; foreach ($requiredCronjobs as $cronjob) { - $query->setParameter("cronjob", $cronjob); + $query->setParameter('cronjob', $cronjob); try { $query->getSingleResult(); } catch (\Exception $e) { $failedCronjobs[] = $cronjob; } - } return $failedCronjobs; } /** - * Clears all cron logger entries + * Clears all cron logger entries. */ public function clear() { @@ -100,14 +100,14 @@ class CronLoggerService } /** - * Runs all crons + * Runs all crons. * * @throws \Exception */ public function runCrons() { $this->entityManager->beginTransaction(); - $repository = $this->entityManager->getRepository("PartKeeprCronLoggerBundle:CronLogger"); + $repository = $this->entityManager->getRepository('PartKeeprCronLoggerBundle:CronLogger'); $cronJobs = $repository->findAll(); @@ -125,9 +125,9 @@ class CronLoggerService $command = $cronJob->getCronjob(); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => $command, - )); + ]); $application->run($input, $output); } diff --git a/src/PartKeepr/CronLoggerBundle/Tests/CronLoggerTest.php b/src/PartKeepr/CronLoggerBundle/Tests/CronLoggerTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\CronLoggerBundle\Tests; use PartKeepr\CoreBundle\Tests\WebTestCase; @@ -7,22 +8,22 @@ class CronLoggerTest extends WebTestCase { public function testCronLogger() { - $cronlogger = $this->getContainer()->get("partkeepr.cronlogger_service"); + $cronlogger = $this->getContainer()->get('partkeepr.cronlogger_service'); - $cronLoggerEntry = $cronlogger->markCronRun("test"); + $cronLoggerEntry = $cronlogger->markCronRun('test'); - $this->assertEquals("test", $cronLoggerEntry->getCronjob()); + $this->assertEquals('test', $cronLoggerEntry->getCronjob()); $this->assertInstanceOf("\DateTime", $cronLoggerEntry->getLastRunDate()); - $cronLoggerEntry->setLastRunDate(new \DateTime("1999-01-01 00:00:00")); + $cronLoggerEntry->setLastRunDate(new \DateTime('1999-01-01 00:00:00')); - $inactiveCronjobs = $cronlogger->getInactiveCronjobs(array("test")); - $this->assertEquals(false, in_array("test", $inactiveCronjobs)); + $inactiveCronjobs = $cronlogger->getInactiveCronjobs(['test']); + $this->assertEquals(false, in_array('test', $inactiveCronjobs)); - $this->getContainer()->get("doctrine.orm.entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.entity_manager')->flush(); - $inactiveCronjobs = $cronlogger->getInactiveCronjobs(array("test")); + $inactiveCronjobs = $cronlogger->getInactiveCronjobs(['test']); - $this->assertEquals(true, in_array("test", $inactiveCronjobs)); + $this->assertEquals(true, in_array('test', $inactiveCronjobs)); } } diff --git a/src/PartKeepr/DistributorBundle/Entity/Distributor.php b/src/PartKeepr/DistributorBundle/Entity/Distributor.php @@ -1,13 +1,14 @@ <?php + namespace PartKeepr\DistributorBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use Symfony\Component\Serializer\Annotation\Groups; /** - * Represents a distributor + * Represents a distributor. * * @ORM\Entity * @TargetService(uri="/api/distributors") @@ -15,7 +16,8 @@ use Symfony\Component\Serializer\Annotation\Groups; class Distributor extends BaseEntity { /** - * Holds the name of the distributor + * Holds the name of the distributor. + * * @ORM\Column(type="string",unique=true) * @Groups({"default"}) * @@ -24,7 +26,8 @@ class Distributor extends BaseEntity private $name; /** - * Holds the address of the distributor + * Holds the address of the distributor. + * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) * @@ -33,7 +36,8 @@ class Distributor extends BaseEntity private $address; /** - * Holds the URL of the distributor + * Holds the URL of the distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -42,7 +46,8 @@ class Distributor extends BaseEntity private $url; /** - * Holds the phone number of the distributor + * Holds the phone number of the distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -51,7 +56,8 @@ class Distributor extends BaseEntity private $phone; /** - * Holds the fax number of the distributor + * Holds the fax number of the distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -60,7 +66,8 @@ class Distributor extends BaseEntity private $fax; /** - * Holds the email of the distributor + * Holds the email of the distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -69,7 +76,8 @@ class Distributor extends BaseEntity private $email; /** - * Holds a comment for the distributor + * Holds a comment for the distributor. + * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) * @@ -78,7 +86,8 @@ class Distributor extends BaseEntity private $comment; /** - * Holds the SKU lookup URL of the distributor + * Holds the SKU lookup URL of the distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -87,7 +96,7 @@ class Distributor extends BaseEntity private $skuurl; /** - * Sets the name for the distributor + * Sets the name for the distributor. * * @param string $name The distributor's name */ @@ -97,7 +106,7 @@ class Distributor extends BaseEntity } /** - * Returns the name of the distributor + * Returns the name of the distributor. * * @return string The distributor's name */ @@ -107,7 +116,7 @@ class Distributor extends BaseEntity } /** - * Sets the address of this distributor + * Sets the address of this distributor. * * @param string $address The address of the distributor */ @@ -117,7 +126,7 @@ class Distributor extends BaseEntity } /** - * Returns the address of this distributor + * Returns the address of this distributor. * * @return string The address of this distributor */ @@ -127,7 +136,7 @@ class Distributor extends BaseEntity } /** - * Sets the phone number for this distributor + * Sets the phone number for this distributor. * * @param string $phone The phone number of this distributor */ @@ -137,7 +146,7 @@ class Distributor extends BaseEntity } /** - * Returns the phone number of this distributor + * Returns the phone number of this distributor. * * @return string The phone number */ @@ -147,7 +156,7 @@ class Distributor extends BaseEntity } /** - * Sets the fax number for this distributor + * Sets the fax number for this distributor. * * @param string $fax The fax number */ @@ -157,7 +166,7 @@ class Distributor extends BaseEntity } /** - * Returns the fax number for this distributor + * Returns the fax number for this distributor. * * @return string $fax The fax number */ @@ -167,7 +176,7 @@ class Distributor extends BaseEntity } /** - * Sets the comment for this distributor + * Sets the comment for this distributor. * * @param string $comment The comment for this distributor */ @@ -177,7 +186,7 @@ class Distributor extends BaseEntity } /** - * Returns the comment for this distributor + * Returns the comment for this distributor. * * @return string The comment */ @@ -187,7 +196,7 @@ class Distributor extends BaseEntity } /** - * Sets the email for this distributor + * Sets the email for this distributor. * * @param string $email The email for this distributor */ @@ -197,7 +206,7 @@ class Distributor extends BaseEntity } /** - * Returns the email for this distributor + * Returns the email for this distributor. * * @return string The email */ @@ -207,7 +216,7 @@ class Distributor extends BaseEntity } /** - * Sets the URL for this distributor + * Sets the URL for this distributor. * * @param string $url The URL for this distributor */ @@ -217,7 +226,7 @@ class Distributor extends BaseEntity } /** - * Returns the URL for this distributor + * Returns the URL for this distributor. * * @return string The URL */ @@ -227,7 +236,7 @@ class Distributor extends BaseEntity } /** - * Sets the SKU lookup URL for this distributor + * Sets the SKU lookup URL for this distributor. * * @param string $skuurl The SKU lookup URL for this distributor */ @@ -237,7 +246,7 @@ class Distributor extends BaseEntity } /** - * Returns the SKU lookup URL for this distributor + * Returns the SKU lookup URL for this distributor. * * @return string The SKU lookup URL */ diff --git a/src/PartKeepr/DistributorBundle/PartKeeprDistributorBundle.php b/src/PartKeepr/DistributorBundle/PartKeeprDistributorBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DistributorBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/DistributorBundle/Tests/DataFixtures/DistributorDataLoader.php b/src/PartKeepr/DistributorBundle/Tests/DataFixtures/DistributorDataLoader.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DistributorBundle\Tests\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; @@ -10,11 +11,11 @@ class DistributorDataLoader extends AbstractFixture public function load(ObjectManager $manager) { $distributor = new Distributor(); - $distributor->setName("TEST"); + $distributor->setName('TEST'); $manager->persist($distributor); $manager->flush(); - $this->addReference("distributor.first", $distributor); + $this->addReference('distributor.first', $distributor); } } diff --git a/src/PartKeepr/DoctrineReflectionBundle/Annotation/IgnoreIds.php b/src/PartKeepr/DoctrineReflectionBundle/Annotation/IgnoreIds.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Annotation; use Doctrine\ORM\Mapping\Annotation; diff --git a/src/PartKeepr/DoctrineReflectionBundle/Annotation/TargetService.php b/src/PartKeepr/DoctrineReflectionBundle/Annotation/TargetService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Annotation; use Doctrine\ORM\Mapping\Annotation; diff --git a/src/PartKeepr/DoctrineReflectionBundle/Annotation/VirtualField.php b/src/PartKeepr/DoctrineReflectionBundle/Annotation/VirtualField.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Annotation; use Doctrine\ORM\Mapping\Annotation; diff --git a/src/PartKeepr/DoctrineReflectionBundle/Command/GenerateEntityCommand.php b/src/PartKeepr/DoctrineReflectionBundle/Command/GenerateEntityCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -11,13 +12,13 @@ class GenerateEntityCommand extends ContainerAwareCommand { parent::configure(); $this->setName('generate:extjs:entities'); - $this->setDescription("Generates Sencha ExtJS models"); + $this->setDescription('Generates Sencha ExtJS models'); } public function execute(InputInterface $input, OutputInterface $output) { - $reflectionService = $this->getContainer()->get("doctrine_reflection_service"); - $cacheDir = $this->getContainer()->get("kernel")->getRootDir()."/../web/bundles/doctrinereflection/"; + $reflectionService = $this->getContainer()->get('doctrine_reflection_service'); + $cacheDir = $this->getContainer()->get('kernel')->getRootDir().'/../web/bundles/doctrinereflection/'; $reflectionService->createCache($cacheDir); } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/DoctrineReflectionBundle/DependencyInjection/Configuration.php b/src/PartKeepr/DoctrineReflectionBundle/DependencyInjection/Configuration.php @@ -6,7 +6,7 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** - * This is the class that validates and merges configuration from your app/config files + * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ diff --git a/src/PartKeepr/DoctrineReflectionBundle/DependencyInjection/PartKeeprDoctrineReflectionExtension.php b/src/PartKeepr/DoctrineReflectionBundle/DependencyInjection/PartKeeprDoctrineReflectionExtension.php @@ -2,13 +2,13 @@ namespace PartKeepr\DoctrineReflectionBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/DoctrineReflectionBundle/Exception/ExceptionWrapperHandler.php b/src/PartKeepr/DoctrineReflectionBundle/Exception/ExceptionWrapperHandler.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Exception; use FOS\RestBundle\View\ExceptionWrapperHandlerInterface; @@ -13,11 +14,11 @@ class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface public function wrap($data) { $data = [ - '@type' => 'Error', - 'hydra:title' => isset($context['title']) ? $context['title'] : 'An error occurred', - 'hydra:description' => $data["message"], + '@type' => 'Error', + 'hydra:title' => isset($context['title']) ? $context['title'] : 'An error occurred', + 'hydra:description' => $data['message'], ]; return $data; } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/DoctrineReflectionBundle/Filter/AdvancedSearchFilter.php b/src/PartKeepr/DoctrineReflectionBundle/Filter/AdvancedSearchFilter.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Filter; use Doctrine\Common\Persistence\ManagerRegistry; @@ -11,7 +12,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; /** - * Class AdvancedSearchFilter + * Class AdvancedSearchFilter. * * Allows filtering by different operators and nested associations. Expects a query parameter "filter" which includes * JSON in the following format: @@ -36,16 +37,16 @@ class AdvancedSearchFilter extends AbstractFilter */ private $propertyAccessor; - const OPERATOR_LESS_THAN = "<"; - const OPERATOR_GREATER_THAN = ">"; - const OPERATOR_EQUALS = "="; - const OPERATOR_GREATER_THAN_EQUALS = ">="; - const OPERATOR_LESS_THAN_EQUALS = ">="; - const OPERATOR_NOT_EQUALS = "!="; - const OPERATOR_IN = "in"; - const OPERATOR_LIKE = "like"; + const OPERATOR_LESS_THAN = '<'; + const OPERATOR_GREATER_THAN = '>'; + const OPERATOR_EQUALS = '='; + const OPERATOR_GREATER_THAN_EQUALS = '>='; + const OPERATOR_LESS_THAN_EQUALS = '>='; + const OPERATOR_NOT_EQUALS = '!='; + const OPERATOR_IN = 'in'; + const OPERATOR_LIKE = 'like'; - const OPERATORS = array( + const OPERATORS = [ self::OPERATOR_LESS_THAN, self::OPERATOR_GREATER_THAN, self::OPERATOR_EQUALS, @@ -54,22 +55,22 @@ class AdvancedSearchFilter extends AbstractFilter self::OPERATOR_NOT_EQUALS, self::OPERATOR_IN, self::OPERATOR_LIKE, - ); + ]; - private $aliases = array(); + private $aliases = []; private $parameterCount = 0; private $requestStack; - private $joins = array(); + private $joins = []; /** * @param ManagerRegistry $managerRegistry * @param IriConverterInterface $iriConverter * @param PropertyAccessorInterface $propertyAccessor - * @param null|array $properties Null to allow filtering on all properties with the exact strategy - * or a map of property name with strategy. + * @param null|array $properties Null to allow filtering on all properties with the exact strategy + * or a map of property name with strategy. */ public function __construct( ManagerRegistry $managerRegistry, @@ -86,7 +87,7 @@ class AdvancedSearchFilter extends AbstractFilter public function getDescription(ResourceInterface $resource) { - return array(); + return []; } /** @@ -103,23 +104,22 @@ class AdvancedSearchFilter extends AbstractFilter } $properties = $this->extractProperties($request); - $filters = $properties["filters"]; - $sorters = $properties["sorters"]; + $filters = $properties['filters']; + $sorters = $properties['sorters']; foreach ($filters as $filter) { - if (isset($fieldNames[$filter["property"]]) && $filter["association"] === null) { + if (isset($fieldNames[$filter['property']]) && $filter['association'] === null) { $queryBuilder ->andWhere( $this->getFilterExpression($queryBuilder, $filter) ); - } else { - if ($filter["association"] !== null) { + if ($filter['association'] !== null) { // Pull in associations $this->addJoins($queryBuilder, $filter); } - $filter["value"] = $this->getFilterValueFromUrl($filter["value"]); + $filter['value'] = $this->getFilterValueFromUrl($filter['value']); $queryBuilder->andWhere( $this->getFilterExpression($queryBuilder, $filter) @@ -128,7 +128,7 @@ class AdvancedSearchFilter extends AbstractFilter } foreach ($sorters as $sorter) { - if ($sorter["association"] !== null) { + if ($sorter['association'] !== null) { // Pull in associations $this->addJoins($queryBuilder, $sorter); } @@ -147,7 +147,7 @@ class AdvancedSearchFilter extends AbstractFilter private function getFilterValueFromUrl($value) { if (is_array($value)) { - $items = array(); + $items = []; foreach ($value as $iri) { try { @@ -183,30 +183,30 @@ class AdvancedSearchFilter extends AbstractFilter */ private function addJoins(QueryBuilder $queryBuilder, $filter) { - if (in_array($filter["association"], $this->joins)) { + if (in_array($filter['association'], $this->joins)) { // Association already added, return return; } - $associations = explode(".", $filter["association"]); + $associations = explode('.', $filter['association']); - $fullAssociation = "o"; + $fullAssociation = 'o'; foreach ($associations as $key => $association) { if (isset($associations[$key - 1])) { $parent = $associations[$key - 1]; } else { - $parent = "o"; + $parent = 'o'; } - $fullAssociation .= ".".$association; + $fullAssociation .= '.'.$association; $alias = $this->getAlias($fullAssociation); - $queryBuilder->join($parent.".".$association, $alias); + $queryBuilder->join($parent.'.'.$association, $alias); } - $this->joins[] = $filter["association"]; + $this->joins[] = $filter['association']; } /** @@ -215,29 +215,30 @@ class AdvancedSearchFilter extends AbstractFilter * @param QueryBuilder $queryBuilder * @param $filter * - * @return \Doctrine\ORM\Query\Expr\Comparison|\Doctrine\ORM\Query\Expr\Func * @throws \Exception + * + * @return \Doctrine\ORM\Query\Expr\Comparison|\Doctrine\ORM\Query\Expr\Func */ private function getFilterExpression(QueryBuilder $queryBuilder, $filter) { - if ($filter["association"] !== null) { - $alias = $this->getAlias("o.".$filter["association"]).".".$filter["property"]; + if ($filter['association'] !== null) { + $alias = $this->getAlias('o.'.$filter['association']).'.'.$filter['property']; } else { - $alias = "o.".$filter["property"]; + $alias = 'o.'.$filter['property']; } - if (strtolower($filter["operator"]) == self::OPERATOR_IN) { - if (!is_array($filter["value"])) { - throw new \Exception("Value needs to be an array for the IN operator"); + if (strtolower($filter['operator']) == self::OPERATOR_IN) { + if (!is_array($filter['value'])) { + throw new \Exception('Value needs to be an array for the IN operator'); } - return $queryBuilder->expr()->in($alias, $filter["value"]); + return $queryBuilder->expr()->in($alias, $filter['value']); } else { - $paramName = ":param".$this->parameterCount; + $paramName = ':param'.$this->parameterCount; $this->parameterCount++; - $queryBuilder->setParameter($paramName, $filter["value"]); + $queryBuilder->setParameter($paramName, $filter['value']); - switch (strtolower($filter["operator"])) { + switch (strtolower($filter['operator'])) { case self::OPERATOR_EQUALS: return $queryBuilder->expr()->eq($alias, $paramName); break; @@ -260,7 +261,7 @@ class AdvancedSearchFilter extends AbstractFilter return $queryBuilder->expr()->like($alias, $paramName); break; default: - throw new \Exception("Unknown filter"); + throw new \Exception('Unknown filter'); } } } @@ -271,18 +272,19 @@ class AdvancedSearchFilter extends AbstractFilter * @param QueryBuilder $queryBuilder * @param $sorter * - * @return \Doctrine\ORM\Query\Expr\Comparison|\Doctrine\ORM\Query\Expr\Func * @throws \Exception + * + * @return \Doctrine\ORM\Query\Expr\Comparison|\Doctrine\ORM\Query\Expr\Func */ private function applyOrderByExpression(QueryBuilder $queryBuilder, $sorter) { - if ($sorter["association"] !== null) { - $alias = $this->getAlias("o.".$sorter["association"]).".".$sorter["property"]; + if ($sorter['association'] !== null) { + $alias = $this->getAlias('o.'.$sorter['association']).'.'.$sorter['property']; } else { - $alias = "o.".$sorter["property"]; + $alias = 'o.'.$sorter['property']; } - return $queryBuilder->addOrderBy($alias, $sorter["direction"]); + return $queryBuilder->addOrderBy($alias, $sorter['direction']); } /** @@ -290,10 +292,10 @@ class AdvancedSearchFilter extends AbstractFilter */ protected function extractProperties(Request $request) { - $filters = array(); + $filters = []; - if ($request->query->has("filter")) { - $data = json_decode($request->query->get("filter")); + if ($request->query->has('filter')) { + $data = json_decode($request->query->get('filter')); if (is_array($data)) { foreach ($data as $filter) { @@ -304,10 +306,10 @@ class AdvancedSearchFilter extends AbstractFilter } } - $sorters = array(); + $sorters = []; - if ($request->query->has("order")) { - $data = json_decode($request->query->get("order")); + if ($request->query->has('order')) { + $data = json_decode($request->query->get('order')); if (is_array($data)) { foreach ($data as $sorter) { @@ -318,7 +320,7 @@ class AdvancedSearchFilter extends AbstractFilter } } - return array("filters" => $filters, "sorters" => $sorters); + return ['filters' => $filters, 'sorters' => $sorters]; } /** @@ -331,7 +333,7 @@ class AdvancedSearchFilter extends AbstractFilter private function getAlias($property) { if (!array_key_exists($property, $this->aliases)) { - $this->aliases[$property] = "t".count($this->aliases); + $this->aliases[$property] = 't'.count($this->aliases); } return $this->aliases[$property]; @@ -342,43 +344,43 @@ class AdvancedSearchFilter extends AbstractFilter * * @param $data * - * @return array An array containing the property, operator and value keys * @throws \Exception + * + * @return array An array containing the property, operator and value keys */ private function extractJSONFilters($data) { - $filter = array(); + $filter = []; - if (property_exists($data, "property")) { - if (strpos($data->property, ".") !== false) { - $associations = explode(".", $data->property); + if (property_exists($data, 'property')) { + if (strpos($data->property, '.') !== false) { + $associations = explode('.', $data->property); $property = array_pop($associations); - $filter["association"] = implode(".", $associations); - $filter["property"] = $property; + $filter['association'] = implode('.', $associations); + $filter['property'] = $property; } else { - $filter["association"] = null; - $filter["property"] = $data->property; + $filter['association'] = null; + $filter['property'] = $data->property; } - } else { - throw new \Exception("You need to set the filter property"); + throw new \Exception('You need to set the filter property'); } - if (property_exists($data, "operator")) { + if (property_exists($data, 'operator')) { if (!in_array(strtolower($data->operator), self::OPERATORS)) { - throw new \Exception(sprintf("Invalid operator %s", $data->operator)); + throw new \Exception(sprintf('Invalid operator %s', $data->operator)); } - $filter["operator"] = $data->operator; + $filter['operator'] = $data->operator; } else { - $filter["operator"] = self::OPERATOR_EQUALS; + $filter['operator'] = self::OPERATOR_EQUALS; } - if (property_exists($data, "value")) { - $filter["value"] = $data->value; + if (property_exists($data, 'value')) { + $filter['value'] = $data->value; } else { - throw new \Exception("No value specified"); + throw new \Exception('No value specified'); } return $filter; @@ -389,42 +391,42 @@ class AdvancedSearchFilter extends AbstractFilter * * @param $data * - * @return array An array containing the property, operator and value keys * @throws \Exception + * + * @return array An array containing the property, operator and value keys */ private function extractJSONSorters($data) { - $sorter = array(); + $sorter = []; if ($data->property) { - if (strpos($data->property, ".") !== false) { - $associations = explode(".", $data->property); + if (strpos($data->property, '.') !== false) { + $associations = explode('.', $data->property); $property = array_pop($associations); - $sorter["association"] = implode(".", $associations); - $sorter["property"] = $property; + $sorter['association'] = implode('.', $associations); + $sorter['property'] = $property; } else { - $sorter["association"] = null; - $sorter["property"] = $data->property; + $sorter['association'] = null; + $sorter['property'] = $data->property; } - } else { - throw new \Exception("You need to set the filter property"); + throw new \Exception('You need to set the filter property'); } if ($data->direction) { switch (strtoupper($data->direction)) { - case "DESC": - $sorter["direction"] = "DESC"; + case 'DESC': + $sorter['direction'] = 'DESC'; break; - case "ASC": + case 'ASC': default: - $sorter["direction"] = "ASC"; + $sorter['direction'] = 'ASC'; break; } } else { - $sorter["direction"] = "ASC"; + $sorter['direction'] = 'ASC'; } return $sorter; diff --git a/src/PartKeepr/DoctrineReflectionBundle/Services/ReflectionService.php b/src/PartKeepr/DoctrineReflectionBundle/Services/ReflectionService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\DoctrineReflectionBundle\Services; use Doctrine\Bundle\DoctrineBundle\Registry; @@ -10,7 +11,6 @@ use Symfony\Component\Templating\EngineInterface; class ReflectionService { - /** @var EntityManager */ protected $em; @@ -26,18 +26,18 @@ class ReflectionService } /** - * Returns a list of all registered entities, converted to the ExtJS naming scheme (. instead of \) + * Returns a list of all registered entities, converted to the ExtJS naming scheme (. instead of \). * * @return array */ public function getEntities() { - $entities = array(); + $entities = []; $meta = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($meta as $m) { - /** @var ClassMetadata $m */ + /* @var ClassMetadata $m */ $entities[] = $this->convertPHPToExtJSClassName($m->getName()); } @@ -45,7 +45,7 @@ class ReflectionService } /** - * Returns the ExtJS Model contents for a given entity + * Returns the ExtJS Model contents for a given entity. * * @param $entity string The ExtJS class name * @@ -55,31 +55,30 @@ class ReflectionService { $bTree = false; - $parentClass = "PartKeepr.data.HydraModel"; + $parentClass = 'PartKeepr.data.HydraModel'; $entity = $this->convertExtJSToPHPClassName($entity); $cm = $this->em->getClassMetadata($entity); if ($cm->getReflectionClass()->isSubclassOf("PartKeepr\CategoryBundle\Entity\AbstractCategory")) { - $parentClass = "PartKeepr.data.HydraTreeModel"; + $parentClass = 'PartKeepr.data.HydraTreeModel'; $bTree = true; } - - $fieldMappings = array(); + $fieldMappings = []; $fieldMappings = array_merge($fieldMappings, $this->getVirtualFieldMappings($cm)); $fieldMappings = array_merge($fieldMappings, $this->getDatabaseFieldMappings($cm)); $associationMappings = $this->getDatabaseAssociationMappings($cm, $bTree); - $renderParams = array( - "fields" => $fieldMappings, - "associations" => $associationMappings, - "className" => $this->convertPHPToExtJSClassName($entity), - "parentClass" => $parentClass, - ); + $renderParams = [ + 'fields' => $fieldMappings, + 'associations' => $associationMappings, + 'className' => $this->convertPHPToExtJSClassName($entity), + 'parentClass' => $parentClass, + ]; $targetService = $this->reader->getClassAnnotation( $cm->getReflectionClass(), @@ -87,7 +86,7 @@ class ReflectionService ); if ($targetService !== null) { - $renderParams["uri"] = $targetService->uri; + $renderParams['uri'] = $targetService->uri; } $ignoreIds = $this->reader->getClassAnnotation( @@ -96,16 +95,16 @@ class ReflectionService ); if ($ignoreIds !== null) { - $renderParams["ignoreIds"] = true; + $renderParams['ignoreIds'] = true; } else { - $renderParams["ignoreIds"] = false; + $renderParams['ignoreIds'] = false; } return $this->templateEngine->render('PartKeeprDoctrineReflectionBundle::model.js.twig', $renderParams); } /** - * Returns association mapping for a given entity + * Returns association mapping for a given entity. * * @param ClassMetadata $cm * @param bool|false $bTree @@ -116,52 +115,51 @@ class ReflectionService { $associations = $cm->getAssociationMappings(); - $associationMappings = array(); + $associationMappings = []; foreach ($associations as $association) { $getterPlural = false; - $associationType = $association["type"]; + $associationType = $association['type']; - switch ($association["type"]) { + switch ($association['type']) { case ClassMetadataInfo::MANY_TO_MANY: - $associationType = "MANY_TO_MANY"; + $associationType = 'MANY_TO_MANY'; $getterPlural = true; break; case ClassMetadataInfo::MANY_TO_ONE: - $associationType = "MANY_TO_ONE"; + $associationType = 'MANY_TO_ONE'; $getterPlural = false; break; case ClassMetadataInfo::ONE_TO_MANY: - $associationType = "ONE_TO_MANY"; + $associationType = 'ONE_TO_MANY'; $getterPlural = true; break; case ClassMetadataInfo::ONE_TO_ONE: - $associationType = "ONE_TO_ONE"; + $associationType = 'ONE_TO_ONE'; $getterPlural = false; break; } - $getter = "get".ucfirst($association["fieldName"]); + $getter = 'get'.ucfirst($association['fieldName']); $getterField = lcfirst($cm->getReflectionClass()->getShortName()).str_replace( - ".", - "", - $this->convertPHPToExtJSClassName($association["targetEntity"]) + '.', + '', + $this->convertPHPToExtJSClassName($association['targetEntity']) ); if ($getterPlural) { - $getterField .= "s"; + $getterField .= 's'; } - // The self-referencing association may not be written for trees, because ExtJS can't load all nodes // in one go. - if (!($bTree && $association["targetEntity"] == $cm->getName())) { - $associationMappings[$associationType][] = array( - "name" => $association["fieldName"], - "target" => $this->convertPHPToExtJSClassName($association["targetEntity"]), - "getter" => $getter, - "getterField" => $getterField, - ); + if (!($bTree && $association['targetEntity'] == $cm->getName())) { + $associationMappings[$associationType][] = [ + 'name' => $association['fieldName'], + 'target' => $this->convertPHPToExtJSClassName($association['targetEntity']), + 'getter' => $getter, + 'getterField' => $getterField, + ]; } } @@ -169,7 +167,7 @@ class ReflectionService } /** - * Returns all virtual field mappings + * Returns all virtual field mappings. * * @param ClassMetadata $cm * @@ -177,7 +175,7 @@ class ReflectionService */ protected function getVirtualFieldMappings(ClassMetadata $cm) { - $fieldMappings = array(); + $fieldMappings = []; foreach ($cm->getReflectionClass()->getProperties() as $property) { $virtualFieldAnnotation = $this->reader->getPropertyAnnotation( @@ -186,10 +184,10 @@ class ReflectionService ); if ($virtualFieldAnnotation !== null) { - $fieldMappings[] = array( - "name" => $property->getName(), - "type" => $this->getExtJSFieldMapping($virtualFieldAnnotation->type), - ); + $fieldMappings[] = [ + 'name' => $property->getName(), + 'type' => $this->getExtJSFieldMapping($virtualFieldAnnotation->type), + ]; } } @@ -197,37 +195,39 @@ class ReflectionService } /** - * Returns database field mappings + * Returns database field mappings. * * @param ClassMetadata $cm * - * @return array * @throws \Doctrine\ORM\Mapping\MappingException + * + * @return array */ protected function getDatabaseFieldMappings(ClassMetadata $cm) { - $fieldMappings = array(); + $fieldMappings = []; $fields = $cm->getFieldNames(); foreach ($fields as $field) { $currentMapping = $cm->getFieldMapping($field); - if ($currentMapping["fieldName"] == "id") { - $currentMapping["fieldName"] = "@id"; - $currentMapping["type"] = "string"; + if ($currentMapping['fieldName'] == 'id') { + $currentMapping['fieldName'] = '@id'; + $currentMapping['type'] = 'string'; } - $fieldMappings[] = array( - "name" => $currentMapping["fieldName"], - "type" => $this->getExtJSFieldMapping($currentMapping["type"]), - ); + $fieldMappings[] = [ + 'name' => $currentMapping['fieldName'], + 'type' => $this->getExtJSFieldMapping($currentMapping['type']), + ]; } return $fieldMappings; } /** - * Converts a doctrine/PHP type to the ExtJS type + * Converts a doctrine/PHP type to the ExtJS type. + * * @param $type string the PHP/doctrine type * * @return string The ExtJS type @@ -235,55 +235,57 @@ class ReflectionService protected function getExtJSFieldMapping($type) { switch ($type) { - case "integer": - return "int"; + case 'integer': + return 'int'; break; - case "string": - return "string"; + case 'string': + return 'string'; break; - case "text": - return "string"; + case 'text': + return 'string'; break; - case "datetime": - return "date"; + case 'datetime': + return 'date'; break; - case "boolean": - return "boolean"; + case 'boolean': + return 'boolean'; break; - case "float": - return "number"; + case 'float': + return 'number'; break; - case "decimal": - return "number"; + case 'decimal': + return 'number'; break; - case "array": - return "array"; + case 'array': + return 'array'; break; } - return "undefined"; + return 'undefined'; } /** - * Converts a PHP class name with namespaces to an ExtJS class name with namespaces + * Converts a PHP class name with namespaces to an ExtJS class name with namespaces. + * * @param $className * * @return string */ protected function convertPHPToExtJSClassName($className) { - return str_replace("\\", ".", $className); + return str_replace('\\', '.', $className); } /** - * Converts an ExtJS class name with namespaces to a PHP class name with namespaces + * Converts an ExtJS class name with namespaces to a PHP class name with namespaces. + * * @param $className * * @return string */ protected function convertExtJSToPHPClassName($className) { - return str_replace(".", "\\", $className); + return str_replace('.', '\\', $className); } public function createCache($cacheDir) @@ -295,11 +297,10 @@ class ReflectionService foreach ($entities as $entity) { $model = $this->getEntity($entity); - $this->writeCacheFile($cacheDir."/".$entity.'.js', $model); + $this->writeCacheFile($cacheDir.'/'.$entity.'.js', $model); } } - protected function writeCacheFile($file, $content) { $tmpFile = tempnam(dirname($file), basename($file)); diff --git a/src/PartKeepr/ExportBundle/Controller/ExportController.php b/src/PartKeepr/ExportBundle/Controller/ExportController.php @@ -1,47 +1,49 @@ <?php + namespace PartKeepr\ExportBundle\Controller; use Exporter\Writer\CsvWriter; use Exporter\Writer\XmlExcelWriter; -use Sensio\Bundle\FrameworkExtraBundle\Configuration as Routing; use FOS\RestBundle\Controller\Annotations\View; use FOS\RestBundle\Controller\FOSRestController; +use Sensio\Bundle\FrameworkExtraBundle\Configuration as Routing; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class ExportController extends FOSRestController { /** - * Exports the given data to a given format + * Exports the given data to a given format. * * @Routing\Route("/api/export", defaults={"method" = "post","_format" = "json"}) * @View() * * @return array */ - public function exportAction (Request $request) { + public function exportAction(Request $request) + { $contentTypes = $request->getAcceptableContentTypes(); $exporter = false; - $file = tempnam(sys_get_temp_dir(), "partkeepr_export"); + $file = tempnam(sys_get_temp_dir(), 'partkeepr_export'); unlink($file); foreach ($contentTypes as $contentType) { switch ($contentType) { - case "text/comma-separated-values": + case 'text/comma-separated-values': $exporter = new CsvWriter($file, ',', '"', '\\', false); break; - case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": + case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': $exporter = new XmlExcelWriter($file, false); break; } } if ($exporter === false) { - throw new \Exception("No or invalid format specified"); + throw new \Exception('No or invalid format specified'); } - $content = json_decode($request->getContent(),true); + $content = json_decode($request->getContent(), true); $exporter->open(); foreach ($content as $item) { diff --git a/src/PartKeepr/ExportBundle/DependencyInjection/Compiler/CsvFormatPass.php b/src/PartKeepr/ExportBundle/DependencyInjection/Compiler/CsvFormatPass.php @@ -1,13 +1,14 @@ <?php -namespace PartKeepr\ExportBundle\DependencyInjection\Compiler; +namespace PartKeepr\ExportBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class CsvFormatPass implements CompilerPassInterface { - public function process (ContainerBuilder $container) { + public function process(ContainerBuilder $container) + { $container->getDefinition('api.format_negotiator')->addMethodCall('registerFormat', [ 'csv', ['text/comma-separated-values'], true, ]); diff --git a/src/PartKeepr/ExportBundle/DependencyInjection/Compiler/XmlExcelFormatPass.php b/src/PartKeepr/ExportBundle/DependencyInjection/Compiler/XmlExcelFormatPass.php @@ -1,13 +1,14 @@ <?php -namespace PartKeepr\ExportBundle\DependencyInjection\Compiler; +namespace PartKeepr\ExportBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class XmlExcelFormatPass implements CompilerPassInterface { - public function process (ContainerBuilder $container) { + public function process(ContainerBuilder $container) + { $container->getDefinition('api.format_negotiator')->addMethodCall('registerFormat', [ 'xlsx', ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], true, ]); diff --git a/src/PartKeepr/ExportBundle/EventListener/AbstractResponderViewListener.php b/src/PartKeepr/ExportBundle/EventListener/AbstractResponderViewListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ExportBundle\EventListener; use Exporter\Writer\WriterInterface; @@ -7,7 +8,6 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; use Symfony\Component\PropertyAccess\PropertyAccess; - abstract class AbstractResponderViewListener { const FORMAT = 'null'; @@ -48,16 +48,15 @@ abstract class AbstractResponderViewListener break; } - $columns = array(); + $columns = []; - if ($event->getRequest()->query->has("columns")) { - $columns = json_decode($event->getRequest()->query->get("columns")); + if ($event->getRequest()->query->has('columns')) { + $columns = json_decode($event->getRequest()->query->get('columns')); } $data = $this->flatten($controllerResult, $columns); - - $file = tempnam(sys_get_temp_dir(), "partkeepr_export"); + $file = tempnam(sys_get_temp_dir(), 'partkeepr_export'); unlink($file); $writer = $this->getWriter($file); $writer->open(); @@ -73,7 +72,7 @@ abstract class AbstractResponderViewListener } /** - * Returns the writer + * Returns the writer. * * @param $file * @@ -92,7 +91,7 @@ abstract class AbstractResponderViewListener protected function flatten($data, $mappings) { $accessor = PropertyAccess::createPropertyAccessor(); - $finalData = array(); + $finalData = []; foreach ($data as $key => $row) { foreach ($mappings as $mapping) { try { @@ -104,10 +103,7 @@ abstract class AbstractResponderViewListener } } } catch (\Exception $e) { - } - - } } diff --git a/src/PartKeepr/ExportBundle/EventListener/CsvResponderViewListener.php b/src/PartKeepr/ExportBundle/EventListener/CsvResponderViewListener.php @@ -1,14 +1,15 @@ <?php + namespace PartKeepr\ExportBundle\EventListener; use Exporter\Writer\CsvWriter; - class CsvResponderViewListener extends AbstractResponderViewListener { const FORMAT = 'csv'; - protected function getWriter($file) { - return new CsvWriter($file); - } + protected function getWriter($file) + { + return new CsvWriter($file); + } } diff --git a/src/PartKeepr/ExportBundle/EventListener/XmlExcelResponderViewListener.php b/src/PartKeepr/ExportBundle/EventListener/XmlExcelResponderViewListener.php @@ -1,9 +1,9 @@ <?php + namespace PartKeepr\ExportBundle\EventListener; use Exporter\Writer\XmlExcelWriter; - class XmlExcelResponderViewListener extends AbstractResponderViewListener { const FORMAT = 'xlsx'; diff --git a/src/PartKeepr/ExportBundle/PartKeeprExportBundle.php b/src/PartKeepr/ExportBundle/PartKeeprExportBundle.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\ExportBundle; +namespace PartKeepr\ExportBundle; use PartKeepr\ExportBundle\DependencyInjection\Compiler\CsvFormatPass; use PartKeepr\ExportBundle\DependencyInjection\Compiler\XmlExcelFormatPass; diff --git a/src/PartKeepr/FootprintBundle/Controller/FootprintAttachmentController.php b/src/PartKeepr/FootprintBundle/Controller/FootprintAttachmentController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle\Controller; use PartKeepr\UploadedFileBundle\Controller\FileController; @@ -6,10 +7,10 @@ use PartKeepr\UploadedFileBundle\Controller\FileController; class FootprintAttachmentController extends FileController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\FootprintBundle\\Entity\\FootprintAttachment"; + return 'PartKeepr\\FootprintBundle\\Entity\\FootprintAttachment'; } } diff --git a/src/PartKeepr/FootprintBundle/Controller/FootprintImageController.php b/src/PartKeepr/FootprintBundle/Controller/FootprintImageController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle\Controller; use PartKeepr\ImageBundle\Controller\ImageController; @@ -6,10 +7,10 @@ use PartKeepr\ImageBundle\Controller\ImageController; class FootprintImageController extends ImageController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\FootprintBundle\\Entity\\FootprintImage"; + return 'PartKeepr\\FootprintBundle\\Entity\\FootprintImage'; } } diff --git a/src/PartKeepr/FootprintBundle/DataFixtures/CategoryDataLoader.php b/src/PartKeepr/FootprintBundle/DataFixtures/CategoryDataLoader.php @@ -1,15 +1,18 @@ <?php + namespace PartKeepr\FootprintBundle\DataFixtures; use PartKeepr\CategoryBundle\DataFixtures\AbstractCategoryDataLoader; class CategoryDataLoader extends AbstractCategoryDataLoader { - protected function getEntityClass () { + protected function getEntityClass() + { return 'PartKeepr\FootprintBundle\Entity\FootprintCategory'; } - protected function getReferencePrefix () { - return "footprintcategory"; + protected function getReferencePrefix() + { + return 'footprintcategory'; } } diff --git a/src/PartKeepr/FootprintBundle/DependencyInjection/PartKeeprFootprintExtension.php b/src/PartKeepr/FootprintBundle/DependencyInjection/PartKeeprFootprintExtension.php @@ -2,13 +2,13 @@ namespace PartKeepr\FootprintBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/FootprintBundle/Entity/Footprint.php b/src/PartKeepr/FootprintBundle/Entity/Footprint.php @@ -1,12 +1,13 @@ <?php + namespace PartKeepr\FootprintBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; -use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFile; +use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -16,7 +17,7 @@ use Symfony\Component\Serializer\Annotation\Groups; class Footprint extends BaseEntity { /** - * Holds the footprint name + * Holds the footprint name. * * @ORM\Column(length=64,unique=true) * @Groups({"default"}) @@ -26,7 +27,7 @@ class Footprint extends BaseEntity private $name; /** - * Holds the footprint description + * Holds the footprint description. * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) @@ -36,7 +37,7 @@ class Footprint extends BaseEntity private $description; /** - * The category of the footprint + * The category of the footprint. * * @ORM\ManyToOne(targetEntity="FootprintCategory", inversedBy="footprints") * @Groups({"default"}) @@ -46,19 +47,20 @@ class Footprint extends BaseEntity private $category; /** - * Holds the footprint image + * Holds the footprint image. * * @ORM\OneToOne(targetEntity="PartKeepr\FootprintBundle\Entity\FootprintImage", * mappedBy="footprint", cascade={"persist", "remove"}, orphanRemoval=true) * * @Groups({"default"}) * @UploadedFile() + * * @var FootprintImage */ private $image; /** - * Holds the footprint attachments + * Holds the footprint attachments. * * @ORM\OneToMany(targetEntity="PartKeepr\FootprintBundle\Entity\FootprintAttachment", * mappedBy="footprint", cascade={"persist", "remove"}, orphanRemoval=true) @@ -70,7 +72,8 @@ class Footprint extends BaseEntity private $attachments; /** - * Returns the category path + * Returns the category path. + * * @Groups({"default"}) * * @return string @@ -80,12 +83,12 @@ class Footprint extends BaseEntity if ($this->category !== null) { return $this->category->getCategoryPath(); } else { - return ""; + return ''; } } /** - * Constructs a new Footprint entity + * Constructs a new Footprint entity. */ public function __construct() { @@ -93,7 +96,7 @@ class Footprint extends BaseEntity } /** - * Sets the name of this footprint + * Sets the name of this footprint. * * @param string $name The footprint name * @@ -105,7 +108,7 @@ class Footprint extends BaseEntity } /** - * Returns the name of this footprint + * Returns the name of this footprint. * * @return string The name of this footprint */ @@ -115,7 +118,7 @@ class Footprint extends BaseEntity } /** - * Sets the description of this footprint + * Sets the description of this footprint. * * @param string $description The description * @@ -127,7 +130,7 @@ class Footprint extends BaseEntity } /** - * Returns the description of this footprint + * Returns the description of this footprint. * * @return string The description */ @@ -137,7 +140,7 @@ class Footprint extends BaseEntity } /** - * Sets the category for this footprint + * Sets the category for this footprint. * * @param FootprintCategory $category The category * @@ -149,7 +152,7 @@ class Footprint extends BaseEntity } /** - * Returns the category of this footprint + * Returns the category of this footprint. * * @return FootprintCategory The footprint category */ @@ -159,7 +162,7 @@ class Footprint extends BaseEntity } /** - * Sets the footprint image + * Sets the footprint image. * * @param FootprintImage $image The footprint image * @@ -180,7 +183,7 @@ class Footprint extends BaseEntity } /** - * Returns the footprint image + * Returns the footprint image. * * @return FootprintImage The footprint image */ @@ -190,7 +193,7 @@ class Footprint extends BaseEntity } /** - * Returns the attachments for this footprint + * Returns the attachments for this footprint. * * @return ArrayCollection The attachments */ @@ -203,7 +206,7 @@ class Footprint extends BaseEntity * Adds an IC Logo. * * @param FootprintAttachment|\PartKeepr\UploadedFileBundle\Entity\TempUploadedFile $attachment - * Either a FootprintAttachment or a TempUploadedFile + * Either a FootprintAttachment or a TempUploadedFile * * @return void */ diff --git a/src/PartKeepr/FootprintBundle/Entity/FootprintAttachment.php b/src/PartKeepr/FootprintBundle/Entity/FootprintAttachment.php @@ -1,27 +1,29 @@ <?php + namespace PartKeepr\FootprintBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\UploadedFileBundle\Entity\UploadedFile; /** - * Holds a footprint attachment + * Holds a footprint attachment. * * @ORM\Entity **/ class FootprintAttachment extends UploadedFile { /** - * Creates a new footprint attachment + * Creates a new footprint attachment. */ public function __construct() { parent::__construct(); - $this->setType("FootprintAttachment"); + $this->setType('FootprintAttachment'); } /** - * The footprint object + * The footprint object. + * * @ORM\ManyToOne(targetEntity="PartKeepr\FootprintBundle\Entity\Footprint",inversedBy="attachments") * * @var Footprint @@ -29,7 +31,7 @@ class FootprintAttachment extends UploadedFile private $footprint = null; /** - * Sets the footprint + * Sets the footprint. * * @param Footprint $footprint The footprint to set */ @@ -39,7 +41,7 @@ class FootprintAttachment extends UploadedFile } /** - * Returns the footprint + * Returns the footprint. * * @return Footprint the footprint */ diff --git a/src/PartKeepr/FootprintBundle/Entity/FootprintCategory.php b/src/PartKeepr/FootprintBundle/Entity/FootprintCategory.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; @@ -34,20 +35,22 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac /** * @ORM\OneToMany(targetEntity="Footprint", mappedBy="category") - * */ protected $footprints; /** * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) + * * @var string */ protected $categoryPath; /** - * Sets the parent category + * Sets the parent category. + * * @Groups({"default"}) + * * @param AbstractCategory|null $parent */ public function setParent(AbstractCategory $parent = null) @@ -56,7 +59,7 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac } /** - * Returns the parent category + * Returns the parent category. * * @return mixed */ @@ -66,7 +69,7 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac } /** - * Returns the footprints + * Returns the footprints. * * @return ArrayCollection */ @@ -76,7 +79,7 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac } /** - * Returns the children + * Returns the children. * * @return ArrayCollection */ @@ -86,7 +89,7 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac } /** - * Returns the category path + * Returns the category path. * * @return string */ @@ -109,7 +112,7 @@ class FootprintCategory extends AbstractCategory implements CategoryPathInterfac public function generateCategoryPath($pathSeparator) { if ($this->getParent() !== null) { - return $this->getParent()->generateCategoryPath($pathSeparator) . $pathSeparator . $this->getName(); + return $this->getParent()->generateCategoryPath($pathSeparator).$pathSeparator.$this->getName(); } else { return $this->getName(); } diff --git a/src/PartKeepr/FootprintBundle/Entity/FootprintImage.php b/src/PartKeepr/FootprintBundle/Entity/FootprintImage.php @@ -1,18 +1,20 @@ <?php + namespace PartKeepr\FootprintBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\ImageBundle\Entity\Image; /** - * Holds a footprint image + * Holds a footprint image. * * @ORM\Entity **/ class FootprintImage extends Image { /** - * The footprint object + * The footprint object. + * * @ORM\OneToOne(targetEntity="PartKeepr\FootprintBundle\Entity\Footprint",inversedBy="image") * * @var Footprint @@ -20,7 +22,7 @@ class FootprintImage extends Image private $footprint = null; /** - * Creates a new IC logo instance + * Creates a new IC logo instance. */ public function __construct() { @@ -28,7 +30,7 @@ class FootprintImage extends Image } /** - * Sets the footprint + * Sets the footprint. * * @param Footprint $footprint The footprint to set */ @@ -38,7 +40,7 @@ class FootprintImage extends Image } /** - * Returns the footprint + * Returns the footprint. * * @return Footprint the footprint */ diff --git a/src/PartKeepr/FootprintBundle/Listeners/CategoryPathListener.php b/src/PartKeepr/FootprintBundle/Listeners/CategoryPathListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle\Listeners; use Doctrine\ORM\EntityManager; @@ -9,7 +10,8 @@ use Symfony\Component\DependencyInjection\ContainerAware; class CategoryPathListener extends ContainerAware { - public function __construct (Container $container) { + public function __construct(Container $container) + { $this->setContainer($container); } @@ -45,7 +47,7 @@ class CategoryPathListener extends ContainerAware public function updateCategoryPaths(FootprintCategory $footprintCategory, OnFlushEventArgs $eventArgs) { $entityManager = $eventArgs->getEntityManager(); - $pathSeparator = $this->container->getParameter("partkeepr.category.path_separator"); + $pathSeparator = $this->container->getParameter('partkeepr.category.path_separator'); $footprintCategory->setCategoryPath($footprintCategory->generateCategoryPath($pathSeparator)); diff --git a/src/PartKeepr/FootprintBundle/PartKeeprFootprintBundle.php b/src/PartKeepr/FootprintBundle/PartKeeprFootprintBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/FootprintBundle/Tests/CategoryCreateTest.php b/src/PartKeepr/FootprintBundle/Tests/CategoryCreateTest.php @@ -1,11 +1,11 @@ <?php + namespace PartKeepr\FootprintBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractCategoryCreateTest; class CategoryCreateTest extends AbstractCategoryCreateTest { - public function getResourceClass() { return 'PartKeepr\FootprintBundle\Entity\FootprintCategory'; @@ -18,6 +18,6 @@ class CategoryCreateTest extends AbstractCategoryCreateTest public function getReferencePrefix() { - return "footprintcategory"; + return 'footprintcategory'; } } diff --git a/src/PartKeepr/FootprintBundle/Tests/MoveActionTest.php b/src/PartKeepr/FootprintBundle/Tests/MoveActionTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\FootprintBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractMoveCategoryTest; @@ -12,6 +13,6 @@ class MoveActionTest extends AbstractMoveCategoryTest public function getReferencePrefix() { - return "footprintcategory"; + return 'footprintcategory'; } } diff --git a/src/PartKeepr/FrontendBundle/Controller/IndexController.php b/src/PartKeepr/FrontendBundle/Controller/IndexController.php @@ -11,58 +11,60 @@ use Symfony\Component\Routing\Annotation\Route; class IndexController extends Controller { /** - * This is basically a copy of the PartKeepr's legacy index.php + * This is basically a copy of the PartKeepr's legacy index.php. + * * @Route("/") */ public function indexAction() { - if ($this->getParameter("partkeepr.maintenance") !== false) { - $renderParams["maintenanceTitle"] = $this->getParameter("partkeepr.maintenance.title"); - $renderParams["maintenanceMessage"] = $this->getParameter("partkeepr.maintenance.message"); + if ($this->getParameter('partkeepr.maintenance') !== false) { + $renderParams['maintenanceTitle'] = $this->getParameter('partkeepr.maintenance.title'); + $renderParams['maintenanceMessage'] = $this->getParameter('partkeepr.maintenance.message'); - return $this->render("@PartKeeprFrontend/maintenance.html.twig", $renderParams); + return $this->render('@PartKeeprFrontend/maintenance.html.twig', $renderParams); } - $aParameters = array(); - $aParameters["doctrine_orm_version"] = ORMVersion::VERSION; - $aParameters["doctrine_dbal_version"] = DBALVersion::VERSION; - $aParameters["doctrine_common_version"] = DoctrineCommonVersion::VERSION; - $aParameters["php_version"] = phpversion(); - $aParameters["auto_start_session"] = true; + $aParameters = []; + $aParameters['doctrine_orm_version'] = ORMVersion::VERSION; + $aParameters['doctrine_dbal_version'] = DBALVersion::VERSION; + $aParameters['doctrine_common_version'] = DoctrineCommonVersion::VERSION; + $aParameters['php_version'] = phpversion(); + $aParameters['auto_start_session'] = true; - $maxPostSize = $this->get("partkeepr_systemservice")->getBytesFromHumanReadable(ini_get("post_max_size")); - $maxFileSize = $this->get("partkeepr_systemservice")->getBytesFromHumanReadable(ini_get("upload_max_filesize")); + $maxPostSize = $this->get('partkeepr_systemservice')->getBytesFromHumanReadable(ini_get('post_max_size')); + $maxFileSize = $this->get('partkeepr_systemservice')->getBytesFromHumanReadable(ini_get('upload_max_filesize')); - $aParameters["maxUploadSize"] = min($maxPostSize, $maxFileSize); + $aParameters['maxUploadSize'] = min($maxPostSize, $maxFileSize); // @todo Hardcoded for now due to GD, see #445 - $aParameters["availableImageFormats"] = array("JPG", "GIF", "PNG"); + $aParameters['availableImageFormats'] = ['JPG', 'GIF', 'PNG']; /* Automatic Login */ - if ($this->getParameterWithDefault("partkeepr.frontend.auto_login.enabled", false) === true) { - $aParameters["autoLoginUsername"] = $this->getParameter("partkeepr.frontend.auto_login.username"); - $aParameters["autoLoginPassword"] = $this->getParameter("partkeepr.frontend.auto_login.password"); + if ($this->getParameterWithDefault('partkeepr.frontend.auto_login.enabled', false) === true) { + $aParameters['autoLoginUsername'] = $this->getParameter('partkeepr.frontend.auto_login.username'); + $aParameters['autoLoginPassword'] = $this->getParameter('partkeepr.frontend.auto_login.password'); } - if ($this->getParameterWithDefault("partkeepr.frontend.motd", false) !== false) { - $aParameters["motd"] = $this->getParameterWithDefault("partkeepr.frontend.motd", false); + if ($this->getParameterWithDefault('partkeepr.frontend.motd', false) !== false) { + $aParameters['motd'] = $this->getParameterWithDefault('partkeepr.frontend.motd', false); } - $aParameters["max_users"] = $this->getParameterWithDefault("partkeepr.auth.max_users", "unlimited"); + $aParameters['max_users'] = $this->getParameterWithDefault('partkeepr.auth.max_users', 'unlimited'); - $aParameters["authentication_provider"] = $this->getParameter("partkeepr.authentication_provider"); - $aParameters["tip_of_the_day_uri"] = $this->getParameter("partkeepr.tip_of_the_day_uri"); + $aParameters['authentication_provider'] = $this->getParameter('partkeepr.authentication_provider'); + $aParameters['tip_of_the_day_uri'] = $this->getParameter('partkeepr.tip_of_the_day_uri'); - $aParameters["password_change"] = $this->getParameterWithDefault("partkeepr.auth.allow_password_change", true); + $aParameters['password_change'] = $this->getParameterWithDefault('partkeepr.auth.allow_password_change', true); - $renderParams = array(); - $renderParams["parameters"] = $aParameters; - $renderParams["debug"] = $this->get("kernel")->isDebug(); + $renderParams = []; + $renderParams['parameters'] = $aParameters; + $renderParams['debug'] = $this->get('kernel')->isDebug(); return $this->render('PartKeeprFrontendBundle::index.html.twig', $renderParams); } - public function getParameterWithDefault ($name, $default) { + public function getParameterWithDefault($name, $default) + { if ($this->container->hasParameter($name)) { return $this->container->getParameter($name); } else { diff --git a/src/PartKeepr/FrontendBundle/PartKeeprFrontendBundle.php b/src/PartKeepr/FrontendBundle/PartKeeprFrontendBundle.php @@ -6,4 +6,4 @@ use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprFrontendBundle extends Bundle { -}- \ No newline at end of file +} diff --git a/src/PartKeepr/ImageBundle/Controller/ImageController.php b/src/PartKeepr/ImageBundle/Controller/ImageController.php @@ -1,11 +1,11 @@ <?php + namespace PartKeepr\ImageBundle\Controller; use Doctrine\ORM\EntityManager; use Gaufrette\Exception\FileNotFound; use Imagine\Gd\Imagine; use Imagine\Image\Box; -use Imagine\Image\Point; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use PartKeepr\ImageBundle\Entity\CachedImage; use PartKeepr\ImageBundle\Entity\Image as PartKeeprImage; @@ -18,7 +18,6 @@ use Symfony\Component\HttpFoundation\Response; abstract class ImageController extends FileController { /** - * * @ApiDoc( * description="Returns a scaled and cached image. Note that the binary data is directly returned.", * parameters={ @@ -35,17 +34,17 @@ abstract class ImageController extends FileController public function getImageAction(Request $request, $id) { /** - * @var $em EntityManager + * @var EntityManager */ $em = $this->getDoctrine()->getManager(); /** - * @var $image PartKeeprImage + * @var PartKeeprImage */ $image = $em->find($this->getEntityClass(), $id); - $width = $request->get("maxWidth"); - $height = $request->get("maxHeight"); + $width = $request->get('maxWidth'); + $height = $request->get('maxHeight'); if ($width === null) { $width = 200; @@ -56,7 +55,7 @@ abstract class ImageController extends FileController } if ($image === null) { - return new ImageResponse($width, $height, 404, "404 not found"); + return new ImageResponse($width, $height, 404, '404 not found'); } try { @@ -64,15 +63,14 @@ abstract class ImageController extends FileController } catch (FileNotFound $e) { $this->get('logger')->error($e->getMessage()); - return new ImageResponse($width, $height, 404, "404 not found"); + return new ImageResponse($width, $height, 404, '404 not found'); } catch (\Exception $e) { $this->get('logger')->error($e->getMessage()); - return new ImageResponse($width, $height, 500, "500 Server Error"); + return new ImageResponse($width, $height, 500, '500 Server Error'); } - return new Response(file_get_contents($file), 200, array("Content-Type" => "image/png")); - + return new Response(file_get_contents($file), 200, ['Content-Type' => 'image/png']); } /** @@ -82,7 +80,7 @@ abstract class ImageController extends FileController */ public function getImageCacheDirectory() { - return $this->container->getParameter("partkeepr.image_cache_directory"); + return $this->container->getParameter('partkeepr.image_cache_directory'); } /** @@ -104,7 +102,7 @@ abstract class ImageController extends FileController * @param UploadedFile $image The image to scale * @param int $width The width * @param int $height The height - * @param boolean $padding If true, pad the output image to the given size (transparent background). + * @param bool $padding If true, pad the output image to the given size (transparent background). * * @return string The path to the scaled file */ @@ -113,9 +111,9 @@ abstract class ImageController extends FileController $this->ensureCacheDirExists(); if ($padding) { - $mode = "fwp"; + $mode = 'fwp'; } else { - $mode = "fw"; + $mode = 'fw'; } $outputFile = $this->getImageCacheFilename($image, $width, $height, $mode); @@ -127,7 +125,7 @@ abstract class ImageController extends FileController $imagine = new Imagine(); $localCacheFile = $this->getImageCacheDirectory().$image->getFullFilename(); - $storage = $this->get("partkeepr_uploadedfile_service")->getStorage($image); + $storage = $this->get('partkeepr_uploadedfile_service')->getStorage($image); file_put_contents($localCacheFile, $storage->read($image->getFullFilename())); @@ -145,8 +143,8 @@ abstract class ImageController extends FileController * Returns the path to an image which has been cached in a particular width, height and mode. * * @param UploadedFile $image The image - * @param integer $width The width - * @param integer $height The height + * @param int $width The width + * @param int $height The height * @param string $mode The mode * * @return string @@ -154,8 +152,8 @@ abstract class ImageController extends FileController public function getImageCacheFilename(UploadedFile $image, $width, $height, $mode) { $outputFile = $this->getImageCacheDirectory(); - $outputFile .= "/".sha1($image->getFilename()); - $outputFile .= $width."x".$height."_".$mode.".png"; + $outputFile .= '/'.sha1($image->getFilename()); + $outputFile .= $width.'x'.$height.'_'.$mode.'.png'; return $outputFile; } @@ -163,10 +161,10 @@ abstract class ImageController extends FileController /** * Checks if the database contains the cache file. * - * @param UploadedFile $image - * @param $width - * @param $height - * @param $mode + * @param UploadedFile $image + * @param $width + * @param $height + * @param $mode * * @return bool */ @@ -175,15 +173,15 @@ abstract class ImageController extends FileController $cacheFilename = $this->getImageCacheFilename($image, $width, $height, $mode); /** - * @var $em EntityManager + * @var EntityManager */ $em = $this->getDoctrine()->getManager(); $queryBuilder = $em->createQueryBuilder(); - $queryBuilder->select("COUNT(c)") - ->from('PartKeepr\ImageBundle\Entity\CachedImage', "c") - ->where("c.cacheFile = :file") - ->setParameter("file", $cacheFilename); + $queryBuilder->select('COUNT(c)') + ->from('PartKeepr\ImageBundle\Entity\CachedImage', 'c') + ->where('c.cacheFile = :file') + ->setParameter('file', $cacheFilename); if ($queryBuilder->getQuery()->getSingleScalarResult() > 0) { return true; diff --git a/src/PartKeepr/ImageBundle/Controller/TemporaryImageController.php b/src/PartKeepr/ImageBundle/Controller/TemporaryImageController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ImageBundle\Controller; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -18,7 +19,7 @@ class TemporaryImageController extends ImageController use ActionUtilTrait; /** - * Handles a temporary image upload + * Handles a temporary image upload. * * @RequestParam(name="url",description="An URL where the image is located",strict=false) * ApiDoc(section="image",output="PartKeepr\ImageBundle\Response\TemporaryImageUploadResponse") @@ -26,32 +27,33 @@ class TemporaryImageController extends ImageController * * @param Request $request The request to process * - * @return JsonResponse The JSON response from the temporary image upload * @throws \Exception An exception if neither the userfile form parameter or an URL was given + * + * @return JsonResponse The JSON response from the temporary image upload */ public function uploadAction(Request $request) { $image = new TempImage(); - $imageService = $this->get("partkeepr_image_service"); + $imageService = $this->get('partkeepr_image_service'); if ($request->files->has('userfile') && $request->files->get('userfile') != null) { $file = $request->files->get('userfile'); - /** + /* * @var $file UploadedFile */ $imageService->replace($image, new File($file->getPathname())); $image->setOriginalFilename($file->getClientOriginalName()); - } elseif ($request->request->has("url")) { - $imageService->replaceFromURL($image, $request->request->get("url")); + } elseif ($request->request->has('url')) { + $imageService->replaceFromURL($image, $request->request->get('url')); } else { - throw new \Exception("Error: No valid file given"); + throw new \Exception('Error: No valid file given'); } $this->getDoctrine()->getManager()->persist($image); $this->getDoctrine()->getManager()->flush(); /** - * @var ResourceInterface $resourceType + * @var ResourceInterface */ list($resourceType) = $this->extractAttributes($request); @@ -65,7 +67,7 @@ class TemporaryImageController extends ImageController } /** - * Uploads a webcam image + * Uploads a webcam image. * * @param Request $request The request to process * @@ -74,13 +76,12 @@ class TemporaryImageController extends ImageController public function webcamUploadAction(Request $request) { $image = new TempImage(); - $imageService = $this->get("partkeepr_image_service"); - + $imageService = $this->get('partkeepr_image_service'); $data = $request->getContent(); $base64 = explode(',', $data); - $imageService->replaceFromData($image, base64_decode($base64[1]), "webcam.png"); + $imageService->replaceFromData($image, base64_decode($base64[1]), 'webcam.png'); $this->getDoctrine()->getManager()->persist($image); $this->getDoctrine()->getManager()->flush(); @@ -89,10 +90,10 @@ class TemporaryImageController extends ImageController } /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\ImageBundle\\Entity\\TempImage"; + return 'PartKeepr\\ImageBundle\\Entity\\TempImage'; } } diff --git a/src/PartKeepr/ImageBundle/DependencyInjection/PartKeeprImageExtension.php b/src/PartKeepr/ImageBundle/DependencyInjection/PartKeeprImageExtension.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\ImageBundle\DependencyInjection; +use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; -use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader; class PartKeeprImageExtension extends Extension { /** - * {@inheritDoc} + * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { diff --git a/src/PartKeepr/ImageBundle/Entity/CachedImage.php b/src/PartKeepr/ImageBundle/Entity/CachedImage.php @@ -1,9 +1,10 @@ <?php + namespace PartKeepr\ImageBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\UploadedFileBundle\Entity\UploadedFile; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\UploadedFileBundle\Entity\UploadedFile; /** * Represents a cached image. Cached images are used for scale/resize @@ -15,9 +16,9 @@ use PartKeepr\CoreBundle\Entity\BaseEntity; class CachedImage extends BaseEntity { /** - * Specifies the ID of the original image + * Specifies the ID of the original image. * - * @var integer + * @var int * @ORM\Column(type="integer") */ private $originalId; @@ -31,7 +32,7 @@ class CachedImage extends BaseEntity private $originalType; /** - * The cache filename of the image + * The cache filename of the image. * * @var string * @ORM\Column(type="string") @@ -46,13 +47,13 @@ class CachedImage extends BaseEntity */ public function __construct(UploadedFile $image, $cacheFile) { - $this->originalId = (int)$image->getId(); + $this->originalId = (int) $image->getId(); $this->originalType = $image->getType(); $this->cacheFile = $cacheFile; } /** - * Returns the cache file + * Returns the cache file. * * @return string The cache file including path */ @@ -62,7 +63,7 @@ class CachedImage extends BaseEntity } /** - * Returns the original ID + * Returns the original ID. * * @return int */ @@ -72,7 +73,7 @@ class CachedImage extends BaseEntity } /** - * Returns the original type + * Returns the original type. * * @return string */ diff --git a/src/PartKeepr/ImageBundle/Entity/Image.php b/src/PartKeepr/ImageBundle/Entity/Image.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ImageBundle\Entity; use Doctrine\ORM\Mapping as ORM; @@ -12,11 +13,11 @@ use PartKeepr\UploadedFileBundle\Entity\UploadedFile; */ abstract class Image extends UploadedFile { - const IMAGE_ICLOGO = "iclogo"; - const IMAGE_TEMP = "temp"; - const IMAGE_PART = "part"; - const IMAGE_STORAGELOCATION = "storagelocation"; - const IMAGE_FOOTPRINT = "footprint"; + const IMAGE_ICLOGO = 'iclogo'; + const IMAGE_TEMP = 'temp'; + const IMAGE_PART = 'part'; + const IMAGE_STORAGELOCATION = 'storagelocation'; + const IMAGE_FOOTPRINT = 'footprint'; /** * Constructs a new image object. @@ -40,15 +41,15 @@ abstract class Image extends UploadedFile protected function setType($type) { switch ($type) { - case Image::IMAGE_ICLOGO: - case Image::IMAGE_TEMP: - case Image::IMAGE_PART: - case Image::IMAGE_FOOTPRINT: - case Image::IMAGE_STORAGELOCATION: + case self::IMAGE_ICLOGO: + case self::IMAGE_TEMP: + case self::IMAGE_PART: + case self::IMAGE_FOOTPRINT: + case self::IMAGE_STORAGELOCATION: parent::setType($type); break; default: throw new InvalidImageTypeException($type); } } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/ImageBundle/Entity/TempImage.php b/src/PartKeepr/ImageBundle/Entity/TempImage.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ImageBundle\Entity; use Doctrine\ORM\Mapping as ORM; @@ -15,4 +16,4 @@ class TempImage extends Image { parent::__construct(Image::IMAGE_TEMP); } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/ImageBundle/PartKeeprImageBundle.php b/src/PartKeepr/ImageBundle/PartKeeprImageBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ImageBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/ImageBundle/Response/ImageResponse.php b/src/PartKeepr/ImageBundle/Response/ImageResponse.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\ImageBundle\Response; +namespace PartKeepr\ImageBundle\Response; use Imagine\Gd\Imagine; use Imagine\Image\Box; @@ -10,13 +10,15 @@ use Symfony\Component\HttpFoundation\Response; class ImageResponse extends Response { /** - * Constructs a new ImageNotFoundResponse - * @param int $maxWidth - * @param int $maxHeight - * @param int $code + * Constructs a new ImageNotFoundResponse. + * + * @param int $maxWidth + * @param int $maxHeight + * @param int $code * @param string $message */ - public function __construct ($maxWidth, $maxHeight, $code, $message) { + public function __construct($maxWidth, $maxHeight, $code, $message) + { if ($maxWidth == 0) { $maxWidth = 300; } @@ -30,10 +32,10 @@ class ImageResponse extends Response $size = new Box(300, 300); $image = $imagine->create($size); - $black = $image->palette()->color("000"); + $black = $image->palette()->color('000'); - $path = realpath(__DIR__ . - "/../Resources/public/fonts/OpenSans-Regular.ttf" + $path = realpath(__DIR__. + '/../Resources/public/fonts/OpenSans-Regular.ttf' ); $font = $imagine->font($path, 24, $black); @@ -49,6 +51,6 @@ class ImageResponse extends Response $image->resize($box); - return parent::__construct($image->get("png"), $code, array("Content-Type" => "image/png")); + return parent::__construct($image->get('png'), $code, ['Content-Type' => 'image/png']); } } diff --git a/src/PartKeepr/ImageBundle/Response/TemporaryImageUploadResponse.php b/src/PartKeepr/ImageBundle/Response/TemporaryImageUploadResponse.php @@ -1,10 +1,12 @@ <?php + namespace PartKeepr\ImageBundle\Response; class TemporaryImageUploadResponse { /** * The success property. This is required for ExtJS. + * * @var bool */ public $success = true; @@ -15,13 +17,13 @@ class TemporaryImageUploadResponse public $image; /** - * Legacy response for ExtJS forms + * Legacy response for ExtJS forms. */ public $response; - public function __construct ($image) { + public function __construct($image) + { $this->image = $image; $this->response = $image; } - -}- \ No newline at end of file +} diff --git a/src/PartKeepr/ImageBundle/Services/ImageService.php b/src/PartKeepr/ImageBundle/Services/ImageService.php @@ -1,6 +1,5 @@ <?php - namespace PartKeepr\ImageBundle\Services; use Doctrine\ORM\EntityManager; @@ -21,29 +20,29 @@ class ImageService extends UploadedFileService } /** - * Invalidates any cached files + * Invalidates any cached files. * * @param UploadedFile $file The file to invalidate */ public function invalidate(UploadedFile $file) { /** - * @var $entityManager EntityManager + * @var EntityManager */ - $entityManager = $this->container->get("doctrine")->getManager(); + $entityManager = $this->container->get('doctrine')->getManager(); $queryBuilder = $entityManager->createQueryBuilder(); - $queryBuilder->select(array("c")) + $queryBuilder->select(['c']) ->from('PartKeepr\ImageBundle\Entity\CachedImage', 'c') - ->where("c.originalId = :id") - ->andWhere("c.originalType = :type") - ->setParameter("id", $file->getId()) - ->setParameter("type", $file->getType()); + ->where('c.originalId = :id') + ->andWhere('c.originalType = :type') + ->setParameter('id', $file->getId()) + ->setParameter('type', $file->getType()); $query = $queryBuilder->getQuery(); foreach ($query->getResult() as $file) { /** - * @var $file CachedImage + * @var CachedImage */ if (file_exists($file->getCacheFile())) { unlink($file->getCacheFile()); @@ -53,16 +52,18 @@ class ImageService extends UploadedFileService } /** - * Checks if the system can handle the given mime type as image. Currently hardcoded for GD + * Checks if the system can handle the given mime type as image. Currently hardcoded for GD. * * @param $mimeType The mime type to check - * @return boolean True if the system can display images of the given mimetype, false otherwise + * + * @return bool True if the system can display images of the given mimetype, false otherwise */ - public function canHandleMimetype ($mimeType) { + public function canHandleMimetype($mimeType) + { switch ($mimeType) { - case "image/jpeg": - case "image/png": - case "image/gif": + case 'image/jpeg': + case 'image/png': + case 'image/gif': return true; default: return false; diff --git a/src/PartKeepr/ImageBundle/Tests/ImageControllerTest.php b/src/PartKeepr/ImageBundle/Tests/ImageControllerTest.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\ImageBundle\Tests; +namespace PartKeepr\ImageBundle\Tests; use PartKeepr\CoreBundle\Tests\WebTestCase; use PartKeepr\ImageBundle\Entity\TempImage; @@ -8,12 +8,13 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; class ImageControllerTest extends WebTestCase { - public function testGetImage () { + public function testGetImage() + { $client = static::makeClient(true); - $file = __DIR__."/Fixtures/files/uploadtest.png"; + $file = __DIR__.'/Fixtures/files/uploadtest.png'; $originalFilename = 'uploadtest.png'; - $mimeType = "image/png"; + $mimeType = 'image/png'; $image = new UploadedFile( $file, @@ -25,37 +26,37 @@ class ImageControllerTest extends WebTestCase $client->request( 'POST', '/api/temp_images/upload', - array(), - array('userfile' => $image) + [], + ['userfile' => $image] ); $response = json_decode($client->getResponse()->getContent()); - $property = "@id"; + $property = '@id'; $imageId = $response->image->$property; - $uri = $imageId . "/getImage"; + $uri = $imageId.'/getImage'; $client->request( 'GET', $uri ); - $this->assertEquals("image/png", $client->getResponse()->headers->get("Content-Type")); + $this->assertEquals('image/png', $client->getResponse()->headers->get('Content-Type')); $imageSize = getimagesizefromstring($client->getResponse()->getContent()); $this->assertEquals(51, $imageSize[0]); $this->assertEquals(23, $imageSize[1]); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $image = $iriConverter->getItemFromIri($imageId); - /** + /* * @var $image TempImage */ - $this->getContainer()->get("partkeepr_image_service")->delete($image); + $this->getContainer()->get('partkeepr_image_service')->delete($image); $client->request( 'GET', @@ -63,6 +64,5 @@ class ImageControllerTest extends WebTestCase ); $this->assertEquals(404, $client->getResponse()->getStatusCode()); - } } diff --git a/src/PartKeepr/ManufacturerBundle/Controller/ManufacturerIcLogoController.php b/src/PartKeepr/ManufacturerBundle/Controller/ManufacturerIcLogoController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ManufacturerBundle\Controller; use PartKeepr\ImageBundle\Controller\ImageController; @@ -6,10 +7,10 @@ use PartKeepr\ImageBundle\Controller\ImageController; class ManufacturerIcLogoController extends ImageController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\ManufacturerBundle\\Entity\\ManufacturerICLogo"; + return 'PartKeepr\\ManufacturerBundle\\Entity\\ManufacturerICLogo'; } } diff --git a/src/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php b/src/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\ManufacturerBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** - * Represents a manufacturer + * Represents a manufacturer. * * @ORM\Entity * @TargetService(uri="/api/manufacturers") @@ -17,7 +18,8 @@ use Symfony\Component\Serializer\Annotation\Groups; class Manufacturer extends BaseEntity { /** - * The name of the manufacturer + * The name of the manufacturer. + * * @ORM\Column(type="string",unique=true) * @Groups({"default"}) * @@ -26,7 +28,8 @@ class Manufacturer extends BaseEntity private $name; /** - * The address of the manufacturer + * The address of the manufacturer. + * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) * @@ -35,7 +38,8 @@ class Manufacturer extends BaseEntity private $address; /** - * The URL + * The URL. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -44,7 +48,8 @@ class Manufacturer extends BaseEntity private $url; /** - * The email + * The email. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -53,7 +58,8 @@ class Manufacturer extends BaseEntity private $email; /** - * The comment + * The comment. + * * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) * @@ -62,7 +68,8 @@ class Manufacturer extends BaseEntity private $comment; /** - * The phone number + * The phone number. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -71,7 +78,8 @@ class Manufacturer extends BaseEntity private $phone; /** - * The fax number + * The fax number. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -80,7 +88,8 @@ class Manufacturer extends BaseEntity private $fax; /** - * All ic logos of this manufacturer + * All ic logos of this manufacturer. + * * @ORM\OneToMany(targetEntity="PartKeepr\ManufacturerBundle\Entity\ManufacturerICLogo",mappedBy="manufacturer",cascade={"persist", "remove"}, orphanRemoval=true) * * @UploadedFileCollection() @@ -89,7 +98,7 @@ class Manufacturer extends BaseEntity private $icLogos; /** - * Creates a new manufacturer instance + * Creates a new manufacturer instance. */ public function __construct() { @@ -97,7 +106,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the name + * Sets the name. * * @param string $name The name */ @@ -107,7 +116,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the name + * Returns the name. * * @return string The name */ @@ -117,7 +126,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the phone number + * Sets the phone number. * * @param string $phone The phone number */ @@ -127,7 +136,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the phone number + * Returns the phone number. * * @return string The phone number */ @@ -137,7 +146,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the fax number + * Sets the fax number. * * @param string $fax The fax number */ @@ -147,7 +156,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the fax number + * Returns the fax number. * * @return string The fax number */ @@ -157,7 +166,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the address + * Sets the address. * * @param string $address The address */ @@ -167,7 +176,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the address + * Returns the address. * * @return string The address */ @@ -177,7 +186,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the comment + * Sets the comment. * * @param string $comment The comment */ @@ -187,7 +196,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the comment + * Returns the comment. * * @return string The comment */ @@ -197,7 +206,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the email + * Sets the email. * * @param string $email The email */ @@ -207,7 +216,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the email + * Returns the email. * * @return string The email */ @@ -217,7 +226,7 @@ class Manufacturer extends BaseEntity } /** - * Sets the URL + * Sets the URL. * * @param string $url The URL */ @@ -227,7 +236,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the URL + * Returns the URL. * * @return string The url */ @@ -237,7 +246,7 @@ class Manufacturer extends BaseEntity } /** - * Returns the ic logos + * Returns the ic logos. * * @return ArrayCollection The array with all ic logos */ diff --git a/src/PartKeepr/ManufacturerBundle/Entity/ManufacturerICLogo.php b/src/PartKeepr/ManufacturerBundle/Entity/ManufacturerICLogo.php @@ -1,18 +1,20 @@ <?php + namespace PartKeepr\ManufacturerBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\ImageBundle\Entity\Image; /** - * Holds a manufacturer IC logo + * Holds a manufacturer IC logo. * * @ORM\Entity **/ class ManufacturerICLogo extends Image { /** - * The manufacturer object + * The manufacturer object. + * * @ORM\ManyToOne(targetEntity="PartKeepr\ManufacturerBundle\Entity\Manufacturer", inversedBy="icLogos") * @ORM\JoinColumn(name="manufacturer_id",referencedColumnName="id") * @@ -21,7 +23,7 @@ class ManufacturerICLogo extends Image private $manufacturer = null; /** - * Creates a new IC logo instance + * Creates a new IC logo instance. */ public function __construct() { @@ -29,7 +31,7 @@ class ManufacturerICLogo extends Image } /** - * Sets the manufacturer + * Sets the manufacturer. * * @param Manufacturer $manufacturer The manufacturer to set */ @@ -39,7 +41,7 @@ class ManufacturerICLogo extends Image } /** - * Returns the manufacturer + * Returns the manufacturer. * * @return Manufacturer the manufacturer */ @@ -47,4 +49,4 @@ class ManufacturerICLogo extends Image { return $this->manufacturer; } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/ManufacturerBundle/PartKeeprManufacturerBundle.php b/src/PartKeepr/ManufacturerBundle/PartKeeprManufacturerBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ManufacturerBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/ManufacturerBundle/Tests/DataFixtures/ManufacturerDataLoader.php b/src/PartKeepr/ManufacturerBundle/Tests/DataFixtures/ManufacturerDataLoader.php @@ -1,21 +1,21 @@ <?php + namespace PartKeepr\ManufacturerBundle\Tests\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use PartKeepr\ManufacturerBundle\Entity\Manufacturer; - class ManufacturerDataLoader extends AbstractFixture { public function load(ObjectManager $manager) { $manufacturer = new Manufacturer(); - $manufacturer->setName("TEST"); + $manufacturer->setName('TEST'); $manager->persist($manufacturer); $manager->flush(); - $this->addReference("manufacturer.first", $manufacturer); + $this->addReference('manufacturer.first', $manufacturer); } } diff --git a/src/PartKeepr/MimetypeIconsBundle/DependencyInjection/PartKeeprMimetypeIconsExtension.php b/src/PartKeepr/MimetypeIconsBundle/DependencyInjection/PartKeeprMimetypeIconsExtension.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\MimetypeIconsBundle\DependencyInjection; +use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; -use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader; class PartKeeprMimetypeIconsExtension extends Extension { /** - * {@inheritDoc} + * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { diff --git a/src/PartKeepr/MimetypeIconsBundle/Services/MimetypeIconService.php b/src/PartKeepr/MimetypeIconsBundle/Services/MimetypeIconService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\MimetypeIconsBundle\Services; use Symfony\Component\Config\FileLocator; @@ -18,7 +19,7 @@ class MimetypeIconService extends ContainerAware } /** - * Returns the file path to an image file which represents the passed mimetype + * Returns the file path to an image file which represents the passed mimetype. * * @param string $mimetype The mimetype * @@ -26,19 +27,18 @@ class MimetypeIconService extends ContainerAware */ public function getMimetypeIcon($mimetype) { - $file = str_replace("/", "-", $mimetype).".svg"; + $file = str_replace('/', '-', $mimetype).'.svg'; - $iconDirectory = $this->container->getParameter("partkeepr.directories.mimetype_icons"); + $iconDirectory = $this->container->getParameter('partkeepr.directories.mimetype_icons'); $fileLocator = new FileLocator($iconDirectory); try { $iconFile = $fileLocator->locate($file); } catch (\InvalidArgumentException $e) { - $file = "empty.svg"; + $file = 'empty.svg'; $iconFile = $fileLocator->locate($file); } return $iconFile; - } } diff --git a/src/PartKeepr/PartBundle/Action/AddStockAction.php b/src/PartKeepr/PartBundle/Action/AddStockAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -12,7 +13,7 @@ use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\Request; /** - * Adds stock to a given part + * Adds stock to a given part. */ class AddStockAction { @@ -47,11 +48,11 @@ class AddStockAction * Retrieves a collection of resources. * * @param Request $request The request - * @param int $id The ID of the part - * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable + * @param int $id The ID of the part * * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -59,22 +60,22 @@ class AddStockAction $part = $this->getItem($this->dataProvider, $resourceType, $id); - /** + /* * @var $part Part */ - $quantity = $request->request->get("quantity"); + $quantity = $request->request->get('quantity'); $user = $this->userService->getUser(); $stock = new StockEntry(); $stock->setUser($user); $stock->setStockLevel(intval($quantity)); - if ($request->request->has("price") && $request->request->get("price") !== null) { - $stock->setPrice(floatval($request->request->get("price"))); + if ($request->request->has('price') && $request->request->get('price') !== null) { + $stock->setPrice(floatval($request->request->get('price'))); } - if ($request->request->has("comment") && $request->request->get("comment") !== null) { - $stock->setComment($request->request->get("comment")); + if ($request->request->has('comment') && $request->request->get('comment') !== null) { + $stock->setComment($request->request->get('comment')); } $part->addStockLevel($stock); diff --git a/src/PartKeepr/PartBundle/Action/PartPutAction.php b/src/PartKeepr/PartBundle/Action/PartPutAction.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\PartBundle\Action; +namespace PartKeepr\PartBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; use Dunglas\ApiBundle\Api\ResourceInterface; @@ -37,31 +37,31 @@ class PartPutAction /** * Create a new item. * - * @param Request $request + * @param Request $request * @param string|int $id * - * @return mixed - * * @throws NotFoundHttpException * @throws RuntimeException * @throws UserProtectedException * @throws UserLimitReachedException + * + * @return mixed */ public function __invoke(Request $request, $id) { - /** - * @var $resourceType ResourceInterface + /** + * @var ResourceInterface */ list($resourceType, $format) = $this->extractAttributes($request); - /** + /* * Workaround to ensure stockLevels are not overwritten in a PUT request. * @see https://github.com/partkeepr/PartKeepr/issues/551 */ $data = json_decode($request->getContent(), true); - if (array_key_exists("stockLevels", $data)) { - unset($data["stockLevels"]); + if (array_key_exists('stockLevels', $data)) { + unset($data['stockLevels']); } $requestData = json_encode($data); diff --git a/src/PartKeepr/PartBundle/Action/PostAction.php b/src/PartKeepr/PartBundle/Action/PostAction.php @@ -1,6 +1,5 @@ <?php - namespace PartKeepr\PartBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -34,18 +33,18 @@ class PostAction } /** - * Injects the specific root node ID if "@local-tree-root" was specified + * Injects the specific root node ID if "@local-tree-root" was specified. * * @param Request $request * - * @return mixed - * * @throws RuntimeException * @throws PartLimitExceededException + * + * @return mixed */ public function __invoke(Request $request) { - /** + /* * @var $resourceType ResourceInterface */ if ($this->partService->checkPartLimit()) { @@ -60,6 +59,5 @@ class PostAction $format, $resourceType->getDenormalizationContext() ); - } } diff --git a/src/PartKeepr/PartBundle/Action/RemoveStockAction.php b/src/PartKeepr/PartBundle/Action/RemoveStockAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -12,7 +13,7 @@ use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\Request; /** - * Removes stock for a given part + * Removes stock for a given part. */ class RemoveStockAction { @@ -42,15 +43,16 @@ class RemoveStockAction $this->userService = $userService; $this->registry = $registry; } + /** * Retrieves a collection of resources. * * @param Request $request The request - * @param int $id The ID of the part - * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable + * @param int $id The ID of the part * * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -58,18 +60,18 @@ class RemoveStockAction $part = $this->getItem($this->dataProvider, $resourceType, $id); - /** + /* * @var $part Part */ - $quantity = $request->request->get("quantity"); + $quantity = $request->request->get('quantity'); $user = $this->userService->getUser(); $stock = new StockEntry(); $stock->setStockLevel(0 - intval($quantity)); $stock->setUser($user); - if ($request->request->has("comment") && $request->request->get("comment") !== null) { - $stock->setComment($request->request->get("comment")); + if ($request->request->has('comment') && $request->request->get('comment') !== null) { + $stock->setComment($request->request->get('comment')); } $part->addStockLevel($stock); diff --git a/src/PartKeepr/PartBundle/Action/SetDefaultUnitAction.php b/src/PartKeepr/PartBundle/Action/SetDefaultUnitAction.php @@ -1,9 +1,7 @@ <?php - namespace PartKeepr\PartBundle\Action; - use Dunglas\ApiBundle\Action\ActionUtilTrait; use Dunglas\ApiBundle\Exception\RuntimeException; use Dunglas\ApiBundle\Model\DataProviderInterface; @@ -25,7 +23,8 @@ class SetDefaultUnitAction */ private $dataProvider; - public function __construct (DataProviderInterface $dataProvider, PartMeasurementUnitService $partMeasurementUnitService) { + public function __construct(DataProviderInterface $dataProvider, PartMeasurementUnitService $partMeasurementUnitService) + { $this->dataProvider = $dataProvider; $this->partMeasurementUnitService = $partMeasurementUnitService; } @@ -34,18 +33,18 @@ class SetDefaultUnitAction * Retrieves a collection of resources. * * @param Request $request The request - * @param int $id The ID of the part - * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable + * @param int $id The ID of the part * * @throws RuntimeException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { list($resourceType) = $this->extractAttributes($request); /** - * @var PartMeasurementUnit $partMeasurementUnit + * @var PartMeasurementUnit */ $partMeasurementUnit = $this->getItem($this->dataProvider, $resourceType, $id); diff --git a/src/PartKeepr/PartBundle/Action/SetStockAction.php b/src/PartKeepr/PartBundle/Action/SetStockAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -12,7 +13,7 @@ use Symfony\Bridge\Doctrine\ManagerRegistry; use Symfony\Component\HttpFoundation\Request; /** - * Sets the stock for a given part + * Sets the stock for a given part. */ class SetStockAction { @@ -42,15 +43,16 @@ class SetStockAction $this->userService = $userService; $this->registry = $registry; } + /** * Retrieves a collection of resources. * * @param Request $request The request - * @param int $id The ID of the part - * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable + * @param int $id The ID of the part * * @throws RuntimeException|RootNodeNotFoundException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -58,23 +60,22 @@ class SetStockAction $part = $this->getItem($this->dataProvider, $resourceType, $id); - /** + /* * @var $part Part */ - $quantity = $request->request->get("quantity"); + $quantity = $request->request->get('quantity'); $user = $this->userService->getUser(); $oldQuantity = $part->getStockLevel(); $correctionQuantity = $quantity - $oldQuantity; if ($correctionQuantity != 0) { - $stock = new StockEntry(); $stock->setStockLevel($correctionQuantity); $stock->setUser($user); - if ($request->request->has("comment") && $request->request->get("comment") !== null) { - $stock->setComment($request->request->get("comment")); + if ($request->request->has('comment') && $request->request->get('comment') !== null) { + $stock->setComment($request->request->get('comment')); } $part->addStockLevel($stock); diff --git a/src/PartKeepr/PartBundle/Controller/PartAttachmentController.php b/src/PartKeepr/PartBundle/Controller/PartAttachmentController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Controller; use PartKeepr\ImageBundle\Controller\ImageController; @@ -6,10 +7,10 @@ use PartKeepr\ImageBundle\Controller\ImageController; class PartAttachmentController extends ImageController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\PartBundle\\Entity\\PartAttachment"; + return 'PartKeepr\\PartBundle\\Entity\\PartAttachment'; } } diff --git a/src/PartKeepr/PartBundle/Controller/PartController.php b/src/PartKeepr/PartBundle/Controller/PartController.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\PartBundle\Controller; +namespace PartKeepr\PartBundle\Controller; use Dunglas\ApiBundle\Api\IriConverter; use FOS\RestBundle\Controller\Annotations\View; @@ -15,35 +15,37 @@ class PartController extends FOSRestController /** * @Routing\Route("/api/parts/massRemoveStock", defaults={"method" = "get","_format" = "json"}) * @View() + * * @param Request $request + * * @throws \Exception Thrown if parameters are formatted incorrectly */ public function massRemoveStockAction(Request $request) { - $removals = json_decode($request->get("removals")); + $removals = json_decode($request->get('removals')); if (!is_array($removals)) { - throw new \Exception("removals parameter must be an array"); + throw new \Exception('removals parameter must be an array'); } /** - * @var IriConverter $iriConverter + * @var IriConverter */ - $iriConverter = $this->get("api.iri_converter"); + $iriConverter = $this->get('api.iri_converter'); - $user = $this->get("partkeepr.userservice")->getUser(); + $user = $this->get('partkeepr.userservice')->getUser(); foreach ($removals as $removal) { - if (!property_exists($removal, "part")) { - throw new \Exception("Each removal must have the part property defined"); + if (!property_exists($removal, 'part')) { + throw new \Exception('Each removal must have the part property defined'); } - if (!property_exists($removal, "amount")) { - throw new \Exception("Each removal must have the amount property defined"); + if (!property_exists($removal, 'amount')) { + throw new \Exception('Each removal must have the amount property defined'); } /** - * @var Part $part + * @var Part */ $part = $iriConverter->getItemFromIri($removal->part); @@ -51,13 +53,13 @@ class PartController extends FOSRestController $stock->setStockLevel(0 - intval($removal->amount)); $stock->setUser($user); - if (!property_exists($removal, "comment")) { + if (!property_exists($removal, 'comment')) { $stock->setComment($removal->comment); } $part->addStockLevel($stock); } - $this->get("doctrine.orm.entity_manager")->flush(); + $this->get('doctrine.orm.entity_manager')->flush(); } } diff --git a/src/PartKeepr/PartBundle/DataFixtures/CategoryDataLoader.php b/src/PartKeepr/PartBundle/DataFixtures/CategoryDataLoader.php @@ -1,15 +1,18 @@ <?php + namespace PartKeepr\PartBundle\DataFixtures; use PartKeepr\CategoryBundle\DataFixtures\AbstractCategoryDataLoader; class CategoryDataLoader extends AbstractCategoryDataLoader { - protected function getEntityClass () { + protected function getEntityClass() + { return 'PartKeepr\PartBundle\Entity\PartCategory'; } - protected function getReferencePrefix () { - return "partcategory"; + protected function getReferencePrefix() + { + return 'partcategory'; } } diff --git a/src/PartKeepr/PartBundle/DataFixtures/PartDataLoader.php b/src/PartKeepr/PartBundle/DataFixtures/PartDataLoader.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\PartBundle\DataFixtures; +namespace PartKeepr\PartBundle\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; @@ -12,25 +12,24 @@ class PartDataLoader extends AbstractFixture public function load(ObjectManager $manager) { $partUnit = new PartMeasurementUnit(); - $partUnit->setName("pieces"); - $partUnit->setShortName("pcs"); + $partUnit->setName('pieces'); + $partUnit->setShortName('pcs'); $partUnit->setDefault(true); $part = new Part(); - $part->setName("FOOBAR"); + $part->setName('FOOBAR'); $part->setPartUnit($partUnit); - $category = $this->getReference("partcategory.first"); - $storageLocation = $this->getReference("storagelocation.first"); + $category = $this->getReference('partcategory.first'); + $storageLocation = $this->getReference('storagelocation.first'); $part->setCategory($category); $part->setStorageLocation($storageLocation); - $part2 = new Part(); - $part2->setName("FOOBAR2"); + $part2->setName('FOOBAR2'); - $category = $this->getReference("partcategory.first"); - $storageLocation = $this->getReference("storagelocation.first"); + $category = $this->getReference('partcategory.first'); + $storageLocation = $this->getReference('storagelocation.first'); $part2->setCategory($category); $part2->setStorageLocation($storageLocation); @@ -42,7 +41,7 @@ class PartDataLoader extends AbstractFixture $manager->flush(); - $this->addReference("part.1", $part); - $this->addReference("part.2", $part2); + $this->addReference('part.1', $part); + $this->addReference('part.2', $part2); } } diff --git a/src/PartKeepr/PartBundle/DependencyInjection/PartKeeprPartExtension.php b/src/PartKeepr/PartBundle/DependencyInjection/PartKeeprPartExtension.php @@ -8,7 +8,7 @@ use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/PartBundle/Entity/Part.php b/src/PartKeepr/PartBundle/Entity/Part.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; @@ -26,7 +27,8 @@ use Symfony\Component\Serializer\Annotation\Groups; class Part extends BaseEntity { /** - * The category of the part + * The category of the part. + * * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\PartCategory") * @Groups({"default"}) * @@ -35,16 +37,18 @@ class Part extends BaseEntity private $category; /** - * The part's name + * The part's name. * * @ORM\Column * @Groups({"default"}) + * * @var string */ private $name; /** - * The part's short description + * The part's short description. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -53,7 +57,8 @@ class Part extends BaseEntity private $description; /** - * The footprint of this part + * The footprint of this part. + * * @ORM\ManyToOne(targetEntity="PartKeepr\FootprintBundle\Entity\Footprint") * @Groups({"default"}) * @@ -64,6 +69,7 @@ class Part extends BaseEntity /** * The unit in which the part's "amount" is calculated. This is necessary to count parts * in "pieces", "meters" or "grams". + * * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\PartMeasurementUnit", inversedBy="parts") * @Groups({"default"}) * @@ -72,7 +78,8 @@ class Part extends BaseEntity private $partUnit; /** - * Defines the storage location of this part + * Defines the storage location of this part. + * * @ORM\ManyToOne(targetEntity="PartKeepr\StorageLocationBundle\Entity\StorageLocation") * @Groups({"default"}) * @@ -81,7 +88,8 @@ class Part extends BaseEntity private $storageLocation; /** - * Holds the manufacturers which can manufacture this part + * Holds the manufacturers which can manufacture this part. + * * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\PartManufacturer",mappedBy="part",cascade={"persist", "remove"}, orphanRemoval=true) * @Groups({"default"}) * @@ -90,7 +98,8 @@ class Part extends BaseEntity private $manufacturers; /** - * Holds the distributors from where we can buy the part + * Holds the distributors from where we can buy the part. + * * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\PartDistributor",mappedBy="part",cascade={"persist", "remove"}, orphanRemoval=true) * @Groups({"default"}) * @@ -99,7 +108,8 @@ class Part extends BaseEntity private $distributors; /** - * Holds the part attachments + * Holds the part attachments. + * * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\PartAttachment", * mappedBy="part",cascade={"persist", "remove"}, orphanRemoval=true) * @Groups({"default"}) @@ -110,11 +120,12 @@ class Part extends BaseEntity private $attachments; /** - * The comment for this part + * The comment for this part. + * * @ORM\Column(type="text") * @Groups({"default"}) */ - private $comment = ""; + private $comment = ''; /** * The stock level. Note that this is a cached value, because it makes our summary queries easier. @@ -122,7 +133,8 @@ class Part extends BaseEntity * @todo It would be nice if we could get rid of that. * @ORM\Column(type="integer") * @Groups({"default"}) - * @var integer + * + * @var int */ private $stockLevel = 0; @@ -132,7 +144,8 @@ class Part extends BaseEntity * * @Groups({"default"}) * @ORM\Column(type="integer") - * @var integer + * + * @var int */ private $minStockLevel = 0; @@ -141,12 +154,14 @@ class Part extends BaseEntity * * @ORM\Column(type="decimal",precision=13,scale=4,nullable=false) * @Groups({"default"}) + * * @var float */ private $averagePrice = 0; /** - * The stock level history + * The stock level history. + * * @ORM\OneToMany(targetEntity="PartKeepr\StockBundle\Entity\StockEntry",mappedBy="part",cascade={"persist", "remove"}) * @Groups({"stock"}) * @@ -155,7 +170,8 @@ class Part extends BaseEntity private $stockLevels; /** - * The parameters for this part + * The parameters for this part. + * * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\PartParameter", * mappedBy="part",cascade={"persist", "remove"}, orphanRemoval=true) * @@ -164,7 +180,8 @@ class Part extends BaseEntity private $parameters; /** - * The part status for this part + * The part status for this part. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -173,16 +190,18 @@ class Part extends BaseEntity private $status; /** - * Defines if the part needs review + * Defines if the part needs review. + * * @ORM\Column(type="boolean") * @Groups({"default"}) * - * @var boolean + * @var bool */ private $needsReview; /** - * Defines the condition of the part + * Defines the condition of the part. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -191,7 +210,8 @@ class Part extends BaseEntity private $partCondition; /** - * The create date+time for this part + * The create date+time for this part. + * * @ORM\Column(type="datetime",nullable=true) * @Groups({"default"}) * @@ -201,12 +221,14 @@ class Part extends BaseEntity /** * @ORM\OneToMany(targetEntity="PartKeepr\ProjectBundle\Entity\ProjectPart", mappedBy="part") + * * @var ProjectPart[] **/ private $projectParts; /** - * The internal part number + * The internal part number. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -216,13 +238,15 @@ class Part extends BaseEntity /** * @ORM\Column(type="boolean",nullable=false) - * @var boolean + * + * @var bool */ private $removals = false; /** * @ORM\Column(type="boolean",nullable=false) - * @var boolean + * + * @var bool */ private $lowStock = false; @@ -239,7 +263,7 @@ class Part extends BaseEntity } /** - * Sets the create date for this part + * Sets the create date for this part. * * @param \DateTime $dateTime The create date+time */ @@ -249,7 +273,7 @@ class Part extends BaseEntity } /** - * @return boolean + * @return bool */ public function isLowStock() { @@ -257,7 +281,7 @@ class Part extends BaseEntity } /** - * @param boolean $lowStock + * @param bool $lowStock */ public function setLowStock($lowStock) { @@ -273,7 +297,7 @@ class Part extends BaseEntity } /** - * Returns the name of this part + * Returns the name of this part. * * @return string The part name */ @@ -283,7 +307,7 @@ class Part extends BaseEntity } /** - * Sets the name for this part + * Sets the name for this part. * * @param string $name The part's name */ @@ -293,7 +317,7 @@ class Part extends BaseEntity } /** - * Returns the internal part number for this part + * Returns the internal part number for this part. * * @return string the internal part number */ @@ -303,7 +327,7 @@ class Part extends BaseEntity } /** - * Sets the internal part number for this part + * Sets the internal part number for this part. * * @param string $partNumber */ @@ -313,7 +337,7 @@ class Part extends BaseEntity } /** - * Returns the short description of this part + * Returns the short description of this part. * * @return string The part description */ @@ -323,7 +347,7 @@ class Part extends BaseEntity } /** - * Sets the description for this part + * Sets the description for this part. * * @param string $description The part's short description */ @@ -333,7 +357,7 @@ class Part extends BaseEntity } /** - * Returns the part unit + * Returns the part unit. * * @param none * @@ -345,10 +369,9 @@ class Part extends BaseEntity } /** - * Sets the part unit + * Sets the part unit. * * @param PartMeasurementUnit $partUnit The part unit object to set - * */ public function setPartUnit(PartMeasurementUnit $partUnit) { @@ -356,9 +379,9 @@ class Part extends BaseEntity } /** - * Returns the review flag + * Returns the review flag. * - * @return boolean True if the part needs review, false otherwise + * @return bool True if the part needs review, false otherwise */ public function getNeedsReview() { @@ -366,9 +389,9 @@ class Part extends BaseEntity } /** - * Sets the review flag + * Sets the review flag. * - * @param boolean $bReview True if the part needs review, false otherwise + * @param bool $bReview True if the part needs review, false otherwise */ public function setNeedsReview($bReview) { @@ -376,7 +399,7 @@ class Part extends BaseEntity } /** - * Returns the condition of this part + * Returns the condition of this part. * * @return string The part condition */ @@ -386,7 +409,7 @@ class Part extends BaseEntity } /** - * Sets the condition for this part + * Sets the condition for this part. * * @param string $partCondition The part's condition */ @@ -396,7 +419,8 @@ class Part extends BaseEntity } /** - * Returns the category path + * Returns the category path. + * * @Groups({"default"}) * * @return string @@ -406,12 +430,12 @@ class Part extends BaseEntity if ($this->category !== null) { return $this->category->getCategoryPath(); } else { - return ""; + return ''; } } /** - * Retrieves the footprint + * Retrieves the footprint. */ public function getFootprint() { @@ -419,7 +443,7 @@ class Part extends BaseEntity } /** - * Sets the footprint for this part + * Sets the footprint for this part. * * @param \PartKeepr\FootprintBundle\Entity\Footprint $footprint The footprint to set */ @@ -429,7 +453,7 @@ class Part extends BaseEntity } /** - * Returns the comment for this part + * Returns the comment for this part. * * @return string The comment */ @@ -439,7 +463,7 @@ class Part extends BaseEntity } /** - * Sets the comment for this part + * Sets the comment for this part. * * @param string $comment The comment for this part */ @@ -449,7 +473,7 @@ class Part extends BaseEntity } /** - * Returns the distributors array + * Returns the distributors array. * * @return ArrayCollection the distributors */ @@ -459,7 +483,7 @@ class Part extends BaseEntity } /** - * Returns the part attachments array + * Returns the part attachments array. * * @return ArrayCollection the part attachments */ @@ -469,7 +493,7 @@ class Part extends BaseEntity } /** - * Returns the manufacturers array + * Returns the manufacturers array. * * @return ArrayCollection the manufacturers */ @@ -479,7 +503,7 @@ class Part extends BaseEntity } /** - * Returns the parameters assigned to this part + * Returns the parameters assigned to this part. * * @return array An array of PartParameter objects */ @@ -489,7 +513,7 @@ class Part extends BaseEntity } /** - * Returns the create date + * Returns the create date. * * @return \DateTime The create date+time */ @@ -522,8 +546,8 @@ class Part extends BaseEntity /** * Checks if the requirements for database persisting are given. * - * @throws CategoryNotAssignedException Thrown if no category is set - * @throws StorageLocationNotAssignedException Thrown if no storage location is set + * @throws CategoryNotAssignedException Thrown if no category is set + * @throws StorageLocationNotAssignedException Thrown if no storage location is set * * @ORM\PrePersist */ @@ -551,7 +575,7 @@ class Part extends BaseEntity } /** - * Returns the assigned category + * Returns the assigned category. * * @return PartCategory */ @@ -561,7 +585,7 @@ class Part extends BaseEntity } /** - * Sets the category for this part + * Sets the category for this part. * * @param PartCategory $category The category */ @@ -583,7 +607,7 @@ class Part extends BaseEntity } /** - * Returns the storage location for this part + * Returns the storage location for this part. * * @return \PartKeepr\StorageLocationBundle\Entity\StorageLocation $storageLocation The storage location */ @@ -601,7 +625,7 @@ class Part extends BaseEntity } /** - * Returns all stock entries + * Returns all stock entries. * * @return ArrayCollection */ @@ -611,7 +635,7 @@ class Part extends BaseEntity } /** - * Returns the minimum stock level + * Returns the minimum stock level. * * @return int */ @@ -621,7 +645,7 @@ class Part extends BaseEntity } /** - * Set the minimum stock level for this part + * Set the minimum stock level for this part. * * Only positive values are allowed. * @@ -644,11 +668,10 @@ class Part extends BaseEntity } else { $this->setLowStock(false); } - } /** - * Sets the average price for this part + * Sets the average price for this part. * * @param float $price The price to set */ @@ -658,7 +681,7 @@ class Part extends BaseEntity } /** - * Returns the acrage price + * Returns the acrage price. * * @return float */ @@ -668,7 +691,7 @@ class Part extends BaseEntity } /** - * Sets the storage location for this part + * Sets the storage location for this part. * * @param \PartKeepr\StorageLocationBundle\Entity\StorageLocation $storageLocation The storage location */ @@ -678,7 +701,6 @@ class Part extends BaseEntity } /** - * * Checks if the requirements for database persisting are given. * * For a list of exceptions, see @@ -693,7 +715,7 @@ class Part extends BaseEntity } /** - * Returns the stock level + * Returns the stock level. * * @return int The stock level */ @@ -703,7 +725,7 @@ class Part extends BaseEntity } /** - * Sets the stock level + * Sets the stock level. * * @param $stockLevel int The stock level to set */ @@ -713,7 +735,7 @@ class Part extends BaseEntity } /** - * Adds a new stock entry to this part + * Adds a new stock entry to this part. * * @param StockEntry $stockEntry */ @@ -724,7 +746,7 @@ class Part extends BaseEntity } /** - * Removes a stock entry from this part + * Removes a stock entry from this part. * * @param StockEntry $stockEntry */ @@ -735,7 +757,7 @@ class Part extends BaseEntity } /** - * Adds a Part Attachment + * Adds a Part Attachment. * * @param PartAttachment $partAttachment An attachment to add */ @@ -748,7 +770,7 @@ class Part extends BaseEntity } /** - * Removes a Part Attachment + * Removes a Part Attachment. * * @param PartAttachment $partAttachment An attachment to remove */ @@ -759,7 +781,7 @@ class Part extends BaseEntity } /** - * Adds a Part Manufacturer + * Adds a Part Manufacturer. * * @param PartManufacturer $partManufacturer A part manufacturer to add */ @@ -770,7 +792,7 @@ class Part extends BaseEntity } /** - * Removes a part manufacturer + * Removes a part manufacturer. * * @param PartManufacturer $partManufacturer A part manufacturer to remove */ @@ -781,7 +803,7 @@ class Part extends BaseEntity } /** - * Adds a Part Distributor + * Adds a Part Distributor. * * @param PartDistributor $partDistributor A part distributor to add */ @@ -792,7 +814,7 @@ class Part extends BaseEntity } /** - * Removes a part distributor + * Removes a part distributor. * * @param PartDistributor $partDistributor A part distributor to remove */ @@ -803,7 +825,7 @@ class Part extends BaseEntity } /** - * Returns the project parts + * Returns the project parts. * * @return ArrayCollection */ @@ -813,7 +835,8 @@ class Part extends BaseEntity } /** - * Returns the project names this part is used in + * Returns the project names this part is used in. + * * @Groups({"default"}) * * @return array @@ -834,38 +857,37 @@ class Part extends BaseEntity { $currentStock = 0; $avgPrice = 0; - + $totalPartStockPrice = 0; $lastPosEntryQuant = 0; $lastPosEntryPrice = 0; $negativeStock = 0; foreach ($this->getStockLevels() as $stockLevel) { - - $currentStock += $stockLevel->getStockLevel(); - - if ($currentStock <= 0) { - $avgPrice = 0; - $totalPartStockPrice = 0; - $negativeStock = $currentStock; - } else { - if ($stockLevel->getStockLevel() > 0) { - $lastPosEntryQuant = $stockLevel->getStockLevel(); - $lastPosEntryPrice = $stockLevel->getPrice(); - $totalPartStockPrice += $lastPosEntryPrice * ($lastPosEntryQuant + $negativeStock); - $avgPrice = $totalPartStockPrice / $currentStock; - } else { - if ($currentStock < $lastPosEntryQuant) { - $totalPartStockPrice = $currentStock * $lastPosEntryPrice; - $avgPrice = $totalPartStockPrice / $currentStock; - } else { - $totalPartStockPrice += $stockLevel->getStockLevel() * $avgPrice; - $avgPrice = $totalPartStockPrice / $currentStock; - } - $negativeStock = 0; - } + $currentStock += $stockLevel->getStockLevel(); + + if ($currentStock <= 0) { + $avgPrice = 0; + $totalPartStockPrice = 0; + $negativeStock = $currentStock; + } else { + if ($stockLevel->getStockLevel() > 0) { + $lastPosEntryQuant = $stockLevel->getStockLevel(); + $lastPosEntryPrice = $stockLevel->getPrice(); + $totalPartStockPrice += $lastPosEntryPrice * ($lastPosEntryQuant + $negativeStock); + $avgPrice = $totalPartStockPrice / $currentStock; + } else { + if ($currentStock < $lastPosEntryQuant) { + $totalPartStockPrice = $currentStock * $lastPosEntryPrice; + $avgPrice = $totalPartStockPrice / $currentStock; + } else { + $totalPartStockPrice += $stockLevel->getStockLevel() * $avgPrice; + $avgPrice = $totalPartStockPrice / $currentStock; + } + $negativeStock = 0; + } } - } + } $this->setStockLevel($currentStock); $this->setAveragePrice($avgPrice); diff --git a/src/PartKeepr/PartBundle/Entity/PartAttachment.php b/src/PartKeepr/PartBundle/Entity/PartAttachment.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; @@ -6,7 +7,7 @@ use PartKeepr\UploadedFileBundle\Entity\UploadedFile; use Symfony\Component\Serializer\Annotation\Groups; /** - * Holds a part attachment + * Holds a part attachment. * * @ORM\Entity **/ @@ -14,25 +15,27 @@ class PartAttachment extends UploadedFile { /** * Defines if the attachment is an image. + * * @ORM\Column(type="boolean",nullable=true) * @Groups({"default"}) * - * @var boolean + * @var bool */ private $isImage; /** - * Creates a new part attachment + * Creates a new part attachment. */ public function __construct() { parent::__construct(); - $this->setType("PartAttachment"); + $this->setType('PartAttachment'); $this->isImage = null; } /** - * The part object + * The part object. + * * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\Part", inversedBy="attachments") * * @var Part @@ -40,7 +43,7 @@ class PartAttachment extends UploadedFile private $part = null; /** - * Sets the part + * Sets the part. * * @param Part $part The part to set */ @@ -50,7 +53,7 @@ class PartAttachment extends UploadedFile } /** - * Returns the part + * Returns the part. * * @return Part the part */ @@ -62,7 +65,7 @@ class PartAttachment extends UploadedFile /** * Returns if the attachment is an image or not. * - * @return True if the attachment is an image, false otherwise + * @return true if the attachment is an image, false otherwise */ public function isImage() { @@ -70,10 +73,12 @@ class PartAttachment extends UploadedFile } /** - * Sets if the attachment is an image + * Sets if the attachment is an image. + * * @param $image */ - public function setImage($image) { + public function setImage($image) + { $this->isImage = $image; } } diff --git a/src/PartKeepr/PartBundle/Entity/PartCategory.php b/src/PartKeepr/PartBundle/Entity/PartCategory.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; @@ -16,7 +17,6 @@ use Symfony\Component\Serializer\Annotation\Groups; * The entity for our part categories * * @TargetService(uri="/api/part_categories") - * */ class PartCategory extends AbstractCategory implements CategoryPathInterface { @@ -37,12 +37,14 @@ class PartCategory extends AbstractCategory implements CategoryPathInterface /** * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) + * * @var string */ protected $categoryPath; /** - * Sets the parent category + * Sets the parent category. + * * @Groups({"default"}) * * @param AbstractCategory|null $parent @@ -53,7 +55,7 @@ class PartCategory extends AbstractCategory implements CategoryPathInterface } /** - * Returns the parent category + * Returns the parent category. * * @return mixed */ @@ -63,7 +65,7 @@ class PartCategory extends AbstractCategory implements CategoryPathInterface } /** - * Returns the children + * Returns the children. * * @return ArrayCollection */ @@ -73,7 +75,7 @@ class PartCategory extends AbstractCategory implements CategoryPathInterface } /** - * Returns the category path + * Returns the category path. * * @return string */ @@ -96,7 +98,7 @@ class PartCategory extends AbstractCategory implements CategoryPathInterface public function generateCategoryPath($pathSeparator) { if ($this->getParent() !== null) { - return $this->getParent()->generateCategoryPath($pathSeparator) . $pathSeparator . $this->getName(); + return $this->getParent()->generateCategoryPath($pathSeparator).$pathSeparator.$this->getName(); } else { return $this->getName(); } diff --git a/src/PartKeepr/PartBundle/Entity/PartDistributor.php b/src/PartKeepr/PartBundle/Entity/PartDistributor.php @@ -1,10 +1,11 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\DistributorBundle\Entity\Distributor; use PartKeepr\PartBundle\Exceptions\PackagingUnitOutOfRangeException; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -16,6 +17,7 @@ class PartDistributor extends BaseEntity { /** * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\Part", inversedBy="distributors") + * * @var Part */ private $part; @@ -27,7 +29,8 @@ class PartDistributor extends BaseEntity private $distributor; /** - * The order number for the part and distributor + * The order number for the part and distributor. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) * @@ -41,7 +44,8 @@ class PartDistributor extends BaseEntity * * @ORM\Column(type="integer") * @Groups({"default"}) - * @var integer + * + * @var int */ private $packagingUnit; @@ -51,14 +55,17 @@ class PartDistributor extends BaseEntity * * @ORM\Column(type="decimal",precision=13,scale=4,nullable=true) * @Groups({"default"}) + * * @var float */ private $price; /** * The distributor's SKU (stock keeping unit) for the part. Used with barcodes. + * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) + * * @var string */ private $sku; @@ -95,7 +102,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the packaging unit + * Returns the packaging unit. * * @return int The packaging unit */ @@ -105,7 +112,7 @@ class PartDistributor extends BaseEntity } /** - * Sets the part + * Sets the part. * * @param Part $part The part */ @@ -115,7 +122,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the part + * Returns the part. * * @return Part The part */ @@ -125,7 +132,7 @@ class PartDistributor extends BaseEntity } /** - * Sets the distributor + * Sets the distributor. * * @param \PartKeepr\DistributorBundle\Entity\Distributor $distributor The distributor */ @@ -135,7 +142,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the distributor + * Returns the distributor. * * @return Distributor The distributor */ @@ -145,7 +152,7 @@ class PartDistributor extends BaseEntity } /** - * Sets the order number + * Sets the order number. * * @param string $orderNumber The order number */ @@ -155,7 +162,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the order number + * Returns the order number. * * @return string The order number */ @@ -165,7 +172,7 @@ class PartDistributor extends BaseEntity } /** - * Sets the price + * Sets the price. * * @param float $price */ @@ -175,7 +182,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the price + * Returns the price. */ public function getPrice() { @@ -183,7 +190,7 @@ class PartDistributor extends BaseEntity } /** - * Sets the SKU (stock keeping unit) + * Sets the SKU (stock keeping unit). * * @param string $sku The SKU */ @@ -193,7 +200,7 @@ class PartDistributor extends BaseEntity } /** - * Returns the SKU (stock keeping unit) + * Returns the SKU (stock keeping unit). * * @return string The SKU */ diff --git a/src/PartKeepr/PartBundle/Entity/PartImage.php b/src/PartKeepr/PartBundle/Entity/PartImage.php @@ -1,18 +1,20 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\ImageBundle\Entity\Image; /** - * Holds a part image + * Holds a part image. * * @ORM\Entity **/ class PartImage extends Image { /** - * The part object + * The part object. + * * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\Part", inversedBy="images") * * @var Part @@ -20,7 +22,7 @@ class PartImage extends Image private $part = null; /** - * Creates a new part image instance + * Creates a new part image instance. */ public function __construct() { @@ -28,7 +30,7 @@ class PartImage extends Image } /** - * Sets the part + * Sets the part. * * @param Part $part The part to set */ @@ -38,7 +40,7 @@ class PartImage extends Image } /** - * Returns the part + * Returns the part. * * @return Part the part */ diff --git a/src/PartKeepr/PartBundle/Entity/PartManufacturer.php b/src/PartKeepr/PartBundle/Entity/PartManufacturer.php @@ -1,9 +1,10 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\ManufacturerBundle\Entity\Manufacturer; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\ManufacturerBundle\Entity\Manufacturer; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -13,6 +14,7 @@ class PartManufacturer extends BaseEntity { /** * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\Part",inversedBy="manufacturers") + * * @var Part */ private $part; @@ -24,16 +26,17 @@ class PartManufacturer extends BaseEntity private $manufacturer; /** - * The part number + * The part number. * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) + * * @var string */ private $partNumber; /** - * Sets the part which belongs to this manufacturer entry + * Sets the part which belongs to this manufacturer entry. * * @param Part $part */ @@ -43,7 +46,7 @@ class PartManufacturer extends BaseEntity } /** - * Returns the part which belongs to this manufacturer entry + * Returns the part which belongs to this manufacturer entry. */ public function getPart() { @@ -51,7 +54,7 @@ class PartManufacturer extends BaseEntity } /** - * Sets the manufacturer which belongs to this entry + * Sets the manufacturer which belongs to this entry. * * @param Manufacturer $manufacturer */ @@ -61,7 +64,7 @@ class PartManufacturer extends BaseEntity } /** - * Returns the manufacturer which belongs to this part + * Returns the manufacturer which belongs to this part. */ public function getManufacturer() { @@ -69,7 +72,7 @@ class PartManufacturer extends BaseEntity } /** - * Sets the manufacturer-specific part number + * Sets the manufacturer-specific part number. * * @param string $partNumber */ @@ -79,7 +82,7 @@ class PartManufacturer extends BaseEntity } /** - * Returns the manufacturer-specific part number + * Returns the manufacturer-specific part number. * * @return string The part number */ diff --git a/src/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php b/src/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php @@ -1,10 +1,11 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; @@ -15,119 +16,137 @@ use Symfony\Component\Validator\Constraints as Assert; * @ORM\Table(name="PartUnit") * @TargetService(uri="/api/part_measurement_units") **/ -class PartMeasurementUnit extends BaseEntity { - /** - * Defines the name of the unit - * - * @ORM\Column(type="string") - * @Groups({"default"}) - * - * @Assert\Type(type="string") - * @Assert\NotBlank(message="partMeasurementUnit.name.not_blank") - * - * @var string - */ - private $name; - - /** - * Defines the short name of the unit - * - * @ORM\Column(type="string") - * @Groups({"default"}) - * - * @Assert\Type(type="string") - * @Assert\NotBlank(message="partMeasurementUnit.shortName.not_blank") - * - * @var string - */ - private $shortName; - - /** - * Defines if the unit is default or not. Note that this property may not be set directly. - * - * @ORM\Column(type="boolean", name="is_default") - * @Groups({"default"}) - * - * @var boolean - */ - private $default; - - /** - * The parts used by this PartMeasurementUnit - * - * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\Part",mappedBy="partUnit") - */ - private $parts; - - - /** - * Creates a new part unit. - * - * Sets the default to false. - */ - public function __construct () { - $this->parts = new ArrayCollection(); - $this->setDefault(false); - } - - /** - * Sets the name for this unit - * @param string $name The name for this unit - */ - public function setName ($name) { - $this->name = $name; - } - - /** - * Returns the name for this unit - * @param none - * @return string The name for this unit - */ - public function getName () { - return $this->name; - } - - /** - * Sets the short name for this unit. - * - * Short names are used for list views (e.g. if your unit name is "metres", your short name could be "m") - * @param string $shortName The short name - */ - public function setShortName ($shortName) { - $this->shortName = $shortName; - } - - /** - * Returns the short name for this unit - * @param none - * @return string The short name for this unit - */ - public function getShortName () { - return $this->shortName; - } - - /** - * Defines if the unit is default or not. - * @param boolean $default True if the unit is default, false otherwise - */ - public function setDefault ($default) { - $this->default = (bool)$default; - } - - /** - * Returns if the unit is default or not - * @param none - * @return boolean True if the unit is default, false for not - */ - public function isDefault () { - return $this->default; - } +class PartMeasurementUnit extends BaseEntity +{ + /** + * Defines the name of the unit. + * + * @ORM\Column(type="string") + * @Groups({"default"}) + * + * @Assert\Type(type="string") + * @Assert\NotBlank(message="partMeasurementUnit.name.not_blank") + * + * @var string + */ + private $name; + + /** + * Defines the short name of the unit. + * + * @ORM\Column(type="string") + * @Groups({"default"}) + * + * @Assert\Type(type="string") + * @Assert\NotBlank(message="partMeasurementUnit.shortName.not_blank") + * + * @var string + */ + private $shortName; + + /** + * Defines if the unit is default or not. Note that this property may not be set directly. + * + * @ORM\Column(type="boolean", name="is_default") + * @Groups({"default"}) + * + * @var bool + */ + private $default; + + /** + * The parts used by this PartMeasurementUnit. + * + * @ORM\OneToMany(targetEntity="PartKeepr\PartBundle\Entity\Part",mappedBy="partUnit") + */ + private $parts; + + /** + * Creates a new part unit. + * + * Sets the default to false. + */ + public function __construct() + { + $this->parts = new ArrayCollection(); + $this->setDefault(false); + } + + /** + * Sets the name for this unit. + * + * @param string $name The name for this unit + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * Returns the name for this unit. + * + * @param none + * + * @return string The name for this unit + */ + public function getName() + { + return $this->name; + } + + /** + * Sets the short name for this unit. + * + * Short names are used for list views (e.g. if your unit name is "metres", your short name could be "m") + * + * @param string $shortName The short name + */ + public function setShortName($shortName) + { + $this->shortName = $shortName; + } + + /** + * Returns the short name for this unit. + * + * @param none + * + * @return string The short name for this unit + */ + public function getShortName() + { + return $this->shortName; + } + + /** + * Defines if the unit is default or not. + * + * @param bool $default True if the unit is default, false otherwise + */ + public function setDefault($default) + { + $this->default = (bool) $default; + } + + /** + * Returns if the unit is default or not. + * + * @param none + * + * @return bool True if the unit is default, false for not + */ + public function isDefault() + { + return $this->default; + } - /** - * Returns the parts for this PartUnit - * @return ArrayCollection - */ - public function getParts () { - return $this->parts; - } + /** + * Returns the parts for this PartUnit. + * + * @return ArrayCollection + */ + public function getParts() + { + return $this->parts; + } } diff --git a/src/PartKeepr/PartBundle/Entity/PartParameter.php b/src/PartKeepr/PartBundle/Entity/PartParameter.php @@ -1,11 +1,11 @@ <?php + namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\SiPrefixBundle\Entity\SiPrefix; use PartKeepr\UnitBundle\Entity\Unit; - /** * This object represents a parameter. Each parameter can have an unit (defined by the class "Unit") associated with * a numeric value. @@ -17,7 +17,8 @@ class PartParameter /** * @ORM\Id @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") - * @var integer + * + * @var int */ private $id; @@ -30,7 +31,8 @@ class PartParameter private $part; /** - * The name of the parameter (e.g. Resistance, Voltage) + * The name of the parameter (e.g. Resistance, Voltage). + * * @ORM\Column(type="string") * * @var string @@ -38,7 +40,8 @@ class PartParameter private $name; /** - * A description for this parameter + * A description for this parameter. + * * @ORM\Column(type="string") * * @var string @@ -49,6 +52,7 @@ class PartParameter * The unit for this type. May be null. * * @ORM\ManyToOne(targetEntity="PartKeepr\UnitBundle\Entity\Unit") + * * @var \PartKeepr\UnitBundle\Entity\Unit */ private $unit; @@ -58,6 +62,7 @@ class PartParameter * * Example: If you have 10µ, the value field will contain "10", the prefix object is linked to the SiPrefix * representing "µ" and the rawValue field will contain 0.000001 + * * @ORM\Column(type="float") * * @var float @@ -65,7 +70,8 @@ class PartParameter private $value; /** - * The SiPrefix of the unit + * The SiPrefix of the unit. + * * @ORM\ManyToOne(targetEntity="PartKeepr\SiPrefixBundle\Entity\SiPrefix") * * @var object @@ -74,6 +80,7 @@ class PartParameter /** * The raw value of the unit. + * * @ORM\Column(type="float") * * @var float @@ -81,7 +88,7 @@ class PartParameter private $rawValue; /** - * Sets the name for this parameter + * Sets the name for this parameter. * * @param string $name The name */ @@ -91,7 +98,7 @@ class PartParameter } /** - * Returns the name for this parameter + * Returns the name for this parameter. * * @return string The name for this parameter */ @@ -101,7 +108,7 @@ class PartParameter } /** - * Sets the description for this parameter + * Sets the description for this parameter. * * @param string $description The description */ @@ -111,7 +118,7 @@ class PartParameter } /** - * Returns the description + * Returns the description. * * @return string The description */ @@ -121,7 +128,7 @@ class PartParameter } /** - * Sets the unit + * Sets the unit. * * @param \PartKeepr\UnitBundle\Entity\Unit $unit The unit to set */ @@ -131,7 +138,7 @@ class PartParameter } /** - * Returns the unit + * Returns the unit. * * @return \PartKeepr\UnitBundle\Entity\Unit the unit */ @@ -141,7 +148,7 @@ class PartParameter } /** - * Sets the part + * Sets the part. * * @param Part $part The part to set */ @@ -151,7 +158,7 @@ class PartParameter } /** - * Returns the part + * Returns the part. * * @return \PartKeepr\PartBundle\Entity\Part the part */ @@ -161,7 +168,7 @@ class PartParameter } /** - * Sets the value + * Sets the value. * * @param float $value The value to set */ @@ -173,7 +180,7 @@ class PartParameter } /** - * Returns the value + * Returns the value. * * @return float The value */ @@ -183,7 +190,7 @@ class PartParameter } /** - * Sets the si prefix for this parameter + * Sets the si prefix for this parameter. * * @param \PartKeepr\SiPrefixBundle\Entity\SiPrefix $prefix The prefix to set, or null */ @@ -195,7 +202,7 @@ class PartParameter } /** - * Returns the si prefix for this parameter + * Returns the si prefix for this parameter. * * @return \PartKeepr\SiPrefixBundle\Entity\SiPrefix the si prefix or null */ diff --git a/src/PartKeepr/PartBundle/Exceptions/CategoryNotAssignedException.php b/src/PartKeepr/PartBundle/Exceptions/CategoryNotAssignedException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\PartBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * This exception is thrown when a part hasn't got a category assigned + * This exception is thrown when a part hasn't got a category assigned. */ class CategoryNotAssignedException extends TranslatableException { public function getMessageKey() { - return "The part has no category assigned"; + return 'The part has no category assigned'; } } diff --git a/src/PartKeepr/PartBundle/Exceptions/MinStockLevelOutOfRangeException.php b/src/PartKeepr/PartBundle/Exceptions/MinStockLevelOutOfRangeException.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; @@ -7,6 +8,6 @@ class MinStockLevelOutOfRangeException extends TranslatableException { public function getMessageKey() { - return "Minimum Stock Level is out of range. The minimum stock level must be 0 or higher"; + return 'Minimum Stock Level is out of range. The minimum stock level must be 0 or higher'; } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/PartBundle/Exceptions/PackagingUnitOutOfRangeException.php b/src/PartKeepr/PartBundle/Exceptions/PackagingUnitOutOfRangeException.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; @@ -7,6 +8,6 @@ class PackagingUnitOutOfRangeException extends TranslatableException { public function getMessageKey() { - return "Packaging Unit is out of range. It must be 1 or higher."; + return 'Packaging Unit is out of range. It must be 1 or higher.'; } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/PartBundle/Exceptions/PartLimitExceededException.php b/src/PartKeepr/PartBundle/Exceptions/PartLimitExceededException.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\PartBundle\Exceptions; +namespace PartKeepr\PartBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; @@ -8,6 +8,6 @@ class PartLimitExceededException extends TranslatableException { public function getMessageKey() { - return "The maximum number of parts is reached"; + return 'The maximum number of parts is reached'; } } diff --git a/src/PartKeepr/PartBundle/Exceptions/StorageLocationNotAssignedException.php b/src/PartKeepr/PartBundle/Exceptions/StorageLocationNotAssignedException.php @@ -1,15 +1,16 @@ <?php + namespace PartKeepr\PartBundle\Exceptions; use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** - * This exception is thrown when a part hasn't got a storage location assigned + * This exception is thrown when a part hasn't got a storage location assigned. */ class StorageLocationNotAssignedException extends TranslatableException { public function getMessageKey() { - return "The part has no storage location assigned"; + return 'The part has no storage location assigned'; } } diff --git a/src/PartKeepr/PartBundle/Listeners/CategoryPathListener.php b/src/PartKeepr/PartBundle/Listeners/CategoryPathListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Listeners; use Doctrine\ORM\EntityManager; @@ -9,7 +10,8 @@ use Symfony\Component\DependencyInjection\ContainerAware; class CategoryPathListener extends ContainerAware { - public function __construct (Container $container) { + public function __construct(Container $container) + { $this->setContainer($container); } @@ -45,7 +47,7 @@ class CategoryPathListener extends ContainerAware public function updateCategoryPaths(PartCategory $partCategory, OnFlushEventArgs $eventArgs) { $entityManager = $eventArgs->getEntityManager(); - $pathSeparator = $this->container->getParameter("partkeepr.category.path_separator"); + $pathSeparator = $this->container->getParameter('partkeepr.category.path_separator'); $partCategory->setCategoryPath($partCategory->generateCategoryPath($pathSeparator)); diff --git a/src/PartKeepr/PartBundle/Listeners/ImageAttachmentListener.php b/src/PartKeepr/PartBundle/Listeners/ImageAttachmentListener.php @@ -1,5 +1,7 @@ <?php + namespace PartKeepr\PartBundle\Listeners; + use Doctrine\ORM\Event\LifecycleEventArgs; use PartKeepr\ImageBundle\Services\ImageService; use PartKeepr\PartBundle\Entity\PartAttachment; @@ -8,13 +10,16 @@ class ImageAttachmentListener { private $imageService; - public function __construct (ImageService $imageService) { + public function __construct(ImageService $imageService) + { $this->imageService = $imageService; } - public function postLoad(LifecycleEventArgs $event) { + + public function postLoad(LifecycleEventArgs $event) + { if ($event->getEntity() instanceof PartAttachment) { /** - * @var $entity PartAttachment + * @var PartAttachment */ $entity = $event->getEntity(); diff --git a/src/PartKeepr/PartBundle/Listeners/StockLevelListener.php b/src/PartKeepr/PartBundle/Listeners/StockLevelListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Listeners; use Doctrine\ORM\Event\OnFlushEventArgs; @@ -9,7 +10,7 @@ use Symfony\Component\DependencyInjection\ContainerAware; class StockLevelListener extends ContainerAware { /** - * Recomputes the stock level for each part + * Recomputes the stock level for each part. * * @param OnFlushEventArgs $eventArgs The event arguments as given by Doctrine */ @@ -18,7 +19,7 @@ class StockLevelListener extends ContainerAware $entityManager = $eventArgs->getEntityManager(); $uow = $entityManager->getUnitOfWork(); - $parts = array(); + $parts = []; foreach ($uow->getScheduledEntityInsertions() as $updated) { if ($updated instanceof StockEntry) { @@ -44,7 +45,7 @@ class StockLevelListener extends ContainerAware } /** - * Updates the stock level for a specific part + * Updates the stock level for a specific part. * * @param Part $part The part to update * @param OnFlushEventArgs $eventArgs The event arguments diff --git a/src/PartKeepr/PartBundle/Services/PartMeasurementUnitService.php b/src/PartKeepr/PartBundle/Services/PartMeasurementUnitService.php @@ -1,9 +1,7 @@ <?php - namespace PartKeepr\PartBundle\Services; - use Doctrine\ORM\EntityManager; use PartKeepr\PartBundle\Entity\PartMeasurementUnit; @@ -11,19 +9,21 @@ class PartMeasurementUnitService { private $entityManager; - public function __construct (EntityManager $entityManager) { + public function __construct(EntityManager $entityManager) + { $this->entityManager = $entityManager; } - public function setDefault (PartMeasurementUnit $partMeasurementUnit) { + public function setDefault(PartMeasurementUnit $partMeasurementUnit) + { $this->entityManager->beginTransaction(); $dql = 'UPDATE PartKeepr\PartBundle\Entity\PartMeasurementUnit pu SET pu.default = :default WHERE pu.id = :id'; $this->entityManager->createQuery($dql) - ->setParameter("id", $partMeasurementUnit->getId()) + ->setParameter('id', $partMeasurementUnit->getId()) ->setParameter( - "default", + 'default', true, \PDO::PARAM_BOOL )->execute(); @@ -31,9 +31,9 @@ class PartMeasurementUnitService $dql = 'UPDATE PartKeepr\PartBundle\Entity\PartMeasurementUnit pu SET pu.default = :default WHERE pu.id != :id'; $this->entityManager->createQuery($dql) - ->setParameter("id", $partMeasurementUnit->getId()) + ->setParameter('id', $partMeasurementUnit->getId()) ->setParameter( - "default", + 'default', false, \PDO::PARAM_BOOL )->execute(); diff --git a/src/PartKeepr/PartBundle/Services/PartService.php b/src/PartKeepr/PartBundle/Services/PartService.php @@ -1,15 +1,13 @@ <?php - namespace PartKeepr\PartBundle\Services; - use Doctrine\ORM\EntityManager; class PartService { /** - * The maximum number of parts allowed + * The maximum number of parts allowed. * * @var int|bool */ @@ -25,23 +23,25 @@ class PartService $partLimit = false ) { $this->entityManager = $entityManager; - $this->partLimit = $partLimit; + $this->partLimit = $partLimit; } /** - * Returns the number of parts present in the system + * Returns the number of parts present in the system. + * * @return mixed */ public function getPartCount() { - $dql = "SELECT COUNT(p) FROM PartKeepr\\PartBundle\\Entity\\Part p"; + $dql = 'SELECT COUNT(p) FROM PartKeepr\\PartBundle\\Entity\\Part p'; $query = $this->entityManager->createQuery($dql); return $query->getSingleScalarResult(); } /** - * Checks if the amount of parts is exceeded + * Checks if the amount of parts is exceeded. + * * @return bool */ public function checkPartLimit() diff --git a/src/PartKeepr/PartBundle/Tests/CategoryCreateTest.php b/src/PartKeepr/PartBundle/Tests/CategoryCreateTest.php @@ -1,12 +1,11 @@ <?php -namespace PartKeepr\PartBundle\Tests; +namespace PartKeepr\PartBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractCategoryCreateTest; class CategoryCreateTest extends AbstractCategoryCreateTest { - public function getResourceClass() { return 'PartKeepr\PartBundle\Entity\PartCategory'; @@ -19,6 +18,6 @@ class CategoryCreateTest extends AbstractCategoryCreateTest public function getReferencePrefix() { - return "partcategory"; + return 'partcategory'; } } diff --git a/src/PartKeepr/PartBundle/Tests/Issues/DistributorAndManufacturerSearchTest.php b/src/PartKeepr/PartBundle/Tests/Issues/DistributorAndManufacturerSearchTest.php @@ -1,6 +1,5 @@ <?php - namespace PartKeepr\PartBundle\Tests\Issues; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -12,13 +11,13 @@ use PartKeepr\PartBundle\Entity\PartDistributor; use PartKeepr\PartBundle\Entity\PartManufacturer; /** - * Class DistributorAndManufacturerSearchTest + * Class DistributorAndManufacturerSearchTest. * * Unit test against issue #647 (Filters for Distributor and Manufacturer don't return any results) */ class DistributorAndManufacturerSearchTest extends WebTestCase { - /** + /** * @var ProxyReferenceRepository */ protected $fixtures; @@ -26,7 +25,7 @@ class DistributorAndManufacturerSearchTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\StorageLocationBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\StorageLocationBundle\DataFixtures\StorageLocationLoader', 'PartKeepr\PartBundle\DataFixtures\CategoryDataLoader', @@ -34,86 +33,88 @@ class DistributorAndManufacturerSearchTest extends WebTestCase 'PartKeepr\AuthBundle\DataFixtures\LoadUserData', 'PartKeepr\ManufacturerBundle\Tests\DataFixtures\ManufacturerDataLoader', 'PartKeepr\DistributorBundle\Tests\DataFixtures\DistributorDataLoader', - ) + ] )->getReferenceRepository(); } - public function testManufacturerFilter () { + public function testManufacturerFilter() + { /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); + $part = $this->fixtures->getReference('part.1'); /** - * @var $manufacturer Manufacturer + * @var Manufacturer */ - $manufacturer = $this->fixtures->getReference("manufacturer.first"); + $manufacturer = $this->fixtures->getReference('manufacturer.first'); $partManufacturer = new PartManufacturer(); $partManufacturer->setManufacturer($manufacturer); - $partManufacturer->setPartNumber("1"); + $partManufacturer->setPartNumber('1'); $part->addManufacturer($partManufacturer); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush(); - $filter = array( - "property" => "manufacturers.manufacturer", - "operator" => "=", - "value" => $this->getContainer()->get("api.iri_converter")->getIriFromItem($manufacturer) - ); + $filter = [ + 'property' => 'manufacturers.manufacturer', + 'operator' => '=', + 'value' => $this->getContainer()->get('api.iri_converter')->getIriFromItem($manufacturer), + ]; - $filters = array($filter); + $filters = [$filter]; $client = static::makeClient(true); - $partResource = $this->getContainer()->get("resource.part"); - $iri = $this->getContainer()->get("api.iri_converter")->getIriFromResource($partResource); + $partResource = $this->getContainer()->get('resource.part'); + $iri = $this->getContainer()->get('api.iri_converter')->getIriFromResource($partResource); - $client->request("GET", $iri, array("filter" => json_encode($filters) )); + $client->request('GET', $iri, ['filter' => json_encode($filters)]); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $data = json_decode($client->getResponse()->getContent()); - $this->assertEquals(1, $data->{"hydra:totalItems"}); + $this->assertEquals(1, $data->{'hydra:totalItems'}); } - public function testDistributorFilter () { + public function testDistributorFilter() + { /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); + $part = $this->fixtures->getReference('part.1'); /** - * @var $distributor Distributor + * @var Distributor */ - $distributor = $this->fixtures->getReference("distributor.first"); + $distributor = $this->fixtures->getReference('distributor.first'); $partDistributor = new PartDistributor(); $partDistributor->setDistributor($distributor); $part->addDistributor($partDistributor); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush(); - $filter = array( - "property" => "distributors.distributor", - "operator" => "=", - "value" => $this->getContainer()->get("api.iri_converter")->getIriFromItem($distributor) - ); + $filter = [ + 'property' => 'distributors.distributor', + 'operator' => '=', + 'value' => $this->getContainer()->get('api.iri_converter')->getIriFromItem($distributor), + ]; - $filters = array($filter); + $filters = [$filter]; $client = static::makeClient(true); - $partResource = $this->getContainer()->get("resource.part"); - $iri = $this->getContainer()->get("api.iri_converter")->getIriFromResource($partResource); + $partResource = $this->getContainer()->get('resource.part'); + $iri = $this->getContainer()->get('api.iri_converter')->getIriFromResource($partResource); - $client->request("GET", $iri, array("filter" => json_encode($filters) )); + $client->request('GET', $iri, ['filter' => json_encode($filters)]); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $data = json_decode($client->getResponse()->getContent()); - $this->assertEquals(1, $data->{"hydra:totalItems"}); + $this->assertEquals(1, $data->{'hydra:totalItems'}); } } diff --git a/src/PartKeepr/PartBundle/Tests/Issues/StockHistoryLostTest.php b/src/PartKeepr/PartBundle/Tests/Issues/StockHistoryLostTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Tests\Issues; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -7,7 +8,7 @@ use PartKeepr\PartBundle\Entity\Part; use PartKeepr\StockBundle\Entity\StockEntry; /** - * Class StockHistoryLostTest + * Class StockHistoryLostTest. * * Unit test against issue #551 (stock history gets removed after saving part) */ @@ -21,7 +22,7 @@ class StockHistoryLostTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\StorageLocationBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\StorageLocationBundle\DataFixtures\StorageLocationLoader', 'PartKeepr\PartBundle\DataFixtures\CategoryDataLoader', @@ -29,45 +30,46 @@ class StockHistoryLostTest extends WebTestCase 'PartKeepr\AuthBundle\DataFixtures\LoadUserData', 'PartKeepr\ManufacturerBundle\Tests\DataFixtures\ManufacturerDataLoader', 'PartKeepr\DistributorBundle\Tests\DataFixtures\DistributorDataLoader', - ) + ] )->getReferenceRepository(); } - public function testStockHistory () { + public function testStockHistory() + { $client = static::makeClient(true); /** - * @var $part1 Part + * @var Part */ - $part1 = $this->fixtures->getReference("part.1"); + $part1 = $this->fixtures->getReference('part.1'); $stockLevel = new StockEntry(); $stockLevel->setPart($part1); $stockLevel->setStockLevel(5); - $fosUser = $this->fixtures->getReference("user.admin"); - $userService = $this->getContainer()->get("partkeepr.userservice"); + $fosUser = $this->fixtures->getReference('user.admin'); + $userService = $this->getContainer()->get('partkeepr.userservice'); $user = $userService->getProxyUser($fosUser->getUsername(), $userService->getBuiltinProvider(), true); $stockLevel->setUser($user); $part1->addStockLevel($stockLevel); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush(); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush(); - $iriCoverter = $this->getContainer()->get("api.iri_converter"); + $iriCoverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriCoverter->getIriFromItem($part1); - $client->request("GET", $iri); + $client->request('GET', $iri); $response = $client->getResponse()->getContent(); $responseObj = json_decode($response, true); - $responseObj["stockLevels"] = array(); + $responseObj['stockLevels'] = []; - $client->request("PUT", $iri, array(), array(), array(), json_encode($responseObj)); + $client->request('PUT', $iri, [], [], [], json_encode($responseObj)); $this->assertEquals(200, $client->getResponse()->getStatusCode()); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->refresh($part1); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->refresh($part1); $this->assertEquals(1, count($part1->getStockLevels())); } } diff --git a/src/PartKeepr/PartBundle/Tests/MoveActionTest.php b/src/PartKeepr/PartBundle/Tests/MoveActionTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractMoveCategoryTest; @@ -12,6 +13,6 @@ class MoveActionTest extends AbstractMoveCategoryTest public function getReferencePrefix() { - return "partcategory"; + return 'partcategory'; } } diff --git a/src/PartKeepr/PartBundle/Tests/PartTest.php b/src/PartKeepr/PartBundle/Tests/PartTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Tests; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -18,14 +19,14 @@ class PartTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\StorageLocationBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\StorageLocationBundle\DataFixtures\StorageLocationLoader', 'PartKeepr\PartBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\PartBundle\DataFixtures\PartDataLoader', 'PartKeepr\ManufacturerBundle\Tests\DataFixtures\ManufacturerDataLoader', 'PartKeepr\DistributorBundle\Tests\DataFixtures\DistributorDataLoader', - ) + ] )->getReferenceRepository(); } @@ -35,11 +36,11 @@ class PartTest extends WebTestCase public function testCategoryRequired() { $part = new Part(); - $part->setName("TEST"); - $part->setStorageLocation($this->fixtures->getReference("storagelocation.first")); + $part->setName('TEST'); + $part->setStorageLocation($this->fixtures->getReference('storagelocation.first')); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($part); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($part); } /** @@ -48,54 +49,54 @@ class PartTest extends WebTestCase public function testStorageLocationRequired() { $part = new Part(); - $part->setName("TEST"); - $part->setCategory($this->getContainer()->get("partkeepr.part.category_service")->getRootNode()); + $part->setName('TEST'); + $part->setCategory($this->getContainer()->get('partkeepr.part.category_service')->getRootNode()); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($part); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($part); } public function testBasics() { $part = new Part(); - $part->setName("TEST"); - $part->setCategory($this->getContainer()->get("partkeepr.part.category_service")->getRootNode()); - $part->setStorageLocation($this->fixtures->getReference("storagelocation.first")); + $part->setName('TEST'); + $part->setCategory($this->getContainer()->get('partkeepr.part.category_service')->getRootNode()); + $part->setStorageLocation($this->fixtures->getReference('storagelocation.first')); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($part); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($part); } public function testAssociationRemoval() { $part = new Part(); - $part->setName("TEST"); - $part->setCategory($this->getContainer()->get("partkeepr.part.category_service")->getRootNode()); - $part->setStorageLocation($this->fixtures->getReference("storagelocation.first")); + $part->setName('TEST'); + $part->setCategory($this->getContainer()->get('partkeepr.part.category_service')->getRootNode()); + $part->setStorageLocation($this->fixtures->getReference('storagelocation.first')); $partManufacturer = new PartManufacturer(); - $partManufacturer->setManufacturer($this->fixtures->getReference("manufacturer.first")); + $partManufacturer->setManufacturer($this->fixtures->getReference('manufacturer.first')); $part->addManufacturer($partManufacturer); $partDistributor = new PartDistributor(); - $partDistributor->setDistributor($this->fixtures->getReference("distributor.first")); + $partDistributor->setDistributor($this->fixtures->getReference('distributor.first')); $part->addDistributor($partDistributor); $partAttachment = new PartAttachment(); - $fileService = $this->getContainer()->get("partkeepr_uploadedfile_service"); - $fileService->replaceFromData($partAttachment, "BLA", "test.txt"); + $fileService = $this->getContainer()->get('partkeepr_uploadedfile_service'); + $fileService->replaceFromData($partAttachment, 'BLA', 'test.txt'); $part->addAttachment($partAttachment); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->persist($part); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->persist($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($part); $part->removeDistributor($partDistributor); $part->removeManufacturer($partManufacturer); $part->removeAttachment($partAttachment); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($part); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($part); $storage = $fileService->getStorage($partAttachment); diff --git a/src/PartKeepr/PartBundle/Tests/StockTest.php b/src/PartKeepr/PartBundle/Tests/StockTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\PartBundle\Tests; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -17,21 +18,21 @@ class StockTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\StorageLocationBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\StorageLocationBundle\DataFixtures\StorageLocationLoader', 'PartKeepr\PartBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\PartBundle\DataFixtures\PartDataLoader', - ) + ] )->getReferenceRepository(); } private function getStockLevel(Part $part) { /** - * @var Query $query + * @var Query */ - $query = $this->getContainer()->get("doctrine")->getManager()->createQuery("SELECT p.stockLevel FROM PartKeeprPartBundle:Part p WHERE p.id = :id")->setParameter("id", + $query = $this->getContainer()->get('doctrine')->getManager()->createQuery('SELECT p.stockLevel FROM PartKeeprPartBundle:Part p WHERE p.id = :id')->setParameter('id', $part->getId()); return $query->getSingleScalarResult(); @@ -42,38 +43,37 @@ class StockTest extends WebTestCase $client = static::makeClient(true); /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); + $part = $this->fixtures->getReference('part.1'); $oldStockLevel = $this->getStockLevel($part); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($part); - $iri .= "/addStock"; + $iri .= '/addStock'; - $request = array( - "quantity" => 5, - ); + $request = [ + 'quantity' => 5, + ]; $client->request( 'PUT', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $result = json_decode($client->getResponse()->getContent()); $newStockLevel = $this->getStockLevel($part); - $this->assertEquals($oldStockLevel + 5, $newStockLevel); - $this->assertObjectHasAttribute("stockLevel", $result); + $this->assertObjectHasAttribute('stockLevel', $result); $this->assertEquals($newStockLevel, $result->stockLevel); } @@ -82,38 +82,37 @@ class StockTest extends WebTestCase $client = static::makeClient(true); /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); + $part = $this->fixtures->getReference('part.1'); $oldStockLevel = $this->getStockLevel($part); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($part); - $iri .= "/removeStock"; + $iri .= '/removeStock'; - $request = array( - "quantity" => 7, - ); + $request = [ + 'quantity' => 7, + ]; $client->request( 'PUT', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $result = json_decode($client->getResponse()->getContent()); $newStockLevel = $this->getStockLevel($part); - $this->assertEquals($oldStockLevel - 7, $newStockLevel); - $this->assertObjectHasAttribute("stockLevel", $result); + $this->assertObjectHasAttribute('stockLevel', $result); $this->assertEquals($newStockLevel, $result->stockLevel); } @@ -122,38 +121,36 @@ class StockTest extends WebTestCase $client = static::makeClient(true); /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); + $part = $this->fixtures->getReference('part.1'); /** - * @var $iriConverter IriConverter + * @var IriConverter */ - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($part); - $iri .= "/setStock"; + $iri .= '/setStock'; - $request = array( - "quantity" => 33, - ); + $request = [ + 'quantity' => 33, + ]; $client->request( 'PUT', $iri, - array(), - array(), - array('CONTENT_TYPE' => 'application/json'), + [], + [], + ['CONTENT_TYPE' => 'application/json'], json_encode($request) ); $result = json_decode($client->getResponse()->getContent()); $newStockLevel = $this->getStockLevel($part); - $this->assertEquals(33, $newStockLevel); - $this->assertObjectHasAttribute("stockLevel", $result); + $this->assertObjectHasAttribute('stockLevel', $result); $this->assertEquals($newStockLevel, $result->stockLevel); } - } diff --git a/src/PartKeepr/ProjectBundle/Controller/ProjectAttachmentController.php b/src/PartKeepr/ProjectBundle/Controller/ProjectAttachmentController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ProjectBundle\Controller; use PartKeepr\ImageBundle\Controller\ImageController; @@ -6,10 +7,10 @@ use PartKeepr\ImageBundle\Controller\ImageController; class ProjectAttachmentController extends ImageController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\ProjectBundle\\Entity\\ProjectAttachment"; + return 'PartKeepr\\ProjectBundle\\Entity\\ProjectAttachment'; } } diff --git a/src/PartKeepr/ProjectBundle/Controller/ProjectReportController.php b/src/PartKeepr/ProjectBundle/Controller/ProjectReportController.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\ProjectBundle\Controller; +namespace PartKeepr\ProjectBundle\Controller; use Dunglas\ApiBundle\Api\IriConverter; use FOS\RestBundle\Controller\Annotations\View; @@ -13,110 +13,108 @@ class ProjectReportController extends FOSRestController /** * @Routing\Route("/api/project_reports", defaults={"method" = "get","_format" = "json"}) * @View() + * * @param Request $request - * @return array + * * @throws \Exception Thrown if parameters are formatted incorrectly + * + * @return array */ public function getProjectReportAction(Request $request) { - $projectsParameter = json_decode($request->get("projects")); + $projectsParameter = json_decode($request->get('projects')); if (!is_array($projectsParameter)) { - throw new \Exception("projects must be an array"); + throw new \Exception('projects must be an array'); } /** - * @var IriConverter $iriConverter + * @var IriConverter */ - $iriConverter = $this->get("api.iri_converter"); + $iriConverter = $this->get('api.iri_converter'); - $projects = array(); + $projects = []; foreach ($projectsParameter as $projectParameter) { if (!is_object($projectParameter)) { - throw new \Exception("Each project in the projects array must be an object"); + throw new \Exception('Each project in the projects array must be an object'); } - if (!property_exists($projectParameter, "quantity")) { - throw new \Exception("quantity must be present"); + if (!property_exists($projectParameter, 'quantity')) { + throw new \Exception('quantity must be present'); } - if (!property_exists($projectParameter, "project")) { - throw new \Exception("project ID must be present"); + if (!property_exists($projectParameter, 'project')) { + throw new \Exception('project ID must be present'); } - $project = $iriConverter->getItemFromIri($projectParameter->project); - $projects[] = array("project" => $project, "quantity" => $projectParameter->quantity); + $projects[] = ['project' => $project, 'quantity' => $projectParameter->quantity]; } - - $partRepository = $this->get("doctrine.orm.entity_manager")->getRepository("PartKeepr\\PartBundle\\Entity\\Part"); - $aPartResults = array(); + $partRepository = $this->get('doctrine.orm.entity_manager')->getRepository('PartKeepr\\PartBundle\\Entity\\Part'); + $aPartResults = []; foreach ($projects as $report) { - $dql = "SELECT pp.quantity, pro.name AS projectname, pp.remarks, p.id FROM "; - $dql .= "PartKeepr\\ProjectBundle\\Entity\\ProjectPart pp JOIN pp.part p "; - $dql .= "JOIN pp.project pro WHERE pp.project = :project"; + $dql = 'SELECT pp.quantity, pro.name AS projectname, pp.remarks, p.id FROM '; + $dql .= 'PartKeepr\\ProjectBundle\\Entity\\ProjectPart pp JOIN pp.part p '; + $dql .= 'JOIN pp.project pro WHERE pp.project = :project'; - $query = $this->get("doctrine.orm.entity_manager")->createQuery($dql); - $query->setParameter("project", $report["project"]); + $query = $this->get('doctrine.orm.entity_manager')->createQuery($dql); + $query->setParameter('project', $report['project']); foreach ($query->getArrayResult() as $result) { + $part = $partRepository->find($result['id']); - $part = $partRepository->find($result["id"]); - - if (array_key_exists($result["id"], $aPartResults)) { + if (array_key_exists($result['id'], $aPartResults)) { // Only update the quantity of the part - $aPartResults[$result["id"]]["quantity"] += $result["quantity"] * $report["quantity"]; - $aPartResults[$result["id"]]["projects"][] = $result["projectname"]; + $aPartResults[$result['id']]['quantity'] += $result['quantity'] * $report['quantity']; + $aPartResults[$result['id']]['projects'][] = $result['projectname']; - if ($result["remarks"] != "") { - $aPartResults[$result["id"]]["remarks"][] = $result["projectname"].": ".$result["remarks"]; + if ($result['remarks'] != '') { + $aPartResults[$result['id']]['remarks'][] = $result['projectname'].': '.$result['remarks']; } } else { - $serializedData = $this->get('serializer')->normalize( $part, 'jsonld' ); // Create a full resultset - $aPartResults[$result["id"]] = array( - "quantity" => $result["quantity"] * $report["quantity"], - "part" => $serializedData, - "storageLocation_name" => $part->getStorageLocation()->getName(), - "available" => $part->getStockLevel(), - "sum_order" => 0, - "projects" => array($result["projectname"]), - "remarks" => array(), - ); - - if ($result["remarks"] != "") { - $aPartResults[$result["id"]]["remarks"] = array($result["projectname"].": ".$result["remarks"]); + $aPartResults[$result['id']] = [ + 'quantity' => $result['quantity'] * $report['quantity'], + 'part' => $serializedData, + 'storageLocation_name' => $part->getStorageLocation()->getName(), + 'available' => $part->getStockLevel(), + 'sum_order' => 0, + 'projects' => [$result['projectname']], + 'remarks' => [], + ]; + + if ($result['remarks'] != '') { + $aPartResults[$result['id']]['remarks'] = [$result['projectname'].': '.$result['remarks']]; } } } } - $aFinalResult = array(); + $aFinalResult = []; // Iterate over all results and calculate how many parts are missing foreach ($aPartResults as $key => $partResult) { - $missing = $partResult["quantity"] - $partResult["available"]; + $missing = $partResult['quantity'] - $partResult['available']; if ($missing < 0) { $missing = 0; } - $partResult["missing"] = $missing; - $partResult["remarks"] = implode(", ", $partResult["remarks"]); - $partResult["projects"] = implode(", ", $partResult["projects"]); + $partResult['missing'] = $missing; + $partResult['remarks'] = implode(', ', $partResult['remarks']); + $partResult['projects'] = implode(', ', $partResult['projects']); $aFinalResult[] = $partResult; } - return $aFinalResult; } } diff --git a/src/PartKeepr/ProjectBundle/DataFixtures/ProjectFixtureLoader.php b/src/PartKeepr/ProjectBundle/DataFixtures/ProjectFixtureLoader.php @@ -1,10 +1,10 @@ <?php + namespace PartKeepr\ProjectBundle\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use PartKeepr\ProjectBundle\Entity\Project; -use PartKeepr\ProjectBundle\Entity\ProjectAttachment; use PartKeepr\ProjectBundle\Entity\ProjectPart; class ProjectFixtureLoader extends AbstractFixture @@ -12,16 +12,16 @@ class ProjectFixtureLoader extends AbstractFixture public function load(ObjectManager $manager) { $projectPart1 = new ProjectPart(); - $projectPart1->setPart($this->getReference("part.1")); + $projectPart1->setPart($this->getReference('part.1')); $projectPart1->setQuantity(1); $projectPart2 = new ProjectPart(); - $projectPart2->setPart($this->getReference("part.2")); + $projectPart2->setPart($this->getReference('part.2')); $projectPart2->setQuantity(1); $project = new Project(); - $project->setName("FOOBAR"); - $project->setDescription("none"); + $project->setName('FOOBAR'); + $project->setDescription('none'); $project->addPart($projectPart1); $project->addPart($projectPart2); @@ -30,8 +30,8 @@ class ProjectFixtureLoader extends AbstractFixture $manager->persist($projectPart2); $manager->flush(); - $this->addReference("project", $project); - $this->addReference("projectpart.1", $projectPart1); - $this->addReference("projectpart.2", $projectPart2); + $this->addReference('project', $project); + $this->addReference('projectpart.1', $projectPart1); + $this->addReference('projectpart.2', $projectPart2); } } diff --git a/src/PartKeepr/ProjectBundle/Entity/Project.php b/src/PartKeepr/ProjectBundle/Entity/Project.php @@ -1,16 +1,17 @@ <?php + namespace PartKeepr\ProjectBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use PartKeepr\AuthBundle\Entity\User; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** - * Represents a project + * Represents a project. * * @ORM\Entity * @TargetService("/api/projects") @@ -18,46 +19,51 @@ use Symfony\Component\Serializer\Annotation\Groups; class Project extends BaseEntity { /** - * Specifies the name of the project + * Specifies the name of the project. * * @ORM\Column(type="string") * @Groups({"default"}) + * * @var string */ private $name; /** - * Specifies the user this project belongs to + * Specifies the user this project belongs to. * * @ORM\ManyToOne(targetEntity="PartKeepr\AuthBundle\Entity\User") + * * @var User */ private $user; /** - * Holds the parts needed for this project + * Holds the parts needed for this project. * * @ORM\OneToMany(targetEntity="PartKeepr\ProjectBundle\Entity\ProjectPart",mappedBy="project",cascade={"persist", "remove"}, orphanRemoval=true) * @Groups({"default"}) + * * @var ArrayCollection */ private $parts; /** - * Holds the description of this project + * Holds the description of this project. * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) + * * @var string */ private $description; /** - * Holds the project attachments + * Holds the project attachments. * * @ORM\OneToMany(targetEntity="PartKeepr\ProjectBundle\Entity\ProjectAttachment",mappedBy="project",cascade={"persist", "remove"}, orphanRemoval=true) * @UploadedFileCollection() * @Groups({"default"}) + * * @var ArrayCollection */ private $attachments; @@ -69,7 +75,7 @@ class Project extends BaseEntity } /** - * Sets the user for this project + * Sets the user for this project. * * @param User $user */ @@ -79,7 +85,7 @@ class Project extends BaseEntity } /** - * Gets the user for this project + * Gets the user for this project. * * @return User */ @@ -89,7 +95,7 @@ class Project extends BaseEntity } /** - * Sets the name for this project + * Sets the name for this project. * * @param string $name */ @@ -99,7 +105,7 @@ class Project extends BaseEntity } /** - * Returns the name of this project + * Returns the name of this project. * * @return string */ @@ -109,7 +115,7 @@ class Project extends BaseEntity } /** - * Sets the description of this project + * Sets the description of this project. * * @param string $description The description to set */ @@ -119,7 +125,7 @@ class Project extends BaseEntity } /** - * Returns the description of this project + * Returns the description of this project. * * @return string The description */ @@ -129,7 +135,7 @@ class Project extends BaseEntity } /** - * Returns the project parts array + * Returns the project parts array. * * @return ProjectPart[] An array of ProjectPart objects */ @@ -139,7 +145,7 @@ class Project extends BaseEntity } /** - * Adds a Project Part + * Adds a Project Part. * * @param ProjectPart $projectPart A part to add */ @@ -150,7 +156,7 @@ class Project extends BaseEntity } /** - * Removes a Project Part + * Removes a Project Part. * * @param ProjectPart $projectPart A part to remove */ @@ -160,9 +166,8 @@ class Project extends BaseEntity $this->parts->removeElement($projectPart); } - /** - * Returns the attachments for this project + * Returns the attachments for this project. * * @return ProjectAttachment[] The attachments */ @@ -172,7 +177,7 @@ class Project extends BaseEntity } /** - * Adds a Project Attachment + * Adds a Project Attachment. * * @param ProjectAttachment $projectAttachment An attachment to add */ @@ -185,7 +190,7 @@ class Project extends BaseEntity } /** - * Removes a Project Attachment + * Removes a Project Attachment. * * @param ProjectAttachment $projectAttachment An attachment to remove */ diff --git a/src/PartKeepr/ProjectBundle/Entity/ProjectAttachment.php b/src/PartKeepr/ProjectBundle/Entity/ProjectAttachment.php @@ -1,13 +1,13 @@ <?php + namespace PartKeepr\ProjectBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Entity\UploadedFile; -use Symfony\Component\Serializer\Annotation\Groups; /** - * Holds a project attachment + * Holds a project attachment. * * @ORM\Entity * @TargetService("/api/project_attachments") @@ -15,24 +15,25 @@ use Symfony\Component\Serializer\Annotation\Groups; class ProjectAttachment extends UploadedFile { /** - * Creates a new project attachment + * Creates a new project attachment. */ public function __construct() { parent::__construct(); - $this->setType("ProjectAttachment"); + $this->setType('ProjectAttachment'); } /** - * The project object + * The project object. * * @ORM\ManyToOne(targetEntity="PartKeepr\ProjectBundle\Entity\Project", inversedBy="attachments") + * * @var Project */ private $project = null; /** - * Sets the project + * Sets the project. * * @param Project $project The project to set */ @@ -42,7 +43,7 @@ class ProjectAttachment extends UploadedFile } /** - * Returns the roject + * Returns the roject. * * @return Project the project */ diff --git a/src/PartKeepr/ProjectBundle/Entity/ProjectPart.php b/src/PartKeepr/ProjectBundle/Entity/ProjectPart.php @@ -1,14 +1,15 @@ <?php + namespace PartKeepr\ProjectBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\PartBundle\Entity\Part; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** - * Represents a project part + * Represents a project part. * * @ORM\Entity * @TargetService("/api/project_parts") @@ -16,42 +17,46 @@ use Symfony\Component\Serializer\Annotation\Groups; class ProjectPart extends BaseEntity { /** - * The part this project part refers to + * The part this project part refers to. * * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\Part", inversedBy="projectParts") * @Groups({"default"}) + * * @var Part */ private $part; /** - * Specifies the amount of parts + * Specifies the amount of parts. * * @ORM\Column(type="integer") * @Groups({"default"}) - * @var integer + * + * @var int */ private $quantity; /** - * Specifies the project which belongs to this project part + * Specifies the project which belongs to this project part. * * @ORM\ManyToOne(targetEntity="PartKeepr\ProjectBundle\Entity\Project", inversedBy="parts") + * * @var Project */ private $project; /** - * Specifies the remarks for this entry + * Specifies the remarks for this entry. * * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) + * * @var string */ private $remarks; /** - * Sets the part which belongs to this entry + * Sets the part which belongs to this entry. * * @param Part $part */ @@ -61,7 +66,7 @@ class ProjectPart extends BaseEntity } /** - * Returns the part which belongs to this entry + * Returns the part which belongs to this entry. * * @return Part */ @@ -71,7 +76,7 @@ class ProjectPart extends BaseEntity } /** - * Sets the quantity for this entry + * Sets the quantity for this entry. * * @param int $quantity */ @@ -81,7 +86,7 @@ class ProjectPart extends BaseEntity } /** - * Returns the quantity for this project + * Returns the quantity for this project. * * @return int the amount of parts needed */ @@ -91,7 +96,7 @@ class ProjectPart extends BaseEntity } /** - * Sets the project assigned to this entry + * Sets the project assigned to this entry. * * @param Project $project */ @@ -101,7 +106,7 @@ class ProjectPart extends BaseEntity } /** - * Returns the project assigned to this entry + * Returns the project assigned to this entry. * * @return Project */ @@ -111,7 +116,7 @@ class ProjectPart extends BaseEntity } /** - * Sets the remarks for this entry + * Sets the remarks for this entry. * * @param string $remarks */ @@ -121,7 +126,7 @@ class ProjectPart extends BaseEntity } /** - * Returns the remarks for this entry + * Returns the remarks for this entry. * * @return string */ diff --git a/src/PartKeepr/ProjectBundle/PartKeeprProjectBundle.php b/src/PartKeepr/ProjectBundle/PartKeeprProjectBundle.php @@ -1,9 +1,9 @@ <?php + namespace PartKeepr\ProjectBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprProjectBundle extends Bundle { - } diff --git a/src/PartKeepr/ProjectBundle/Tests/ProjectTest.php b/src/PartKeepr/ProjectBundle/Tests/ProjectTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\ProjectBundle\Tests; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; @@ -18,13 +19,13 @@ class ProjectTest extends WebTestCase public function setUp() { $this->fixtures = $this->loadFixtures( - array( + [ 'PartKeepr\StorageLocationBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\StorageLocationBundle\DataFixtures\StorageLocationLoader', 'PartKeepr\PartBundle\DataFixtures\CategoryDataLoader', 'PartKeepr\PartBundle\DataFixtures\PartDataLoader', 'PartKeepr\ProjectBundle\DataFixtures\ProjectFixtureLoader', - ) + ] )->getReferenceRepository(); } @@ -32,9 +33,9 @@ class ProjectTest extends WebTestCase { $client = static::makeClient(true); - $file = __DIR__."/../../UploadedFileBundle/Tests/Fixtures/files/uploadtest.png"; + $file = __DIR__.'/../../UploadedFileBundle/Tests/Fixtures/files/uploadtest.png'; $originalFilename = 'uploadtest.png'; - $mimeType = "image/png"; + $mimeType = 'image/png'; $image = new UploadedFile( $file, @@ -46,120 +47,116 @@ class ProjectTest extends WebTestCase $client->request( 'POST', '/api/temp_uploaded_files/upload', - array(), - array('userfile' => $image) + [], + ['userfile' => $image] ); $uploadedFile = json_decode($client->getResponse()->getContent()); /** - * @var $part Part + * @var Part */ - $part = $this->fixtures->getReference("part.1"); - $part2 = $this->fixtures->getReference("part.2"); - + $part = $this->fixtures->getReference('part.1'); + $part2 = $this->fixtures->getReference('part.2'); - $serializedPart1 = $this->getContainer()->get("serializer")->normalize( + $serializedPart1 = $this->getContainer()->get('serializer')->normalize( $part, 'jsonld' ); - $serializedPart2 = $this->getContainer()->get("serializer")->normalize( + $serializedPart2 = $this->getContainer()->get('serializer')->normalize( $part2, 'jsonld' ); - $project = array( - "name" => "foobar", - "description" => "testdescription", - "attachments" => array( + $project = [ + 'name' => 'foobar', + 'description' => 'testdescription', + 'attachments' => [ $uploadedFile->image, - ), - "parts" => array( - array( - "quantity" => 1, - "part" => $serializedPart1, - "remarks" => "testremark", - ), - array( - "quantity" => 2, - "part" => $serializedPart2, - "remarks" => "testremark2", - ), - ), - ); + ], + 'parts' => [ + [ + 'quantity' => 1, + 'part' => $serializedPart1, + 'remarks' => 'testremark', + ], + [ + 'quantity' => 2, + 'part' => $serializedPart2, + 'remarks' => 'testremark2', + ], + ], + ]; $client->request( 'POST', '/api/projects', - array(), - array(), - array(), + [], + [], + [], json_encode($project) ); - $response = json_decode($client->getResponse()->getContent()); - $this->assertObjectHasAttribute("@type", $response); - $this->assertEquals("Project", $response->{"@type"}); + $this->assertObjectHasAttribute('@type', $response); + $this->assertEquals('Project', $response->{'@type'}); - $this->assertObjectHasAttribute("name", $response); - $this->assertEquals("foobar", $response->name); + $this->assertObjectHasAttribute('name', $response); + $this->assertEquals('foobar', $response->name); - $this->assertObjectHasAttribute("description", $response); - $this->assertEquals("testdescription", $response->description); + $this->assertObjectHasAttribute('description', $response); + $this->assertEquals('testdescription', $response->description); - $this->assertObjectHasAttribute("parts", $response); - $this->assertInternalType("array", $response->parts); + $this->assertObjectHasAttribute('parts', $response); + $this->assertInternalType('array', $response->parts); $this->assertEquals(2, count($response->parts)); $this->assertArrayHasKey(0, $response->parts); - $this->assertEquals("ProjectPart", $response->parts[0]->{"@type"}); + $this->assertEquals('ProjectPart', $response->parts[0]->{'@type'}); $this->assertEquals(1, $response->parts[0]->quantity); - $this->assertEquals("testremark", $response->parts[0]->remarks); - $this->assertEquals("Part", $response->parts[0]->part->{"@type"}); + $this->assertEquals('testremark', $response->parts[0]->remarks); + $this->assertEquals('Part', $response->parts[0]->part->{'@type'}); - $this->assertObjectHasAttribute("attachments", $response); + $this->assertObjectHasAttribute('attachments', $response); $this->assertEquals(1, count($response->attachments)); $this->assertArrayHasKey(0, $response->attachments); - $this->assertEquals("ProjectAttachment", $response->attachments[0]->{"@type"}); + $this->assertEquals('ProjectAttachment', $response->attachments[0]->{'@type'}); unset($response->parts[0]); - - } public function testProjectPartRemoval() { $client = static::makeClient(true); - $project = $this->fixtures->getReference("project"); - $projectPart = $this->fixtures->getReference("projectpart.1"); + $project = $this->fixtures->getReference('project'); + $projectPart = $this->fixtures->getReference('projectpart.1'); $project->removePart($projectPart); - $serializedProject = $this->getContainer()->get("serializer")->normalize( + $serializedProject = $this->getContainer()->get('serializer')->normalize( $project, 'jsonld' ); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($project); $client->request( 'PUT', $iri, - array(), - array(), - array(), + [], + [], + [], json_encode($serializedProject) ); $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("array", $response->parts); + $this->assertInternalType('array', $response->parts); $this->assertArrayNotHasKey(1, $response->parts, - "When removing an entry from the ArrayCollection, the array must be resorted!"); + 'When removing an entry from the ArrayCollection, the array must be resorted!'); $this->assertEquals(1, count($response->parts)); } @@ -168,42 +165,42 @@ class ProjectTest extends WebTestCase $client = static::makeClient(true); /** - * @var $project Project + * @var Project */ - $project = $this->fixtures->getReference("project"); + $project = $this->fixtures->getReference('project'); $projectAttachment = new ProjectAttachment(); - $fileService = $this->getContainer()->get("partkeepr_uploadedfile_service"); - $fileService->replaceFromData($projectAttachment, "BLA", "test.txt"); + $fileService = $this->getContainer()->get('partkeepr_uploadedfile_service'); + $fileService->replaceFromData($projectAttachment, 'BLA', 'test.txt'); $project->addAttachment($projectAttachment); - $this->getContainer()->get("doctrine.orm.default_entity_manager")->flush($project); + $this->getContainer()->get('doctrine.orm.default_entity_manager')->flush($project); $project->removeAttachment($projectAttachment); - $serializedProject = $this->getContainer()->get("serializer")->normalize( + $serializedProject = $this->getContainer()->get('serializer')->normalize( $project, 'jsonld' ); - $iriConverter = $this->getContainer()->get("api.iri_converter"); + $iriConverter = $this->getContainer()->get('api.iri_converter'); $iri = $iriConverter->getIriFromItem($project); $client->request( 'PUT', $iri, - array(), - array(), - array(), + [], + [], + [], json_encode($serializedProject) ); $response = json_decode($client->getResponse()->getContent()); - $this->assertInternalType("array", $response->attachments); + $this->assertInternalType('array', $response->attachments); $this->assertArrayNotHasKey(1, $response->attachments, - "When removing an entry from the ArrayCollection, the array must be resorted!"); + 'When removing an entry from the ArrayCollection, the array must be resorted!'); $this->assertEquals(0, count($response->attachments)); } diff --git a/src/PartKeepr/RESTBundle/DependencyInjection/PartKeeprRESTExtension.php b/src/PartKeepr/RESTBundle/DependencyInjection/PartKeeprRESTExtension.php @@ -2,13 +2,13 @@ namespace PartKeepr\RESTBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/RESTBundle/Request/ParamReader.php b/src/PartKeepr/RESTBundle/Request/ParamReader.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\RESTBundle\Request; use FOS\RestBundle\Request\ParamReader as FOSRestParamReader; @@ -7,7 +8,7 @@ class ParamReader extends FOSRestParamReader { public function getParamsFromMethod(\ReflectionMethod $method) { - $parentParams = array(); + $parentParams = []; $params = parent::getParamsFromMethod($method); // This loads the annotations of the parent method @@ -21,4 +22,4 @@ class ParamReader extends FOSRestParamReader return array_merge($params, $parentParams); } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/SetupBundle/Command/ImportFootprintsCommand.php b/src/PartKeepr/SetupBundle/Command/ImportFootprintsCommand.php @@ -1,25 +1,25 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class ImportFootprintsCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:setup:import-footprints'); - $this->setDescription("Imports the default PartKeepr footprints"); + $this->setDescription('Imports the default PartKeepr footprints'); } public function execute(InputInterface $input, OutputInterface $output) { - $return = $this->getContainer()->get("partkeepr.setup.footprint_service")->importFootprints(); + $return = $this->getContainer()->get('partkeepr.setup.footprint_service')->importFootprints(); - $output->writeln(sprintf("%d footprints imported, %d existing footprints skipped", $return["imported"], - $return["skipped"])); + $output->writeln(sprintf('%d footprints imported, %d existing footprints skipped', $return['imported'], + $return['skipped'])); } } diff --git a/src/PartKeepr/SetupBundle/Command/ImportManufacturersCommand.php b/src/PartKeepr/SetupBundle/Command/ImportManufacturersCommand.php @@ -1,25 +1,25 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class ImportManufacturersCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:setup:import-manufacturers'); - $this->setDescription("Imports the default PartKeepr manufacturers"); + $this->setDescription('Imports the default PartKeepr manufacturers'); } public function execute(InputInterface $input, OutputInterface $output) { - $return = $this->getContainer()->get("partkeepr.setup.manufacturer_service")->importManufacturers(); + $return = $this->getContainer()->get('partkeepr.setup.manufacturer_service')->importManufacturers(); - $output->writeln(sprintf("%d manufacturers imported, %d existing manufacturers skipped", $return["imported"], - $return["skipped"])); + $output->writeln(sprintf('%d manufacturers imported, %d existing manufacturers skipped', $return['imported'], + $return['skipped'])); } } diff --git a/src/PartKeepr/SetupBundle/Command/ImportSiPrefixesCommand.php b/src/PartKeepr/SetupBundle/Command/ImportSiPrefixesCommand.php @@ -1,25 +1,25 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class ImportSiPrefixesCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:setup:import-si-prefixes'); - $this->setDescription("Imports or updates the default PartKeepr si prefixes"); + $this->setDescription('Imports or updates the default PartKeepr si prefixes'); } public function execute(InputInterface $input, OutputInterface $output) { - $return = $this->getContainer()->get("partkeepr.setup.si_prefix_service")->importSiPrefixes(); + $return = $this->getContainer()->get('partkeepr.setup.si_prefix_service')->importSiPrefixes(); - $output->writeln(sprintf("%d SI prefixes imported, %d existing SI Prefixes updated", $return["imported"], - $return["updated"])); + $output->writeln(sprintf('%d SI prefixes imported, %d existing SI Prefixes updated', $return['imported'], + $return['updated'])); } } diff --git a/src/PartKeepr/SetupBundle/Command/ImportUnitsCommand.php b/src/PartKeepr/SetupBundle/Command/ImportUnitsCommand.php @@ -1,25 +1,25 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class ImportUnitsCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:setup:import-units'); - $this->setDescription("Imports the default PartKeepr units"); + $this->setDescription('Imports the default PartKeepr units'); } public function execute(InputInterface $input, OutputInterface $output) { - $return = $this->getContainer()->get("partkeepr.setup.unit_service")->importUnits(); + $return = $this->getContainer()->get('partkeepr.setup.unit_service')->importUnits(); - $output->writeln(sprintf("%d units imported, %d existing units skipped", $return["imported"], - $return["skipped"])); + $output->writeln(sprintf('%d units imported, %d existing units skipped', $return['imported'], + $return['skipped'])); } } diff --git a/src/PartKeepr/SetupBundle/Command/SetupDefaultPartUnitCommand.php b/src/PartKeepr/SetupBundle/Command/SetupDefaultPartUnitCommand.php @@ -1,28 +1,28 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - class SetupDefaultPartUnitCommand extends ContainerAwareCommand { public function configure() { parent::configure(); $this->setName('partkeepr:setup:part-unit'); - $this->setDescription("Sets up the default part unit"); + $this->setDescription('Sets up the default part unit'); } public function execute(InputInterface $input, OutputInterface $output) { - $return = $this->getContainer()->get("partkeepr.setup.part_unit_service")->setupDefaultPartUnit(); + $return = $this->getContainer()->get('partkeepr.setup.part_unit_service')->setupDefaultPartUnit(); if ($return) { - $output->writeln("Default part unit created"); + $output->writeln('Default part unit created'); } else { - $output->writeln("Default part unit not created as it already exists"); + $output->writeln('Default part unit not created as it already exists'); } } } diff --git a/src/PartKeepr/SetupBundle/Command/UpdateConfigCommand.php b/src/PartKeepr/SetupBundle/Command/UpdateConfigCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -11,16 +12,16 @@ class UpdateConfigCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:setup:update-config'); - $this->setDescription("Updates the PartKeepr configuration with all required config parameters"); + $this->setDescription('Updates the PartKeepr configuration with all required config parameters'); } public function execute(InputInterface $input, OutputInterface $output) { - $configService = $this->getContainer()->get("partkeepr.setup.config_service"); + $configService = $this->getContainer()->get('partkeepr.setup.config_service'); $config = $configService->configParser(); $configOutput = $configService->getConfig($config); file_put_contents($configService->getConfigPath(false), $configOutput); - $output->writeln("Config updated"); + $output->writeln('Config updated'); } } diff --git a/src/PartKeepr/SetupBundle/Controller/AdminUserSetupController.php b/src/PartKeepr/SetupBundle/Controller/AdminUserSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; @@ -15,7 +16,7 @@ class AdminUserSetupController extends SetupBaseController { $data = json_decode($request->getContent(), true); - $response = $this->handleRequest($request, "/setup/_int_create_user", $data["adminuser"]); + $response = $this->handleRequest($request, '/setup/_int_create_user', $data['adminuser']); return new Response($response->getContent()); } @@ -30,36 +31,35 @@ class AdminUserSetupController extends SetupBaseController } $data = json_decode($request->getContent(), true); - if (!array_key_exists("authKey", $data) || !$this->verifyAuthKey($data["authKey"])) { - $response["success"] = false; - $response["message"] = "Invalid Authentication Key"; - $response["errors"] = array(); + if (!array_key_exists('authKey', $data) || !$this->verifyAuthKey($data['authKey'])) { + $response['success'] = false; + $response['message'] = 'Invalid Authentication Key'; + $response['errors'] = []; return new JsonResponse($response); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Admin user successfully created", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Admin user successfully created', + ]; try { $manager = $this->get('fos_user.user_manager'); - $user = $manager->findUserByUsername($request->query->get("username")); + $user = $manager->findUserByUsername($request->query->get('username')); if ($user === null) { $manipulator = $this->get('fos_user.util.user_manipulator'); - $manipulator->create($request->query->get("username"), $request->query->get("password"), - $request->query->get("email"), true, true); + $manipulator->create($request->query->get('username'), $request->query->get('password'), + $request->query->get('email'), true, true); } } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "User creation error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'User creation error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); } - } diff --git a/src/PartKeepr/SetupBundle/Controller/CacheWarmupSetupController.php b/src/PartKeepr/SetupBundle/Controller/CacheWarmupSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Symfony\Bundle\FrameworkBundle\Console\Application; @@ -20,11 +21,11 @@ class CacheWarmupSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Cache successfully warmed up", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Cache successfully warmed up', + ]; try { $kernel = $this->get('kernel'); @@ -32,74 +33,73 @@ class CacheWarmupSetupController extends SetupBaseController $application->setAutoExit(false); $output = new NullOutput(); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'cache:warmup', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'nfq:sprite:generate', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'assets:install', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'generate:extjs:entities', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'assetic:dump', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'partkeepr:update-category-paths', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'partkeepr:cron:clear', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'partkeepr:cron:versioncheck', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'partkeepr:cron:synctips', - )); + ]); $application->run($input, $output); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'partkeepr:cron:create-statistic-snapshot', - )); + ]); $application->run($input, $output); - if (function_exists("apc_clear_cache")) { + if (function_exists('apc_clear_cache')) { apc_clear_cache(); } - } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Cache warm up error"; - $response["errors"] = [$e->getMessage(), $e->getTrace()]; + $response['success'] = false; + $response['message'] = 'Cache warm up error'; + $response['errors'] = [$e->getMessage(), $e->getTrace()]; } return new JsonResponse($response); @@ -111,12 +111,12 @@ class CacheWarmupSetupController extends SetupBaseController public function cacheWarmupAction(Request $request) { // Clear old cache. We don't do that directly as it could happen that old files are loaded prior clearing the cache - $cacheDir = $this->get("kernel")->getRootDir()."/cache/prod"; + $cacheDir = $this->get('kernel')->getRootDir().'/cache/prod'; - $filesystem = $this->get("filesystem"); + $filesystem = $this->get('filesystem'); $filesystem->remove($cacheDir); - $response = $this->handleRequest($request, "/setup/_int_cache_warmup", array(), "prod"); + $response = $this->handleRequest($request, '/setup/_int_cache_warmup', [], 'prod'); return new Response($response->getContent()); } diff --git a/src/PartKeepr/SetupBundle/Controller/ExistingConfigParserController.php b/src/PartKeepr/SetupBundle/Controller/ExistingConfigParserController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; @@ -9,6 +10,7 @@ class ExistingConfigParserController extends SetupBaseController { /** * @Route("/setup/parseExistingConfig") + * * @param Request $request * * @return JsonResponse @@ -19,30 +21,29 @@ class ExistingConfigParserController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Existing configuration imported successfully", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Existing configuration imported successfully', + ]; try { - $response["config"] = $this->get("partkeepr.setup.config_service")->configParser(); + $response['config'] = $this->get('partkeepr.setup.config_service')->configParser(); - if (count($response["config"]) == 0) { - $response["config"] = $this->getLegacyConfig(); + if (count($response['config']) == 0) { + $response['config'] = $this->getLegacyConfig(); } - if (count($response["config"]) == 0) { - $response["message"] = "No configuration found"; - $response["existingConfig"] = false; + if (count($response['config']) == 0) { + $response['message'] = 'No configuration found'; + $response['existingConfig'] = false; } else { - $response["existingConfig"] = true; + $response['existingConfig'] = true; } - } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Configuration parse error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Configuration parse error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -50,67 +51,67 @@ class ExistingConfigParserController extends SetupBaseController protected function getLegacyConfig() { - $config = array(); + $config = []; - $legacyConfig = $this->get("partkeepr.setup.config_service")->legacyConfigParser(); + $legacyConfig = $this->get('partkeepr.setup.config_service')->legacyConfigParser(); if (count($legacyConfig) > 0) { - if (array_key_exists("partkeepr.database.driver", $legacyConfig)) { - $config["database_driver"] = $legacyConfig["partkeepr.database.driver"]; + if (array_key_exists('partkeepr.database.driver', $legacyConfig)) { + $config['database_driver'] = $legacyConfig['partkeepr.database.driver']; } - if (array_key_exists("partkeepr.database.hostname", $legacyConfig)) { - $config["database_host"] = $legacyConfig["partkeepr.database.hostname"]; + if (array_key_exists('partkeepr.database.hostname', $legacyConfig)) { + $config['database_host'] = $legacyConfig['partkeepr.database.hostname']; } - if (array_key_exists("partkeepr.database.username", $legacyConfig)) { - $config["database_user"] = $legacyConfig["partkeepr.database.username"]; + if (array_key_exists('partkeepr.database.username', $legacyConfig)) { + $config['database_user'] = $legacyConfig['partkeepr.database.username']; } - if (array_key_exists("partkeepr.database.password", $legacyConfig)) { - $config["database_password"] = $legacyConfig["partkeepr.database.password"]; + if (array_key_exists('partkeepr.database.password', $legacyConfig)) { + $config['database_password'] = $legacyConfig['partkeepr.database.password']; } - if (array_key_exists("partkeepr.database.dbname", $legacyConfig)) { - $config["database_name"] = $legacyConfig["partkeepr.database.dbname"]; + if (array_key_exists('partkeepr.database.dbname', $legacyConfig)) { + $config['database_name'] = $legacyConfig['partkeepr.database.dbname']; } - if (array_key_exists("partkeepr.database.port", $legacyConfig)) { - $config["database_port"] = $legacyConfig["partkeepr.database.port"]; + if (array_key_exists('partkeepr.database.port', $legacyConfig)) { + $config['database_port'] = $legacyConfig['partkeepr.database.port']; } - $config["authentication_provider"] = "PartKeepr.Auth.HTTPBasicAuthenticationProvider"; + $config['authentication_provider'] = 'PartKeepr.Auth.HTTPBasicAuthenticationProvider'; - if (array_key_exists("partkeepr.frontend.motd", $legacyConfig)) { - $config["partkeepr.frontend.motd"] = $legacyConfig["partkeepr.frontend.motd"]; + if (array_key_exists('partkeepr.frontend.motd', $legacyConfig)) { + $config['partkeepr.frontend.motd'] = $legacyConfig['partkeepr.frontend.motd']; } - if (array_key_exists("partkeepr.frontend.autologin.enabled", $legacyConfig)) { - $config["partkeepr.frontend.auto_login.enabled"] = $legacyConfig["partkeepr.frontend.autologin.enabled"]; + if (array_key_exists('partkeepr.frontend.autologin.enabled', $legacyConfig)) { + $config['partkeepr.frontend.auto_login.enabled'] = $legacyConfig['partkeepr.frontend.autologin.enabled']; } - if (array_key_exists("partkeepr.frontend.autologin.username", $legacyConfig)) { - $config["partkeepr.frontend.auto_login.username"] = $legacyConfig["partkeepr.frontend.autologin.username"]; + if (array_key_exists('partkeepr.frontend.autologin.username', $legacyConfig)) { + $config['partkeepr.frontend.auto_login.username'] = $legacyConfig['partkeepr.frontend.autologin.username']; } - if (array_key_exists("partkeepr.frontend.autologin.password", $legacyConfig)) { - $config["partkeepr.frontend.auto_login.password"] = $legacyConfig["partkeepr.frontend.autologin.password"]; + if (array_key_exists('partkeepr.frontend.autologin.password', $legacyConfig)) { + $config['partkeepr.frontend.auto_login.password'] = $legacyConfig['partkeepr.frontend.autologin.password']; } - if (array_key_exists("partkeepr.cronjobs.disablecheck", $legacyConfig)) { - $config["partkeepr.cronjob.check"] = $legacyConfig["partkeepr.cronjobs.disablecheck"]; + if (array_key_exists('partkeepr.cronjobs.disablecheck', $legacyConfig)) { + $config['partkeepr.cronjob.check'] = $legacyConfig['partkeepr.cronjobs.disablecheck']; } - if (array_key_exists("partkeepr.category.path_separator", $legacyConfig)) { - $config["partkeepr.category.path_separator"] = $legacyConfig["partkeepr.category.path_separator"]; + if (array_key_exists('partkeepr.category.path_separator', $legacyConfig)) { + $config['partkeepr.category.path_separator'] = $legacyConfig['partkeepr.category.path_separator']; } - if (array_key_exists("partkeepr.frontend.allow_password_change", $legacyConfig)) { - $config["partkeepr.auth.allow_password_change"] = $legacyConfig["partkeepr.frontend.allow_password_change"]; + if (array_key_exists('partkeepr.frontend.allow_password_change', $legacyConfig)) { + $config['partkeepr.auth.allow_password_change'] = $legacyConfig['partkeepr.frontend.allow_password_change']; } - if (array_key_exists("partkeepr.files.path", $legacyConfig)) { - $config["partkeepr.filesystem.data_directory"] = $legacyConfig["partkeepr.files.path"]; + if (array_key_exists('partkeepr.files.path', $legacyConfig)) { + $config['partkeepr.filesystem.data_directory'] = $legacyConfig['partkeepr.files.path']; } } diff --git a/src/PartKeepr/SetupBundle/Controller/ExistingUserSetupController.php b/src/PartKeepr/SetupBundle/Controller/ExistingUserSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; @@ -9,7 +10,8 @@ use Symfony\Component\HttpFoundation\Response; class ExistingUserSetupController extends SetupBaseController { /** - * Checks if there are existing userds in the database + * Checks if there are existing userds in the database. + * * @Route("/setup/testExistingUsers") */ public function testExistingUsersAction(Request $request) @@ -20,7 +22,7 @@ class ExistingUserSetupController extends SetupBaseController $this->dumpConfig($request); - $response = $this->handleRequest($request, "/setup/_int_test_existing_users"); + $response = $this->handleRequest($request, '/setup/_int_test_existing_users'); return new Response($response->getContent()); } @@ -36,22 +38,22 @@ class ExistingUserSetupController extends SetupBaseController $legacyUsersDQL = "SELECT COUNT(u) FROM PartKeepr\AuthBundle\Entity\User u WHERE u.legacy = true"; - $legacyUsersQuery = $this->get("doctrine.orm.default_entity_manager")->createQuery($legacyUsersDQL); + $legacyUsersQuery = $this->get('doctrine.orm.default_entity_manager')->createQuery($legacyUsersDQL); $totalUsersDQL = "SELECT COUNT(u) FROM PartKeepr\AuthBundle\Entity\User u"; - $totalUsersQuery = $this->get("doctrine.orm.default_entity_manager")->createQuery($totalUsersDQL); + $totalUsersQuery = $this->get('doctrine.orm.default_entity_manager')->createQuery($totalUsersDQL); - $response = array( - "success" => true, - "legacyUsers" => (int)$legacyUsersQuery->getSingleScalarResult(), - "totalUsers" => (int)$totalUsersQuery->getSingleScalarResult(), - "errors" => [], - "message" => "No existing users found", - ); + $response = [ + 'success' => true, + 'legacyUsers' => (int) $legacyUsersQuery->getSingleScalarResult(), + 'totalUsers' => (int) $totalUsersQuery->getSingleScalarResult(), + 'errors' => [], + 'message' => 'No existing users found', + ]; if ($totalUsersQuery->getSingleScalarResult() > 0) { - $response["message"] = "Existing users found"; + $response['message'] = 'Existing users found'; } return new JsonResponse($response); diff --git a/src/PartKeepr/SetupBundle/Controller/FileMigrationController.php b/src/PartKeepr/SetupBundle/Controller/FileMigrationController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; @@ -9,17 +10,19 @@ use Symfony\Component\HttpFoundation\Response; class FileMigrationController extends SetupBaseController { /** - * Checks if there are existing userds in the database + * Checks if there are existing userds in the database. + * * @Route("/setup/migrateFiles") * * @param Request $request + * * @return Response */ public function migrateFilesAction(Request $request) { $this->dumpConfig($request); - $response = $this->handleRequest($request, "/setup/_int_migrate_files_action"); + $response = $this->handleRequest($request, '/setup/_int_migrate_files_action'); return new Response($response->getContent()); } @@ -33,58 +36,57 @@ class FileMigrationController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "No files to migrate", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'No files to migrate', + ]; - $legacyConfig = $this->get("partkeepr.setup.config_service")->legacyConfigParser(); + $legacyConfig = $this->get('partkeepr.setup.config_service')->legacyConfigParser(); - $legacyFilePath = $this->get("kernel")->getRootDir()."/../data/"; - $legacyImagePath = $this->get("kernel")->getRootDir()."/../data/images/"; + $legacyFilePath = $this->get('kernel')->getRootDir().'/../data/'; + $legacyImagePath = $this->get('kernel')->getRootDir().'/../data/images/'; - $legacyFileDirectories = array("FootprintAttachment", "PartAttachment", "ProjectAttachment"); + $legacyFileDirectories = ['FootprintAttachment', 'PartAttachment', 'ProjectAttachment']; - if (array_key_exists("partkeepr.files.path", $legacyConfig)) { - $legacyFilePath = $legacyConfig["partkeepr.files.path"]; + if (array_key_exists('partkeepr.files.path', $legacyConfig)) { + $legacyFilePath = $legacyConfig['partkeepr.files.path']; } - if (array_key_exists("partkeepr.images.path", $legacyConfig)) { - $legacyImagePath = $legacyConfig["partkeepr.images.path"]; + if (array_key_exists('partkeepr.images.path', $legacyConfig)) { + $legacyImagePath = $legacyConfig['partkeepr.images.path']; } - $newFilesPath = $legacyFilePath."/files/"; - $newImagesPath = $legacyFilePath."/images/"; + $newFilesPath = $legacyFilePath.'/files/'; + $newImagesPath = $legacyFilePath.'/images/'; if (!is_dir($newFilesPath)) { mkdir($newFilesPath, 0777, true); } - if (!is_dir($newImagesPath)) { mkdir($newImagesPath, 0777, true); } foreach ($legacyFileDirectories as $legacyFileDirectory) { - $legacyMovePath = $legacyFilePath."/".$legacyFileDirectory."/"; - $newMovePath = $legacyFilePath."/files/".$legacyFileDirectory."/"; + $legacyMovePath = $legacyFilePath.'/'.$legacyFileDirectory.'/'; + $newMovePath = $legacyFilePath.'/files/'.$legacyFileDirectory.'/'; if (is_dir($legacyMovePath)) { $this->moveFiles($legacyMovePath, $newMovePath); - $response["message"] = "Old image directories moved"; + $response['message'] = 'Old image directories moved'; } } - $legacyImageDirectories = array("footprint", "iclogo", "part", "storagelocation"); + $legacyImageDirectories = ['footprint', 'iclogo', 'part', 'storagelocation']; foreach ($legacyImageDirectories as $legacyImageDirectory) { - $legacyMovePath = $legacyImagePath."/".$legacyImageDirectory."/"; - $newMovePath = $legacyFilePath."/images/".$legacyImageDirectory."/"; + $legacyMovePath = $legacyImagePath.'/'.$legacyImageDirectory.'/'; + $newMovePath = $legacyFilePath.'/images/'.$legacyImageDirectory.'/'; if (is_dir($legacyMovePath)) { $this->moveFiles($legacyMovePath, $newMovePath); - $response["message"] = "Old image directories moved"; + $response['message'] = 'Old image directories moved'; } } @@ -101,9 +103,8 @@ class FileMigrationController extends SetupBaseController foreach ($iterator as $file) { if (!$file->isDot()) { - rename($file->getPathName(), $target."/".$file->getFilename()); + rename($file->getPathName(), $target.'/'.$file->getFilename()); } } } - } diff --git a/src/PartKeepr/SetupBundle/Controller/FootprintSetupController.php b/src/PartKeepr/SetupBundle/Controller/FootprintSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; @@ -17,18 +18,18 @@ class FootprintSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Default footprints successfully created", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Default footprints successfully created', + ]; try { - $this->get("partkeepr.setup.footprint_service")->importFootprints(); + $this->get('partkeepr.setup.footprint_service')->importFootprints(); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Footprint creation error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Footprint creation error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -41,9 +42,8 @@ class FootprintSetupController extends SetupBaseController */ public function createFootprintsAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_create_footprints"); + $response = $this->handleRequest($request, '/setup/_int_create_footprints'); return new Response($response->getContent()); } - } diff --git a/src/PartKeepr/SetupBundle/Controller/ManufacturerSetupController.php b/src/PartKeepr/SetupBundle/Controller/ManufacturerSetupController.php @@ -1,13 +1,12 @@ <?php -namespace PartKeepr\SetupBundle\Controller; +namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; - class ManufacturerSetupController extends SetupBaseController { /** @@ -19,18 +18,18 @@ class ManufacturerSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Default manufacturers successfully created", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Default manufacturers successfully created', + ]; try { - $this->get("partkeepr.setup.manufacturer_service")->importManufacturers(); + $this->get('partkeepr.setup.manufacturer_service')->importManufacturers(); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Manufacturers creation error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Manufacturers creation error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -38,12 +37,14 @@ class ManufacturerSetupController extends SetupBaseController /** * @Route("/setup/createManufacturers") + * * @param Request $request + * * @return Response */ public function createManufacturersAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_create_manufacturers"); + $response = $this->handleRequest($request, '/setup/_int_create_manufacturers'); return new Response($response->getContent()); } diff --git a/src/PartKeepr/SetupBundle/Controller/PartUnitSetupController.php b/src/PartKeepr/SetupBundle/Controller/PartUnitSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; @@ -10,12 +11,14 @@ class PartUnitSetupController extends SetupBaseController { /** * @Route("/setup/createPartUnits") + * * @param Request $request + * * @return Response */ public function createPartUnitsAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_create_part_units"); + $response = $this->handleRequest($request, '/setup/_int_create_part_units'); return new Response($response->getContent()); } @@ -29,21 +32,20 @@ class PartUnitSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Default part unit successfully created", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Default part unit successfully created', + ]; try { - $this->get("partkeepr.setup.part_unit_service")->setupDefaultPartUnit(); + $this->get('partkeepr.setup.part_unit_service')->setupDefaultPartUnit(); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Part unit setup error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Part unit setup error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); } - } diff --git a/src/PartKeepr/SetupBundle/Controller/SchemaMigrationSetupController.php b/src/PartKeepr/SetupBundle/Controller/SchemaMigrationSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Doctrine\Bundle\MigrationsBundle\Command\DoctrineCommand; @@ -20,11 +21,11 @@ class SchemaMigrationSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Database schema successfully migrated", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Database schema successfully migrated', + ]; $configuration = $this->getMigrationConfiguration(); $migration = new Migration($configuration); @@ -36,10 +37,9 @@ class SchemaMigrationSetupController extends SetupBaseController return new JsonResponse($response); } - protected function getMigrationConfiguration() { - $config = new Configuration($this->get("doctrine.dbal.default_connection")); + $config = new Configuration($this->get('doctrine.dbal.default_connection')); DoctrineCommand::configureMigrations($this->container, $config); @@ -51,10 +51,8 @@ class SchemaMigrationSetupController extends SetupBaseController */ public function migrateSchemaAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_migrate_schema"); + $response = $this->handleRequest($request, '/setup/_int_migrate_schema'); return new Response($response->getContent()); } - - } diff --git a/src/PartKeepr/SetupBundle/Controller/SchemaSetupController.php b/src/PartKeepr/SetupBundle/Controller/SchemaSetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Doctrine\ORM\Tools\SchemaTool; @@ -18,22 +19,22 @@ class SchemaSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Database successfully installed/updated", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Database successfully installed/updated', + ]; - $entityManager = $this->get("doctrine.orm.default_entity_manager"); + $entityManager = $this->get('doctrine.orm.default_entity_manager'); $schemaTool = new SchemaTool($entityManager); $metadatas = $entityManager->getMetadataFactory()->getAllMetadata(); try { $schemaTool->updateSchema($metadatas, true); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Database setup error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Database setup error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -44,7 +45,7 @@ class SchemaSetupController extends SetupBaseController */ public function setupSchemaAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_setup_schema"); + $response = $this->handleRequest($request, '/setup/_int_setup_schema'); return new Response($response->getContent()); } diff --git a/src/PartKeepr/SetupBundle/Controller/SetupBaseController.php b/src/PartKeepr/SetupBundle/Controller/SetupBaseController.php @@ -1,9 +1,10 @@ <?php + namespace PartKeepr\SetupBundle\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; class SetupBaseController extends Controller { @@ -17,39 +18,40 @@ class SetupBaseController extends Controller * * @return JsonResponse|\Symfony\Component\HttpFoundation\Response */ - protected function handleRequest(Request $request, $uri, $parameters = array(), $environment = "setup_test") + protected function handleRequest(Request $request, $uri, $parameters = [], $environment = 'setup_test') { $data = json_decode($request->getContent(), true); - if (!array_key_exists("authKey", $data) || !$this->verifyAuthKey($data["authKey"])) { - $response["success"] = false; - $response["message"] = "Invalid Authentication Key"; - $response["errors"] = array(); + if (!array_key_exists('authKey', $data) || !$this->verifyAuthKey($data['authKey'])) { + $response['success'] = false; + $response['message'] = 'Invalid Authentication Key'; + $response['errors'] = []; return new JsonResponse($response); } - $parameters["authKey"] = $data["authKey"]; + $parameters['authKey'] = $data['authKey']; try { $kernel = new \AppKernel($environment, true); - $internalRequest = Request::create($uri, "GET", $parameters); + $internalRequest = Request::create($uri, 'GET', $parameters); return $kernel->handle($internalRequest); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Generic Error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Generic Error'; + $response['errors'] = [$e->getMessage()]; return new JsonResponse($response); } } - protected function ensureAuthKey (Request $request) { + protected function ensureAuthKey(Request $request) + { $data = json_decode($request->getContent(), true); - if (!is_array($data) || !array_key_exists("authKey", $data) || !$this->verifyAuthKey($data["authKey"])) { - if ($request->query->has("authKey") && $this->verifyAuthKey($request->query->get("authKey"))) { + if (!is_array($data) || !array_key_exists('authKey', $data) || !$this->verifyAuthKey($data['authKey'])) { + if ($request->query->has('authKey') && $this->verifyAuthKey($request->query->get('authKey'))) { return true; } @@ -59,17 +61,18 @@ class SetupBaseController extends Controller } } - protected function getAuthKeyErrorResponse () { - $response["success"] = false; - $response["message"] = "Invalid Authentication Key"; - $response["errors"] = array(); + protected function getAuthKeyErrorResponse() + { + $response['success'] = false; + $response['message'] = 'Invalid Authentication Key'; + $response['errors'] = []; return new JsonResponse($response); } protected function verifyAuthKey($givenKey) { - $key = $this->get("partkeepr.setup.config_service")->getAuthKey(); + $key = $this->get('partkeepr.setup.config_service')->getAuthKey(); if ($key === $givenKey) { return true; @@ -82,9 +85,9 @@ class SetupBaseController extends Controller { $data = json_decode($request->getContent(), true); - $configService = $this->get("partkeepr.setup.config_service"); + $configService = $this->get('partkeepr.setup.config_service'); - $config = $configService->getConfig($data["values"]); + $config = $configService->getConfig($data['values']); file_put_contents($configService->getConfigPath($test), $config); } diff --git a/src/PartKeepr/SetupBundle/Controller/SetupController.php b/src/PartKeepr/SetupBundle/Controller/SetupController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Controller; use Doctrine\DBAL\Exception\DriverException; @@ -18,26 +19,26 @@ class SetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Connection successful", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Connection successful', + ]; try { - $this->get("doctrine.dbal.default_connection")->connect(); + $this->get('doctrine.dbal.default_connection')->connect(); } catch (DriverException $e) { - $response["success"] = false; - $response["message"] = "Connection Error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Connection Error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); } - /** * @Route("/setup/testConnectivity") + * * @param Request $request * * @return Response @@ -46,13 +47,14 @@ class SetupController extends SetupBaseController { $this->dumpConfig($request); - $response = $this->handleRequest($request, "/setup/_int_test_connectivity"); + $response = $this->handleRequest($request, '/setup/_int_test_connectivity'); return new Response($response->getContent()); } /** * @Route("/setup/saveConfig") + * * @param Request $request * * @return JsonResponse @@ -61,12 +63,11 @@ class SetupController extends SetupBaseController { $this->dumpConfig($request, false); - - $response = array( - "success" => true, - "errors" => [], - "message" => "Configuration saved successful", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Configuration saved successful', + ]; return new JsonResponse($response); } @@ -76,11 +77,11 @@ class SetupController extends SetupBaseController */ public function webserverTestAction() { - $response = array( - "success" => true, - "message" => "Web Server configuration OK", - "errors" => array(), - ); + $response = [ + 'success' => true, + 'message' => 'Web Server configuration OK', + 'errors' => [], + ]; return new JsonResponse($response); } @@ -90,20 +91,19 @@ class SetupController extends SetupBaseController */ public function generateAuthKeyAction() { - $response = array( - "success" => true, - "message" => "Auth key successfully generated", - "errors" => array(), - ); + $response = [ + 'success' => true, + 'message' => 'Auth key successfully generated', + 'errors' => [], + ]; - $parameters = array( - "authkey" => $this->get("partkeepr.setup.config_service")->generateSecret() - ); + $parameters = [ + 'authkey' => $this->get('partkeepr.setup.config_service')->generateSecret(), + ]; $contents = $this->container->get('templating')->render('PartKeeprSetupBundle::authkey.php.twig', $parameters); - file_put_contents($this->get("partkeepr.setup.config_service")->getAuthKeyPath(), $contents); + file_put_contents($this->get('partkeepr.setup.config_service')->getAuthKeyPath(), $contents); return new JsonResponse($response); } - } diff --git a/src/PartKeepr/SetupBundle/Controller/SiPrefixSetupController.php b/src/PartKeepr/SetupBundle/Controller/SiPrefixSetupController.php @@ -1,15 +1,12 @@ <?php - namespace PartKeepr\SetupBundle\Controller; - use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; - class SiPrefixSetupController extends SetupBaseController { /** @@ -21,18 +18,18 @@ class SiPrefixSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "SI Prefixes successfully created/updated", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'SI Prefixes successfully created/updated', + ]; try { - $this->get("partkeepr.setup.si_prefix_service")->importSiPrefixes(); + $this->get('partkeepr.setup.si_prefix_service')->importSiPrefixes(); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "SI Prefix creation error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'SI Prefix creation error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -40,15 +37,15 @@ class SiPrefixSetupController extends SetupBaseController /** * @Route("/setup/createSiPrefixes") + * * @param Request $request + * * @return Response */ public function createSiPrefixesAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_create_si_prefixes"); + $response = $this->handleRequest($request, '/setup/_int_create_si_prefixes'); return new Response($response->getContent()); } - - } diff --git a/src/PartKeepr/SetupBundle/Controller/UnitSetupController.php b/src/PartKeepr/SetupBundle/Controller/UnitSetupController.php @@ -1,6 +1,5 @@ <?php - namespace PartKeepr\SetupBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; @@ -19,18 +18,18 @@ class UnitSetupController extends SetupBaseController return $this->getAuthKeyErrorResponse(); } - $response = array( - "success" => true, - "errors" => [], - "message" => "Default units successfully created/updated", - ); + $response = [ + 'success' => true, + 'errors' => [], + 'message' => 'Default units successfully created/updated', + ]; try { - $this->get("partkeepr.setup.unit_service")->importUnits(); + $this->get('partkeepr.setup.unit_service')->importUnits(); } catch (\Exception $e) { - $response["success"] = false; - $response["message"] = "Unit creation error"; - $response["errors"] = [$e->getMessage()]; + $response['success'] = false; + $response['message'] = 'Unit creation error'; + $response['errors'] = [$e->getMessage()]; } return new JsonResponse($response); @@ -38,13 +37,14 @@ class UnitSetupController extends SetupBaseController /** * @Route("/setup/createUnits") + * * @param Request $request * * @return Response */ public function createUnitAction(Request $request) { - $response = $this->handleRequest($request, "/setup/_int_create_units"); + $response = $this->handleRequest($request, '/setup/_int_create_units'); return new Response($response->getContent()); } diff --git a/src/PartKeepr/SetupBundle/DependencyInjection/PartKeeprSetupExtension.php b/src/PartKeepr/SetupBundle/DependencyInjection/PartKeeprSetupExtension.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; @@ -7,7 +8,7 @@ use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ @@ -19,8 +20,7 @@ class PartKeeprSetupExtension extends Extension public function load(array $configs, ContainerBuilder $container) { $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - if ($container->getParameter("kernel.environment") !== "setup") { - + if ($container->getParameter('kernel.environment') !== 'setup') { $loader->load('setup_services.xml'); } diff --git a/src/PartKeepr/SetupBundle/PartKeeprSetupBundle.php b/src/PartKeepr/SetupBundle/PartKeeprSetupBundle.php @@ -1,9 +1,9 @@ <?php + namespace PartKeepr\SetupBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprSetupBundle extends Bundle { - } diff --git a/src/PartKeepr/SetupBundle/Services/ConfigSetupService.php b/src/PartKeepr/SetupBundle/Services/ConfigSetupService.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\SetupBundle\Services; +namespace PartKeepr\SetupBundle\Services; use PartKeepr\SetupBundle\Visitor\ConfigVisitor; use PartKeepr\SetupBundle\Visitor\LegacyConfigVisitor; @@ -9,7 +9,7 @@ use Symfony\Bundle\TwigBundle\TwigEngine; class ConfigSetupService { /** - * The authentification key length + * The authentification key length. */ const KEY_LENGTH = 32; @@ -31,75 +31,75 @@ class ConfigSetupService public function getConfig($config) { // Parameter defaults to ensure they exist - $parameters = array( - "database_driver" => null, - "database_host" => null, - "database_port" => null, - "database_name" => null, - "database_password" => null, - - "mailer_transport" => null, - "mailer_host" => null, - "mailer_port" => null, - "mailer_encryption" => null, - "mailer_user" => null, - "mailer_password" => null, - "mailer_auth_mode" => null, - - "authentication_provider" => "PartKeepr.Auth.HTTPBasicAuthenticationProvider", - - "locale" => "en", - - "secret" => $this->generateSecret(), - - "fr3d_ldap.driver.host" => "127.0.0.1", - "fr3d_ldap.driver.port" => 389, - "fr3d_ldap.driver.username" => null, - "fr3d_ldap.driver.password" => null, - "fr3d_ldap.driver.bindRequiresDn" => false, - "fr3d_ldap.driver.baseDn" => "", - "fr3d_ldap.driver.accountFilterFormat" => null, - "fr3d_ldap.driver.optReferrals" => null, - "fr3d_ldap.driver.useSsl" => null, - "fr3d_ldap.driver.useStartTls" => null, - "fr3d_ldap.driver.accountCanonicalForm" => null, - "fr3d_ldap.driver.accountDomainName" => null, - "fr3d_ldap.driver.accountDomainNameShort" => null, - "fr3d_ldap.user.enabled" => false, - "fr3d_ldap.user.baseDn" => "dc=example,dc=com", - "fr3d_ldap.user.filter" => null, - "fr3d_ldap.user.attribute.username" => "samaccountname", - "fr3d_ldap.user.attribute.email" => "email", - - "partkeepr.filesystem.data_directory" => "%kernel.root_dir%/../data/", - "partkeepr.cronjob.check" => true, - "partkeepr.filesystem.quota" => false, - "partkeepr.auth.max_users" => "unlimited", - "partkeepr.category.path_separator" => " ➤ ", - "partkeepr.maintenance" => false, - "partkeepr.maintenance.title" => "", - "partkeepr.maintenance.message" => "", - "cache.dunglas" => false, - "cache.doctrine" => "array", - "partkeepr.parts.limit" => false, - "partkeepr.users.limit" => false, - ); - - if (function_exists("apc_fetch")) { - $parameters["cache.dunglas"] = "api.mapping.cache.apc"; - $parameters["cache.doctrine"] = "apc"; + $parameters = [ + 'database_driver' => null, + 'database_host' => null, + 'database_port' => null, + 'database_name' => null, + 'database_password' => null, + + 'mailer_transport' => null, + 'mailer_host' => null, + 'mailer_port' => null, + 'mailer_encryption' => null, + 'mailer_user' => null, + 'mailer_password' => null, + 'mailer_auth_mode' => null, + + 'authentication_provider' => 'PartKeepr.Auth.HTTPBasicAuthenticationProvider', + + 'locale' => 'en', + + 'secret' => $this->generateSecret(), + + 'fr3d_ldap.driver.host' => '127.0.0.1', + 'fr3d_ldap.driver.port' => 389, + 'fr3d_ldap.driver.username' => null, + 'fr3d_ldap.driver.password' => null, + 'fr3d_ldap.driver.bindRequiresDn' => false, + 'fr3d_ldap.driver.baseDn' => '', + 'fr3d_ldap.driver.accountFilterFormat' => null, + 'fr3d_ldap.driver.optReferrals' => null, + 'fr3d_ldap.driver.useSsl' => null, + 'fr3d_ldap.driver.useStartTls' => null, + 'fr3d_ldap.driver.accountCanonicalForm' => null, + 'fr3d_ldap.driver.accountDomainName' => null, + 'fr3d_ldap.driver.accountDomainNameShort' => null, + 'fr3d_ldap.user.enabled' => false, + 'fr3d_ldap.user.baseDn' => 'dc=example,dc=com', + 'fr3d_ldap.user.filter' => null, + 'fr3d_ldap.user.attribute.username' => 'samaccountname', + 'fr3d_ldap.user.attribute.email' => 'email', + + 'partkeepr.filesystem.data_directory' => '%kernel.root_dir%/../data/', + 'partkeepr.cronjob.check' => true, + 'partkeepr.filesystem.quota' => false, + 'partkeepr.auth.max_users' => 'unlimited', + 'partkeepr.category.path_separator' => ' ➤ ', + 'partkeepr.maintenance' => false, + 'partkeepr.maintenance.title' => '', + 'partkeepr.maintenance.message' => '', + 'cache.dunglas' => false, + 'cache.doctrine' => 'array', + 'partkeepr.parts.limit' => false, + 'partkeepr.users.limit' => false, + ]; + + if (function_exists('apc_fetch')) { + $parameters['cache.dunglas'] = 'api.mapping.cache.apc'; + $parameters['cache.doctrine'] = 'apc'; } $this->applyIf($parameters, $config); $parameters = array_merge($parameters, $config); - if ($parameters["fr3d_ldap.user.attribute.username"] === null) { - $parameters["fr3d_ldap.user.attribute.username"] = "samaccountname"; + if ($parameters['fr3d_ldap.user.attribute.username'] === null) { + $parameters['fr3d_ldap.user.attribute.username'] = 'samaccountname'; } - if ($parameters["fr3d_ldap.user.attribute.email"] === null) { - $parameters["fr3d_ldap.user.attribute.email"] = "email"; + if ($parameters['fr3d_ldap.user.attribute.email'] === null) { + $parameters['fr3d_ldap.user.attribute.email'] = 'email'; } array_walk_recursive($parameters, function (&$item) { @@ -109,7 +109,7 @@ class ConfigSetupService ksort($parameters); return $this->twig->render('PartKeeprSetupBundle::parameters.php.twig', - array("parameters" => $parameters)); + ['parameters' => $parameters]); } public function legacyConfigParser() @@ -124,7 +124,7 @@ class ConfigSetupService return LegacyConfigVisitor::getConfigValues(); } - return array(); + return []; } public function configParser() @@ -139,23 +139,23 @@ class ConfigSetupService return ConfigVisitor::getConfigValues(); } - return array(); + return []; } public function getConfigPath($test) { if ($test) { - $filename = "parameters_setup.php"; + $filename = 'parameters_setup.php'; } else { - $filename = "parameters.php"; + $filename = 'parameters.php'; } - return dirname(__FILE__)."/../../../../app/config/".$filename; + return dirname(__FILE__).'/../../../../app/config/'.$filename; } public function getLegacyConfigPath() { - return dirname(__FILE__)."/../../../../config.php"; + return dirname(__FILE__).'/../../../../config.php'; } public function applyIf($target, $source) @@ -171,7 +171,7 @@ class ConfigSetupService public function generateSecret() { - $secret = ""; + $secret = ''; for ($i = 0; $i < self::KEY_LENGTH; $i++) { $secret .= chr(65 + rand(0, 16)); } @@ -179,17 +179,18 @@ class ConfigSetupService return $secret; } - public function getAuthKey () { - $findText = "Your auth key is: "; + public function getAuthKey() + { + $findText = 'Your auth key is: '; $data = file_get_contents($this->getAuthKeyPath()); $position = strpos($data, $findText); - return substr($data, $position + strlen($findText), ConfigSetupService::KEY_LENGTH); + return substr($data, $position + strlen($findText), self::KEY_LENGTH); } public function getAuthKeyPath() { - return dirname(__FILE__)."/../../../../app/authkey.php"; + return dirname(__FILE__).'/../../../../app/authkey.php'; } } diff --git a/src/PartKeepr/SetupBundle/Services/FootprintSetupService.php b/src/PartKeepr/SetupBundle/Services/FootprintSetupService.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\SetupBundle\Services; +namespace PartKeepr\SetupBundle\Services; use Doctrine\ORM\EntityManager; use PartKeepr\CategoryBundle\Services\CategoryService; @@ -14,8 +14,8 @@ use Symfony\Component\Yaml\Parser; class FootprintSetupService { - const FOOTPRINT_PATH = "@PartKeeprSetupBundle/Resources/setup-data/footprints/"; - const FOOTPRINT_DATA = "footprints.yml"; + const FOOTPRINT_PATH = '@PartKeeprSetupBundle/Resources/setup-data/footprints/'; + const FOOTPRINT_DATA = 'footprints.yml'; /** * @var EntityManager @@ -50,7 +50,7 @@ class FootprintSetupService } /** - * Imports the existing footprints. Skips existing footprints + * Imports the existing footprints. Skips existing footprints. * * @return array An array with the keys "skipped" and "imported" which contain the number of footprints skipped and imported */ @@ -76,35 +76,34 @@ class FootprintSetupService $this->entityManager->flush(); - return array("skipped" => $skipped, "imported" => $count); + return ['skipped' => $skipped, 'imported' => $count]; } protected function createFootprint($footprintName, $footprintData) { /** - * @var FootprintCategory $footprintCategoryRootNode + * @var FootprintCategory */ $footprintCategoryRootNode = $this->footprintCategoryService->getRootNode(); $footprint = new Footprint(); $footprint->setName($footprintName); - if (array_key_exists("description", $footprintData)) { - $footprint->setDescription($footprintData["description"]); + if (array_key_exists('description', $footprintData)) { + $footprint->setDescription($footprintData['description']); } - if (array_key_exists("category", $footprintData)) { - $footprintCategory = $this->addFootprintCategoryPath(explode("/", $footprintData["category"]), + if (array_key_exists('category', $footprintData)) { + $footprintCategory = $this->addFootprintCategoryPath(explode('/', $footprintData['category']), $footprintCategoryRootNode); $footprint->setCategory($footprintCategory); } - if (array_key_exists("image", $footprintData)) { + if (array_key_exists('image', $footprintData)) { $footprintImage = new FootprintImage(); - - $file = $this->kernel->locateResource(self::FOOTPRINT_PATH.$footprintData["image"]); + $file = $this->kernel->locateResource(self::FOOTPRINT_PATH.$footprintData['image']); $this->uploadedFileService->replaceFromFilesystem($footprintImage, new File($file)); $footprint->setImage($footprintImage); @@ -114,14 +113,14 @@ class FootprintSetupService } /** - * Creates a node structure for the given path + * Creates a node structure for the given path. * * @param $path array The components of the path * @param $parentNode FootprintCategory The parent node * * @return FootprintCategory */ - protected function addFootprintCategoryPath(Array $path, FootprintCategory $parentNode) + protected function addFootprintCategoryPath(array $path, FootprintCategory $parentNode) { if (count($path) == 0) { return $parentNode; @@ -149,17 +148,17 @@ class FootprintSetupService } /** - * Checks if the specified footprint exists + * Checks if the specified footprint exists. * * @param string $name The footprint name * - * @return boolean true if the footprints exists, false otherwise + * @return bool true if the footprints exists, false otherwise */ protected function footprintExists($name) { $dql = "SELECT COUNT(fp) FROM PartKeepr\FootprintBundle\Entity\Footprint fp WHERE fp.name = :name"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("name", $name); + $query->setParameter('name', $name); if ($query->getSingleScalarResult() == 0) { return false; diff --git a/src/PartKeepr/SetupBundle/Services/ManufacturerSetupService.php b/src/PartKeepr/SetupBundle/Services/ManufacturerSetupService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Services; use Doctrine\ORM\EntityManager; @@ -11,8 +12,8 @@ use Symfony\Component\Yaml\Parser; class ManufacturerSetupService { - const MANUFACTURER_PATH = "@PartKeeprSetupBundle/Resources/setup-data/manufacturers/"; - const MANUFACTURER_DATA = "manufacturers.yml"; + const MANUFACTURER_PATH = '@PartKeeprSetupBundle/Resources/setup-data/manufacturers/'; + const MANUFACTURER_DATA = 'manufacturers.yml'; /** * @var EntityManager @@ -53,7 +54,6 @@ class ManufacturerSetupService $yaml = new Parser(); $data = $yaml->parse(file_get_contents($path)); - foreach ($data as $manufacturerName => $manufacturerData) { if ($this->manufacturerExists($manufacturerName)) { $skipped++; @@ -66,7 +66,7 @@ class ManufacturerSetupService $this->entityManager->flush(); - return array("skipped" => $skipped, "imported" => $count); + return ['skipped' => $skipped, 'imported' => $count]; } protected function createManufacturer($manufacturerName, $manufacturerData) @@ -74,9 +74,8 @@ class ManufacturerSetupService $manufacturer = new Manufacturer(); $manufacturer->setName($manufacturerName); - if (array_key_exists("iclogos", $manufacturerData)) { - - foreach ($manufacturerData["iclogos"] as $icLogo) { + if (array_key_exists('iclogos', $manufacturerData)) { + foreach ($manufacturerData['iclogos'] as $icLogo) { $manufacturerIcLogo = new ManufacturerICLogo(); $file = $this->kernel->locateResource(self::MANUFACTURER_PATH.$icLogo); @@ -89,9 +88,8 @@ class ManufacturerSetupService $this->entityManager->persist($manufacturer); } - /** - * Checks if the specified manufacturer exists + * Checks if the specified manufacturer exists. * * @param string $name The manufacturer name * @@ -101,7 +99,7 @@ class ManufacturerSetupService { $dql = "SELECT COUNT(m) FROM PartKeepr\ManufacturerBundle\Entity\Manufacturer m WHERE m.name = :name"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("name", $name); + $query->setParameter('name', $name); if ($query->getSingleScalarResult() == 0) { return false; diff --git a/src/PartKeepr/SetupBundle/Services/PartUnitSetupService.php b/src/PartKeepr/SetupBundle/Services/PartUnitSetupService.php @@ -1,9 +1,7 @@ <?php - namespace PartKeepr\SetupBundle\Services; - use Doctrine\ORM\EntityManager; use PartKeepr\PartBundle\Entity\PartMeasurementUnit; @@ -21,24 +19,25 @@ class PartUnitSetupService } /** - * Sets up the default part unit (pieces) if it doesn't exist - * @return boolean True if a default unit was created, false if it already exists + * Sets up the default part unit (pieces) if it doesn't exist. + * + * @return bool True if a default unit was created, false if it already exists */ public function setupDefaultPartUnit() { - $dql = "SELECT COUNT(p) FROM PartKeepr\PartBundle\Entity\PartMeasurementUnit p WHERE p.default = :default"; $query = $this->entityManager->createQuery($dql); - $query->setParameter("default", true); + $query->setParameter('default', true); if ($query->getSingleScalarResult() == 0) { $partUnit = new PartMeasurementUnit(); - $partUnit->setName("Pieces"); - $partUnit->setShortName("pcs"); + $partUnit->setName('Pieces'); + $partUnit->setShortName('pcs'); $partUnit->setDefault(true); $this->entityManager->persist($partUnit); $this->entityManager->flush(); + return true; } else { return false; diff --git a/src/PartKeepr/SetupBundle/Services/SiPrefixSetupService.php b/src/PartKeepr/SetupBundle/Services/SiPrefixSetupService.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\SetupBundle\Services; +namespace PartKeepr\SetupBundle\Services; use Doctrine\ORM\EntityManager; use PartKeepr\SiPrefixBundle\Entity\SiPrefix; @@ -9,8 +9,8 @@ use Symfony\Component\Yaml\Parser; class SiPrefixSetupService { - const SIPREFIX_PATH = "@PartKeeprSetupBundle/Resources/setup-data/"; - const SIPREFIX_DATA = "siprefixes.yml"; + const SIPREFIX_PATH = '@PartKeeprSetupBundle/Resources/setup-data/'; + const SIPREFIX_DATA = 'siprefixes.yml'; /** * @var EntityManager @@ -59,19 +59,19 @@ class SiPrefixSetupService $count++; } - $prefix->setExponent($prefixData["exponent"]); - $prefix->setSymbol($prefixData["symbol"]); - $prefix->setBase($prefixData["base"]); + $prefix->setExponent($prefixData['exponent']); + $prefix->setSymbol($prefixData['symbol']); + $prefix->setBase($prefixData['base']); $updated++; } $this->entityManager->flush(); - return array("updated" => $updated-$count, "imported" => $count); + return ['updated' => $updated - $count, 'imported' => $count]; } /** - * Finds an SI Prefix by name + * Finds an SI Prefix by name. * * @param string $name The SI Prefix name * @@ -79,8 +79,8 @@ class SiPrefixSetupService */ protected function getSiPrefix($name) { - $repository = $this->entityManager->getRepository("PartKeeprSiPrefixBundle:SiPrefix"); + $repository = $this->entityManager->getRepository('PartKeeprSiPrefixBundle:SiPrefix'); - return $repository->findOneBy(array("prefix" => $name)); + return $repository->findOneBy(['prefix' => $name]); } } diff --git a/src/PartKeepr/SetupBundle/Services/UnitSetupService.php b/src/PartKeepr/SetupBundle/Services/UnitSetupService.php @@ -1,6 +1,5 @@ <?php - namespace PartKeepr\SetupBundle\Services; use Doctrine\ORM\EntityManager; @@ -11,8 +10,8 @@ use Symfony\Component\Yaml\Parser; class UnitSetupService { - const UNIT_PATH = "@PartKeeprSetupBundle/Resources/setup-data/"; - const UNIT_DATA = "units.yml"; + const UNIT_PATH = '@PartKeeprSetupBundle/Resources/setup-data/'; + const UNIT_DATA = 'units.yml'; /** * @var EntityManager @@ -39,8 +38,9 @@ class UnitSetupService /** * Imports units. * - * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported * @throws \Exception If an error occured + * + * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported */ public function importUnits() { @@ -58,17 +58,17 @@ class UnitSetupService if ($unit === null) { $unit = new Unit(); $unit->setName($unitName); - $unit->setSymbol($unitData["symbol"]); + $unit->setSymbol($unitData['symbol']); - if (array_key_exists("prefixes", $unitData)) { - if (!is_array($unitData["prefixes"])) { + if (array_key_exists('prefixes', $unitData)) { + if (!is_array($unitData['prefixes'])) { throw new \Exception($unitName." doesn't contain a prefix list, or the prefix list is not an array."); } - foreach ($unitData["prefixes"] as $name) { + foreach ($unitData['prefixes'] as $name) { $prefix = $this->getSiPrefix($name); if ($prefix === null) { - throw new \Exception("Unable to find SI Prefix ".$name); + throw new \Exception('Unable to find SI Prefix '.$name); } $unit->getPrefixes()->add($prefix); @@ -82,24 +82,25 @@ class UnitSetupService } } - return array("imported" => $count, "skipped" => $skipped); + return ['imported' => $count, 'skipped' => $skipped]; } /** - * Checks if the specified SI Prefix + * Checks if the specified SI Prefix. * * @param string $name The footprint name + * * @return Unit|null */ protected function getUnit($name) { - $repository = $this->entityManager->getRepository("PartKeeprUnitBundle:Unit"); + $repository = $this->entityManager->getRepository('PartKeeprUnitBundle:Unit'); - return $repository->findOneBy(array("name" => $name)); + return $repository->findOneBy(['name' => $name]); } /** - * Finds an SI Prefix by name + * Finds an SI Prefix by name. * * @param string $name The SI Prefix name * @@ -107,8 +108,8 @@ class UnitSetupService */ protected function getSiPrefix($name) { - $repository = $this->entityManager->getRepository("PartKeeprSiPrefixBundle:SiPrefix"); + $repository = $this->entityManager->getRepository('PartKeeprSiPrefixBundle:SiPrefix'); - return $repository->findOneBy(array("prefix" => $name)); + return $repository->findOneBy(['prefix' => $name]); } } diff --git a/src/PartKeepr/SetupBundle/Tests/ExistingUsersSetupTest.php b/src/PartKeepr/SetupBundle/Tests/ExistingUsersSetupTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\SetupBundle\Tests; use PartKeepr\CoreBundle\Tests\SetupWebTestCase; @@ -7,49 +8,48 @@ class ExistingUsersSetupTest extends SetupWebTestCase { public function setUp() { - $this->loadFixtures(array()); + $this->loadFixtures([]); } - public function testExistingUsers() { - $this->markTestSkipped("Setup tests requires setup refactoring, skipping"); + $this->markTestSkipped('Setup tests requires setup refactoring, skipping'); $authKey = $this->generateAndGetAuthKey(); $configuration = $this->getConfiguration($authKey); $client = static::makeClient(); - $parameters = array(); + $parameters = []; // First test: Ensure invalid auth key is returned $client->request( 'GET', '/setup/testExistingUsers', - array(), - array(), - array(), + [], + [], + [], json_encode($parameters) ); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $data = json_decode($client->getResponse()->getContent(), true); - $this->assertArrayHasKey("success", $data); - $this->assertArrayHasKey("errors", $data); - $this->assertArrayHasKey("message", $data); + $this->assertArrayHasKey('success', $data); + $this->assertArrayHasKey('errors', $data); + $this->assertArrayHasKey('message', $data); - $this->assertFalse($data["success"]); - $this->assertEquals("Invalid Authentication Key", $data["message"]); + $this->assertFalse($data['success']); + $this->assertEquals('Invalid Authentication Key', $data['message']); - $parameters["authKey"] = $authKey; - $parameters["values"] = $configuration; + $parameters['authKey'] = $authKey; + $parameters['values'] = $configuration; $client->request( 'GET', '/setup/testExistingUsers', - array(), - array(), - array(), + [], + [], + [], json_encode($parameters) ); @@ -57,15 +57,15 @@ class ExistingUsersSetupTest extends SetupWebTestCase $data = json_decode($client->getResponse()->getContent(), true); - $this->assertArrayHasKey("success", $data); - $this->assertArrayHasKey("legacyUsers", $data); - $this->assertArrayHasKey("totalUsers", $data); - $this->assertArrayHasKey("errors", $data); - $this->assertArrayHasKey("message", $data); + $this->assertArrayHasKey('success', $data); + $this->assertArrayHasKey('legacyUsers', $data); + $this->assertArrayHasKey('totalUsers', $data); + $this->assertArrayHasKey('errors', $data); + $this->assertArrayHasKey('message', $data); - $this->assertTrue($data["success"]); - $this->assertEquals(0, $data["legacyUsers"]); - $this->assertEquals(0, $data["totalUsers"]); - $this->assertEquals(0, count($data["errors"])); + $this->assertTrue($data['success']); + $this->assertEquals(0, $data['legacyUsers']); + $this->assertEquals(0, $data['totalUsers']); + $this->assertEquals(0, count($data['errors'])); } } diff --git a/src/PartKeepr/SetupBundle/Visitor/ConfigVisitor.php b/src/PartKeepr/SetupBundle/Visitor/ConfigVisitor.php @@ -1,14 +1,15 @@ <?php -namespace PartKeepr\SetupBundle\Visitor; +namespace PartKeepr\SetupBundle\Visitor; class ConfigVisitor extends \PHPParser_NodeVisitorAbstract { - private static $configValues = array(); + private static $configValues = []; - public function enterNode(\PHPParser_Node $node) { + public function enterNode(\PHPParser_Node $node) + { if ($node instanceof \PHPParser_Node_Expr_MethodCall) { - if ($node->var->name == "container" && $node->name == "setParameter") { + if ($node->var->name == 'container' && $node->name == 'setParameter') { if (array_key_exists(0, $node->args) && array_key_exists(1, $node->args)) { if ($node->args[1]->value instanceof \PHPParser_Node_Scalar_String) { self::$configValues[$node->args[0]->value->value] = $node->args[1]->value->value; @@ -16,13 +17,13 @@ class ConfigVisitor extends \PHPParser_NodeVisitorAbstract self::$configValues[$node->args[0]->value->value] = $node->args[1]->value->value; } elseif ($node->args[1]->value instanceof \PHPParser_Node_Expr_ConstFetch) { switch (strtolower($node->args[1]->value->name->parts[0])) { - case "true": + case 'true': $value = true; break; - case "false": + case 'false': $value = false; break; - case "null": + case 'null': $value = null; break; } @@ -30,11 +31,11 @@ class ConfigVisitor extends \PHPParser_NodeVisitorAbstract } } } - } } - public static function getConfigValues () { + public static function getConfigValues() + { return self::$configValues; } } diff --git a/src/PartKeepr/SetupBundle/Visitor/LegacyConfigVisitor.php b/src/PartKeepr/SetupBundle/Visitor/LegacyConfigVisitor.php @@ -1,17 +1,16 @@ <?php -namespace PartKeepr\SetupBundle\Visitor; +namespace PartKeepr\SetupBundle\Visitor; class LegacyConfigVisitor extends \PHPParser_NodeVisitorAbstract { - private static $configValues = array(); + private static $configValues = []; - public function enterNode(\PHPParser_Node $node) { + public function enterNode(\PHPParser_Node $node) + { if ($node instanceof \PHPParser_Node_Expr_StaticCall) { - - if ($node->class->parts[0] == "Configuration" && $node->name == "setOption") { + if ($node->class->parts[0] == 'Configuration' && $node->name == 'setOption') { if (array_key_exists(0, $node->args) && array_key_exists(1, $node->args)) { - if ($node->args[1]->value instanceof \PHPParser_Node_Scalar_String) { self::$configValues[$node->args[0]->value->value] = $node->args[1]->value->value; } elseif ($node->args[1]->value instanceof \PHPParser_Node_Scalar_LNumber) { @@ -21,11 +20,11 @@ class LegacyConfigVisitor extends \PHPParser_NodeVisitorAbstract } } } - } } - public static function getConfigValues () { + public static function getConfigValues() + { return self::$configValues; } } diff --git a/src/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php b/src/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php @@ -1,14 +1,15 @@ <?php + namespace PartKeepr\SiPrefixBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; /** - * Represents an SI Prefix + * Represents an SI Prefix. * * @link http://en.wikipedia.org/wiki/Metric_prefix * @@ -18,44 +19,48 @@ use Symfony\Component\Validator\Constraints as Assert; class SiPrefix extends BaseEntity { /** - * The prefix name of the Si-Prefix (e.g. yotta, deca, deci, centi) + * The prefix name of the Si-Prefix (e.g. yotta, deca, deci, centi). * * @ORM\Column(type="string") * * @Assert\Type(type="string") * @Assert\NotBlank(message="siprefix.prefix.not_blank") + * * @var string * @Groups({"default"}) */ private $prefix; /** - * The symbol of the Si-Prefix (e.g. m, M, G) + * The symbol of the Si-Prefix (e.g. m, M, G). * * @ORM\Column(type="string",length=2) * * @Assert\Type(type="string") * @Groups({"default"}) + * * @var string */ private $symbol; /** - * The exponent of the Si-Prefix (e.g. milli = 10^-3) + * The exponent of the Si-Prefix (e.g. milli = 10^-3). * * @ORM\Column(type="integer") * @Assert\Type(type="integer") * @Groups({"default"}) + * * @var int */ private $exponent; /** - * The base of the Si-Prefix (e.g. 2^-3) + * The base of the Si-Prefix (e.g. 2^-3). * * @ORM\Column(type="integer") * @Assert\Type(type="integer") * @Groups({"default"}) + * * @var int */ private $base; @@ -71,7 +76,7 @@ class SiPrefix extends BaseEntity } /** - * Returns the prefix name + * Returns the prefix name. * * * @return string The prefix name @@ -82,7 +87,7 @@ class SiPrefix extends BaseEntity } /** - * Sets the symbol for the prefix + * Sets the symbol for the prefix. * * @param string $symbol The symbol */ @@ -92,7 +97,7 @@ class SiPrefix extends BaseEntity } /** - * Returns the symbol for the prefix + * Returns the symbol for the prefix. * * @return string The symbol */ @@ -102,7 +107,7 @@ class SiPrefix extends BaseEntity } /** - * Sets the exponent + * Sets the exponent. * * @param int $exponent The exponent */ @@ -112,7 +117,7 @@ class SiPrefix extends BaseEntity } /** - * Returns the exponent + * Returns the exponent. * * @return int The exponent */ @@ -122,7 +127,7 @@ class SiPrefix extends BaseEntity } /** - * Sets the base + * Sets the base. * * @param int $base The base */ @@ -132,7 +137,7 @@ class SiPrefix extends BaseEntity } /** - * Returns the base + * Returns the base. * * @return int The base */ @@ -142,7 +147,7 @@ class SiPrefix extends BaseEntity } /** - * Calculates the product for a given value + * Calculates the product for a given value. * * @param $value float The value to calculate the product * diff --git a/src/PartKeepr/SiPrefixBundle/PartKeeprSiPrefixBundle.php b/src/PartKeepr/SiPrefixBundle/PartKeeprSiPrefixBundle.php @@ -1,8 +1,9 @@ <?php + namespace PartKeepr\SiPrefixBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprSiPrefixBundle extends Bundle { -}- \ No newline at end of file +} diff --git a/src/PartKeepr/SiPrefixBundle/Tests/Model/SiPrefixTest.php b/src/PartKeepr/SiPrefixBundle/Tests/Model/SiPrefixTest.php @@ -1,26 +1,30 @@ <?php + namespace PartKeepr\SiPrefixBundle\Tests\Model; use PartKeepr\SiPrefixBundle\Entity\SiPrefix; -class SiPrefixTest extends \PHPUnit_Framework_TestCase { - - public function testPrefix () { +class SiPrefixTest extends \PHPUnit_Framework_TestCase +{ + public function testPrefix() + { $siPrefix = $this->getSiPrefix(); - $siPrefix->setPrefix("yotta"); - $this->assertEquals("yotta", $siPrefix->getPrefix()); + $siPrefix->setPrefix('yotta'); + $this->assertEquals('yotta', $siPrefix->getPrefix()); } - public function testSymbol () { + public function testSymbol() + { $siPrefix = $this->getSiPrefix(); - $siPrefix->setSymbol("µ"); + $siPrefix->setSymbol('µ'); - $this->assertEquals("µ", $siPrefix->getSymbol()); + $this->assertEquals('µ', $siPrefix->getSymbol()); } - public function testBase () { + public function testBase() + { $siPrefix = $this->getSiPrefix(); $siPrefix->setBase(10); @@ -28,24 +32,26 @@ class SiPrefixTest extends \PHPUnit_Framework_TestCase { $this->assertEquals(10, $siPrefix->getBase()); } - public function testExponent () { + public function testExponent() + { $siPrefix = $this->getSiPrefix(); $siPrefix->setExponent(10); $this->assertEquals(10, $siPrefix->getExponent()); } - public function testCalculation () { + public function testCalculation() + { $siPrefix = $this->getSiPrefix(); $siPrefix->setBase(10); $siPrefix->setExponent(2); $this->assertEquals(310, $siPrefix->calculateProduct(3.1)); - - } - private function getSiPrefix () { + + private function getSiPrefix() + { return new SiPrefix(); } -}- \ No newline at end of file +} diff --git a/src/PartKeepr/StatisticBundle/Command/CreateStatisticSnapshotCommand.php b/src/PartKeepr/StatisticBundle/Command/CreateStatisticSnapshotCommand.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StatisticBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -11,12 +12,12 @@ class CreateStatisticSnapshotCommand extends ContainerAwareCommand { parent::configure(); $this->setName('partkeepr:cron:create-statistic-snapshot'); - $this->setDescription("Creates a statistic snapshot"); + $this->setDescription('Creates a statistic snapshot'); } public function execute(InputInterface $input, OutputInterface $output) { - $this->getContainer()->get("partkeepr.statistic.service")->createStatisticSnapshot(); - $this->getContainer()->get("partkeepr.cronlogger_service")->markCronRun("partkeepr:cron:create-statistic-snapshot"); + $this->getContainer()->get('partkeepr.statistic.service')->createStatisticSnapshot(); + $this->getContainer()->get('partkeepr.cronlogger_service')->markCronRun('partkeepr:cron:create-statistic-snapshot'); } } diff --git a/src/PartKeepr/StatisticBundle/Controller/StatisticController.php b/src/PartKeepr/StatisticBundle/Controller/StatisticController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StatisticBundle\Controller; use FOS\RestBundle\Controller\Annotations\QueryParam; @@ -10,7 +11,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration as Routing; class StatisticController extends FOSRestController { /** - * Returns the current system statistics + * Returns the current system statistics. * * @Routing\Route("/api/statistics/current", defaults={"method" = "get","_format" = "json"}) * @View() @@ -19,22 +20,22 @@ class StatisticController extends FOSRestController */ public function getCurrentStatisticAction() { - $statisticService = $this->get("partkeepr.statistic.service"); + $statisticService = $this->get('partkeepr.statistic.service'); - $aData = array(); - $aData["partCount"] = $statisticService->getPartCount(); - $aData["partCategoryCount"] = $statisticService->getPartCategoryCount(); - $aData["totalPrice"] = $statisticService->getTotalPrice(); - $aData["averagePrice"] = $statisticService->getAveragePrice(); - $aData["partsWithPrice"] = $statisticService->getPartCount(true); - $aData["partsWithoutPrice"] = $aData["partCount"] - $aData["partsWithPrice"]; - $aData["units"] = $statisticService->getUnitCounts(); + $aData = []; + $aData['partCount'] = $statisticService->getPartCount(); + $aData['partCategoryCount'] = $statisticService->getPartCategoryCount(); + $aData['totalPrice'] = $statisticService->getTotalPrice(); + $aData['averagePrice'] = $statisticService->getAveragePrice(); + $aData['partsWithPrice'] = $statisticService->getPartCount(true); + $aData['partsWithoutPrice'] = $aData['partCount'] - $aData['partsWithPrice']; + $aData['units'] = $statisticService->getUnitCounts(); return $aData; } - /** - * Returns the sampled statistics for a given period + /** + * Returns the sampled statistics for a given period. * * @QueryParam(name="start") * @QueryParam(name="end") @@ -42,24 +43,27 @@ class StatisticController extends FOSRestController * @View() * * @param ParamFetcher $paramFetcher + * * @return array */ - public function getSampledStatisticAction (ParamFetcher $paramFetcher) { - $start = new \DateTime($paramFetcher->get("start")); - $end = new \DateTime($paramFetcher->get("end")); - return $this->get("partkeepr.statistic.service")->getSampledStatistics($start, $end); + public function getSampledStatisticAction(ParamFetcher $paramFetcher) + { + $start = new \DateTime($paramFetcher->get('start')); + $end = new \DateTime($paramFetcher->get('end')); + + return $this->get('partkeepr.statistic.service')->getSampledStatistics($start, $end); } /** - * Returns the range in which statistics are available + * Returns the range in which statistics are available. * * @Routing\Route("/api/statistics/range", defaults={"method" = "get","_format" = "json"}) * @View() * * @return array */ - public function getStatisticRangeAction () { - return $this->get("partkeepr.statistic.service")->getStatisticRange(); + public function getStatisticRangeAction() + { + return $this->get('partkeepr.statistic.service')->getStatisticRange(); } - } diff --git a/src/PartKeepr/StatisticBundle/DependencyInjection/PartKeeprStatisticExtension.php b/src/PartKeepr/StatisticBundle/DependencyInjection/PartKeeprStatisticExtension.php @@ -1,6 +1,6 @@ <?php -namespace PartKeepr\StatisticBundle\DependencyInjection; +namespace PartKeepr\StatisticBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; diff --git a/src/PartKeepr/StatisticBundle/Entity/StatisticSnapshot.php b/src/PartKeepr/StatisticBundle/Entity/StatisticSnapshot.php @@ -1,114 +1,139 @@ <?php + namespace PartKeepr\StatisticBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as Mapping; - /** * @Mapping\Entity() */ -class StatisticSnapshot { - /** +class StatisticSnapshot +{ + /** * @Mapping\Id * @Mapping\Column(type="integer") - * @Mapping\GeneratedValue(strategy="AUTO") - * @var integer - */ - private $id; - - /** - * Defines the date when this snapshot has been taken - * @Mapping\Column(type="datetime") - * @var \DateTime - */ - private $dateTime; - - /** - * Defines the amount of different parts in the database - * @Mapping\Column(type="integer") - * @var int - */ - private $parts; - - /** - * Defines the amount of categories - * @Mapping\Column(type="integer") - * @var int - */ - private $categories; - - /** - * Holds all defined units in the database - * @Mapping\OneToMany(targetEntity="PartKeepr\StatisticBundle\Entity\StatisticSnapshotUnit",mappedBy="statisticSnapshot",cascade={"persist", "remove"}) - */ - private $units; - - /** - * Creates a new statistic snapshot - */ - public function __construct () { - $this->units = new ArrayCollection(); - $this->setDateTime(new \DateTime()); - } - - /** - * Sets the date+time for the snapshot - * @param \DateTime $dateTime The date+time for the snapshot - */ - public function setDateTime (\DateTime $dateTime) { - $this->dateTime = $dateTime; - } - - /** - * Returns the date+time for the snapshot - * @return \DateTime The date+time for the snapshot - */ - public function getDateTime () { - return $this->dateTime; - } - - /** - * Sets the amount of overall parts for the snapshot - * @param int $parts The amount of parts - */ - public function setParts ($parts) { - $this->parts = $parts; - } - - /** - * Returns the amount of overall parts for the snapshot - * @return int The amount of parts - */ - public function getParts () { - return $this->parts; - } - - /** - * Sets the amount of categories for the snapshot - * @param int $categories The amount of categories - */ - public function setCategories ($categories) { - $this->categories = $categories; - } - - /** - * Returns the amount of categories - * @return int The amount of categories - */ - public function getCategories () { - return $this->categories; - } - - /** - * Returns the ID of this snapshot - * @return int The ID of this snapshot - */ - public function getId () { - return $this->id; - } - - public function getUnits () { - return $this->units; - } + * @Mapping\GeneratedValue(strategy="AUTO") + * + * @var int + */ + private $id; + + /** + * Defines the date when this snapshot has been taken. + * + * @Mapping\Column(type="datetime") + * + * @var \DateTime + */ + private $dateTime; + + /** + * Defines the amount of different parts in the database. + * + * @Mapping\Column(type="integer") + * + * @var int + */ + private $parts; + + /** + * Defines the amount of categories. + * + * @Mapping\Column(type="integer") + * + * @var int + */ + private $categories; + + /** + * Holds all defined units in the database. + * + * @Mapping\OneToMany(targetEntity="PartKeepr\StatisticBundle\Entity\StatisticSnapshotUnit",mappedBy="statisticSnapshot",cascade={"persist", "remove"}) + */ + private $units; + + /** + * Creates a new statistic snapshot. + */ + public function __construct() + { + $this->units = new ArrayCollection(); + $this->setDateTime(new \DateTime()); + } + + /** + * Sets the date+time for the snapshot. + * + * @param \DateTime $dateTime The date+time for the snapshot + */ + public function setDateTime(\DateTime $dateTime) + { + $this->dateTime = $dateTime; + } + + /** + * Returns the date+time for the snapshot. + * + * @return \DateTime The date+time for the snapshot + */ + public function getDateTime() + { + return $this->dateTime; + } + + /** + * Sets the amount of overall parts for the snapshot. + * + * @param int $parts The amount of parts + */ + public function setParts($parts) + { + $this->parts = $parts; + } + + /** + * Returns the amount of overall parts for the snapshot. + * + * @return int The amount of parts + */ + public function getParts() + { + return $this->parts; + } + + /** + * Sets the amount of categories for the snapshot. + * + * @param int $categories The amount of categories + */ + public function setCategories($categories) + { + $this->categories = $categories; + } + + /** + * Returns the amount of categories. + * + * @return int The amount of categories + */ + public function getCategories() + { + return $this->categories; + } + + /** + * Returns the ID of this snapshot. + * + * @return int The ID of this snapshot + */ + public function getId() + { + return $this->id; + } + + public function getUnits() + { + return $this->units; + } } diff --git a/src/PartKeepr/StatisticBundle/Entity/StatisticSnapshotUnit.php b/src/PartKeepr/StatisticBundle/Entity/StatisticSnapshotUnit.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StatisticBundle\Entity; use Doctrine\ORM\Mapping as Mapping; @@ -7,90 +8,109 @@ use PartKeepr\PartBundle\Entity\PartMeasurementUnit; /** * @Mapping\Entity */ -class StatisticSnapshotUnit { - /** +class StatisticSnapshotUnit +{ + /** * @Mapping\Id * @Mapping\Column(type="integer") - * @Mapping\GeneratedValue(strategy="AUTO") - * @var integer - */ - private $id; + * @Mapping\GeneratedValue(strategy="AUTO") + * + * @var int + */ + private $id; - /** - * @Mapping\ManyToOne(targetEntity="PartKeepr\StatisticBundle\Entity\StatisticSnapshot") - * The statistic snapshot this entity belongs to - * @var StatisticSnapshot - */ - private $statisticSnapshot; + /** + * @Mapping\ManyToOne(targetEntity="PartKeepr\StatisticBundle\Entity\StatisticSnapshot") + * The statistic snapshot this entity belongs to + * + * @var StatisticSnapshot + */ + private $statisticSnapshot; - /** - * @Mapping\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\PartMeasurementUnit") - * The statistic snapshot this entity belongs to - * @var StatisticSnapshot - */ - private $partUnit; + /** + * @Mapping\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\PartMeasurementUnit") + * The statistic snapshot this entity belongs to + * + * @var StatisticSnapshot + */ + private $partUnit; - /** - * The stockLevel for the unit - * @Mapping\Column(type="integer") - * @var int - */ - private $stockLevel; + /** + * The stockLevel for the unit. + * + * @Mapping\Column(type="integer") + * + * @var int + */ + private $stockLevel; - /** - * Sets the statistic snapshot this entity belongs to - * @param StatisticSnapshot $snapshot The snapshot - */ - public function setStatisticSnapshot (StatisticSnapshot $snapshot) { - $this->statisticSnapshot = $snapshot; - } + /** + * Sets the statistic snapshot this entity belongs to. + * + * @param StatisticSnapshot $snapshot The snapshot + */ + public function setStatisticSnapshot(StatisticSnapshot $snapshot) + { + $this->statisticSnapshot = $snapshot; + } - /** - * Returns the snapshot this entity belongs to - * @return StatisticSnapshot The snapshot - */ - public function getStatisticSnapshot () { - return $this->statisticSnapshot; - } + /** + * Returns the snapshot this entity belongs to. + * + * @return StatisticSnapshot The snapshot + */ + public function getStatisticSnapshot() + { + return $this->statisticSnapshot; + } - /** - * - * Sets the part unit for this entity - * @param PartMeasurementUnit $unit The part unit - */ - public function setPartUnit (PartMeasurementUnit $unit) { - $this->partUnit = $unit; - } + /** + * Sets the part unit for this entity. + * + * @param PartMeasurementUnit $unit The part unit + */ + public function setPartUnit(PartMeasurementUnit $unit) + { + $this->partUnit = $unit; + } - /** - * Returns the part unit for this entity - * @return PartMeasurementUnit The part unit - */ - public function getPartUnit () { - return $this->partUnit; - } + /** + * Returns the part unit for this entity. + * + * @return PartMeasurementUnit The part unit + */ + public function getPartUnit() + { + return $this->partUnit; + } - /** - * Returns the ID of this statistic snapshot unit - * @return int The ID - */ - public function getId () { - return $this->id; - } + /** + * Returns the ID of this statistic snapshot unit. + * + * @return int The ID + */ + public function getId() + { + return $this->id; + } - /** - * Sets the stock level for this unit snapshot - * @param int $stockLevel - */ - public function setStockLevel ($stockLevel) { - $this->stockLevel = $stockLevel; - } + /** + * Sets the stock level for this unit snapshot. + * + * @param int $stockLevel + */ + public function setStockLevel($stockLevel) + { + $this->stockLevel = $stockLevel; + } - /** - * Returns the stock level for this unit snapshot - * @return int The stock level - */ - public function getStockLevel () { - return $this->stockLevel; - } + /** + * Returns the stock level for this unit snapshot. + * + * @return int The stock level + */ + public function getStockLevel() + { + return $this->stockLevel; + } } diff --git a/src/PartKeepr/StatisticBundle/PartKeeprStatisticBundle.php b/src/PartKeepr/StatisticBundle/PartKeeprStatisticBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StatisticBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/StatisticBundle/Services/StatisticService.php b/src/PartKeepr/StatisticBundle/Services/StatisticService.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StatisticBundle\Services; use Doctrine\ORM\EntityManager; @@ -19,7 +20,7 @@ class StatisticService } /** - * Returns the part count + * Returns the part count. * * @param bool|false $withoutPrice Set to true to retrieve all parts where the average price is null * @@ -30,14 +31,14 @@ class StatisticService $dql = "SELECT COUNT(p.id) FROM PartKeepr\PartBundle\Entity\Part p"; if ($withoutPrice === true) { - $dql .= " WHERE p.averagePrice IS NOT NULL"; + $dql .= ' WHERE p.averagePrice IS NOT NULL'; } return $this->entityManager->createQuery($dql)->getSingleScalarResult(); } /** - * Returns the part category count + * Returns the part category count. * * @return int */ @@ -73,7 +74,7 @@ class StatisticService } /** - * Returns the part counts per part unit + * Returns the part counts per part unit. * * @return array An array of arrays with the keys "name" and "stockLevel" */ @@ -86,17 +87,18 @@ class StatisticService } /** - * Returns the range of all recorded statistic snapshots. - */ - public function getStatisticRange () { - $dql = "SELECT MIN(sts.dateTime) AS startDate, MAX(sts.dateTime) AS endDate FROM PartKeepr\\StatisticBundle\\Entity\\StatisticSnapshot sts"; - $query = $this->entityManager->createQuery($dql); + * Returns the range of all recorded statistic snapshots. + */ + public function getStatisticRange() + { + $dql = 'SELECT MIN(sts.dateTime) AS startDate, MAX(sts.dateTime) AS endDate FROM PartKeepr\\StatisticBundle\\Entity\\StatisticSnapshot sts'; + $query = $this->entityManager->createQuery($dql); - return $query->getSingleResult(); - } + return $query->getSingleResult(); + } /** - * Gets the sampled statistics + * Gets the sampled statistics. * * @param \DateTime $startDate * @param \DateTime $endDate @@ -108,14 +110,14 @@ class StatisticService { if ($startDate->getTimestamp() > $endDate->getTimestamp()) { // Swap both times - list($startDate, $endDate) = array($endDate, $startDate); + list($startDate, $endDate) = [$endDate, $startDate]; } $intervalSize = intval(($endDate->getTimestamp() - $startDate->getTimestamp()) / $sampleSize); $queryStartTime = clone $startDate; $queryEndTime = clone $startDate; - $queryEndTime->add(new \DateInterval("PT".$intervalSize."S")); + $queryEndTime->add(new \DateInterval('PT'.$intervalSize.'S')); $partUnitQuery = "SELECT pu FROM PartKeepr\PartBundle\Entity\PartMeasurementUnit pu"; $query = $this->entityManager->createQuery($partUnitQuery); @@ -128,80 +130,78 @@ class StatisticService $dql = "SELECT AVG(stsu.stockLevel) AS stockLevel FROM PartKeepr\StatisticBundle\Entity\StatisticSnapshotUnit stsu JOIN stsu.statisticSnapshot sts WHERE sts.dateTime >= :start AND sts.dateTime <= :end AND stsu.partUnit = :partUnit"; $subQuery = $this->entityManager->createQuery($dql); - $aRecords = array(); + $aRecords = []; for ($i = 0; $i < $sampleSize; $i++) { - $mainQuery->setParameter("start", $queryStartTime); - $mainQuery->setParameter("end", $queryEndTime); + $mainQuery->setParameter('start', $queryStartTime); + $mainQuery->setParameter('end', $queryEndTime); $result = $mainQuery->getResult(); $record = $result[0]; - if ($record["parts"] !== null) { - $record["parts"] = floatval($record["parts"]); + if ($record['parts'] !== null) { + $record['parts'] = floatval($record['parts']); } - if ($record["categories"] !== null) { - $record["categories"] = floatval($record["categories"]); + if ($record['categories'] !== null) { + $record['categories'] = floatval($record['categories']); } foreach ($aPartUnits as $partUnit) { - /** + /* * @var $partUnit PartMeasurementUnit */ - $subQuery->setParameter("start", $queryStartTime); - $subQuery->setParameter("end", $queryEndTime); - $subQuery->setParameter("partUnit", $partUnit); + $subQuery->setParameter('start', $queryStartTime); + $subQuery->setParameter('end', $queryEndTime); + $subQuery->setParameter('partUnit', $partUnit); $aResult = $subQuery->getResult(); - if ($aResult[0]["stockLevel"] !== null) { - $record["units"][$partUnit->getName()] = floatval($aResult[0]["stockLevel"]); + if ($aResult[0]['stockLevel'] !== null) { + $record['units'][$partUnit->getName()] = floatval($aResult[0]['stockLevel']); } else { - $record["units"][$partUnit->getName()] = null; + $record['units'][$partUnit->getName()] = null; } - } - $record["start"] = $queryStartTime->format("Y-m-d H:i:s"); + $record['start'] = $queryStartTime->format('Y-m-d H:i:s'); - if ($record["parts"] !== null) { + if ($record['parts'] !== null) { $aRecords[] = $record; } - - $queryStartTime->add(new \DateInterval("PT".$intervalSize."S")); - $queryEndTime->add(new \DateInterval("PT".$intervalSize."S")); + $queryStartTime->add(new \DateInterval('PT'.$intervalSize.'S')); + $queryEndTime->add(new \DateInterval('PT'.$intervalSize.'S')); } return $aRecords; } - public function createStatisticSnapshot () { - - $snapshot = new StatisticSnapshot(); - $snapshot->setParts($this->getPartCount()); - $snapshot->setCategories($this->getPartCategoryCount()); - - $unitCounts = $this->getUnitCounts(); - $partUnitRepository = $this->entityManager->getRepository("PartKeeprPartBundle:PartMeasurementUnit"); - - foreach ($unitCounts as $unitCount) { - $snapshotUnit = new StatisticSnapshotUnit(); - $snapshotUnit->setPartUnit($partUnitRepository->findOneBy(array("id" => $unitCount["partMeasurementUnit"]["id"]))); - $snapshotUnit->setStatisticSnapshot($snapshot); - - if ($unitCount["stockLevel"] !== null) { - $snapshotUnit->setStockLevel($unitCount["stockLevel"]); - } else { - $snapshotUnit->setStockLevel(0); - } + public function createStatisticSnapshot() + { + $snapshot = new StatisticSnapshot(); + $snapshot->setParts($this->getPartCount()); + $snapshot->setCategories($this->getPartCategoryCount()); + + $unitCounts = $this->getUnitCounts(); + $partUnitRepository = $this->entityManager->getRepository('PartKeeprPartBundle:PartMeasurementUnit'); + + foreach ($unitCounts as $unitCount) { + $snapshotUnit = new StatisticSnapshotUnit(); + $snapshotUnit->setPartUnit($partUnitRepository->findOneBy(['id' => $unitCount['partMeasurementUnit']['id']])); + $snapshotUnit->setStatisticSnapshot($snapshot); + + if ($unitCount['stockLevel'] !== null) { + $snapshotUnit->setStockLevel($unitCount['stockLevel']); + } else { + $snapshotUnit->setStockLevel(0); + } - $snapshot->getUnits()->add($snapshotUnit); - } + $snapshot->getUnits()->add($snapshotUnit); + } $this->entityManager->persist($snapshot); $this->entityManager->flush(); - } + } } diff --git a/src/PartKeepr/StockBundle/Entity/StockEntry.php b/src/PartKeepr/StockBundle/Entity/StockEntry.php @@ -1,11 +1,12 @@ <?php + namespace PartKeepr\StockBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\AuthBundle\Entity\User; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\PartBundle\Entity\Part; -use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -35,8 +36,10 @@ class StockEntry extends BaseEntity /** * The price per item. + * * @ORM\Column(type="decimal",precision=13,scale=4,nullable=true) * @Groups({"default"}) + * * @var float */ private $price; @@ -44,6 +47,7 @@ class StockEntry extends BaseEntity /** * @ORM\Column(type="datetime") * @Groups({"default"}) + * * @var \DateTime */ private $dateTime; @@ -53,22 +57,23 @@ class StockEntry extends BaseEntity * * @ORM\Column(type="boolean") * @Groups({"default"}) - * @var boolean + * + * @var bool */ private $correction; /** * @ORM\Column(type="string",nullable=true) * @Groups({"default"}) + * * @var string */ private $comment; - /** * Creates a new stock entry. A stock entry tracks how many parts * were the stockLevel is the amount of items added/removed, - * by which user and how much the user paid for it (for adding parts only!) + * by which user and how much the user paid for it (for adding parts only!). */ public function __construct() { @@ -76,9 +81,8 @@ class StockEntry extends BaseEntity $this->setCorrection(false); } - /** - * Sets the date+time + * Sets the date+time. * * @param \DateTime $dateTime The date+time */ @@ -110,7 +114,7 @@ class StockEntry extends BaseEntity /** * Returns if the entry is a correction entry. * - * @return boolean True if the entry is a correction entry, false otherwise + * @return bool True if the entry is a correction entry, false otherwise */ public function getCorrection() { @@ -192,7 +196,7 @@ class StockEntry extends BaseEntity } /** - * Returns the user for this entry + * Returns the user for this entry. * * @return User the user */ @@ -216,7 +220,7 @@ class StockEntry extends BaseEntity /** * Returns if the current stock entry is a removal. * - * @return boolean True if the entry is a removal, false otherwise + * @return bool True if the entry is a removal, false otherwise */ public function isRemoval() { @@ -228,7 +232,7 @@ class StockEntry extends BaseEntity } /** - * Sets a comment + * Sets a comment. * * @param string $comment */ @@ -238,7 +242,7 @@ class StockEntry extends BaseEntity } /** - * Returns the comment + * Returns the comment. * * @return string The comment */ diff --git a/src/PartKeepr/StockBundle/PartKeeprStockBundle.php b/src/PartKeepr/StockBundle/PartKeeprStockBundle.php @@ -1,9 +1,9 @@ <?php + namespace PartKeepr\StockBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PartKeeprStockBundle extends Bundle { - } diff --git a/src/PartKeepr/StorageLocationBundle/Controller/StorageLocationImageController.php b/src/PartKeepr/StorageLocationBundle/Controller/StorageLocationImageController.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle\Controller; use PartKeepr\ImageBundle\Controller\ImageController; @@ -6,10 +7,10 @@ use PartKeepr\ImageBundle\Controller\ImageController; class StorageLocationImageController extends ImageController { /** - * @inheritdoc + * {@inheritdoc} */ protected function getEntityClass() { - return "PartKeepr\\StorageLocationBundle\\Entity\\StorageLocationImage"; + return 'PartKeepr\\StorageLocationBundle\\Entity\\StorageLocationImage'; } } diff --git a/src/PartKeepr/StorageLocationBundle/DataFixtures/CategoryDataLoader.php b/src/PartKeepr/StorageLocationBundle/DataFixtures/CategoryDataLoader.php @@ -1,15 +1,18 @@ <?php + namespace PartKeepr\StorageLocationBundle\DataFixtures; use PartKeepr\CategoryBundle\DataFixtures\AbstractCategoryDataLoader; class CategoryDataLoader extends AbstractCategoryDataLoader { - protected function getEntityClass () { + protected function getEntityClass() + { return 'PartKeepr\StorageLocationBundle\Entity\StorageLocationCategory'; } - protected function getReferencePrefix () { - return "storagelocationcategory"; + protected function getReferencePrefix() + { + return 'storagelocationcategory'; } } diff --git a/src/PartKeepr/StorageLocationBundle/DataFixtures/StorageLocationLoader.php b/src/PartKeepr/StorageLocationBundle/DataFixtures/StorageLocationLoader.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle\DataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; @@ -10,12 +11,12 @@ class StorageLocationLoader extends AbstractFixture public function load(ObjectManager $manager) { $storageLocation = new StorageLocation(); - $storageLocation->setName("test"); - $storageLocation->setCategory($this->getReference("storagelocationcategory.first")); + $storageLocation->setName('test'); + $storageLocation->setCategory($this->getReference('storagelocationcategory.first')); $manager->persist($storageLocation); $manager->flush(); - $this->addReference("storagelocation.first", $storageLocation); + $this->addReference('storagelocation.first', $storageLocation); } } diff --git a/src/PartKeepr/StorageLocationBundle/DependencyInjection/PartKeeprStorageLocationExtension.php b/src/PartKeepr/StorageLocationBundle/DependencyInjection/PartKeeprStorageLocationExtension.php @@ -2,13 +2,13 @@ namespace PartKeepr\StorageLocationBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** - * This is the class that loads and manages your bundle configuration + * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ diff --git a/src/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php b/src/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php @@ -1,9 +1,10 @@ <?php + namespace PartKeepr\StorageLocationBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\CoreBundle\Entity\BaseEntity; +use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFile; use Symfony\Component\Serializer\Annotation\Groups; @@ -13,7 +14,8 @@ use Symfony\Component\Serializer\Annotation\Groups; class StorageLocation extends BaseEntity { /** - * Holds the name for our storage location + * Holds the name for our storage location. + * * @ORM\Column(type="string",unique=true) * @Groups({"default"}) * @@ -22,17 +24,19 @@ class StorageLocation extends BaseEntity private $name; /** - * Holds the storage location image + * Holds the storage location image. + * * @ORM\OneToOne(targetEntity="PartKeepr\StorageLocationBundle\Entity\StorageLocationImage", * mappedBy="storageLocation",cascade={"persist", "remove"}, orphanRemoval=true) * @Groups({"default"}) * @UploadedFile() + * * @var StorageLocationImage */ private $image; /** - * The category of the storage location + * The category of the storage location. * * @ORM\ManyToOne(targetEntity="PartKeepr\StorageLocationBundle\Entity\StorageLocationCategory", * inversedBy="storageLocations") @@ -43,7 +47,8 @@ class StorageLocation extends BaseEntity private $category; /** - * Returns the category path + * Returns the category path. + * * @Groups({"default"}) * * @return string @@ -53,12 +58,12 @@ class StorageLocation extends BaseEntity if ($this->category !== null) { return $this->category->getCategoryPath(); } else { - return ""; + return ''; } } /** - * Sets the category for this storage location + * Sets the category for this storage location. * * @param StorageLocationCategory $category The category * @@ -70,7 +75,7 @@ class StorageLocation extends BaseEntity } /** - * Returns the category of this storage location + * Returns the category of this storage location. * * @return StorageLocationCategory The storage location category */ @@ -80,7 +85,7 @@ class StorageLocation extends BaseEntity } /** - * Sets the name for the storage location + * Sets the name for the storage location. * * @param string $name the name to set */ @@ -90,7 +95,7 @@ class StorageLocation extends BaseEntity } /** - * Returns the name of the storage location + * Returns the name of the storage location. * * @return string The name */ @@ -100,7 +105,7 @@ class StorageLocation extends BaseEntity } /** - * Sets the storage location image + * Sets the storage location image. * * @param StorageLocationImage $image The storage location image * @@ -121,7 +126,7 @@ class StorageLocation extends BaseEntity } /** - * Returns the storage location image + * Returns the storage location image. * * @return StorageLocationImage The storage location image */ diff --git a/src/PartKeepr/StorageLocationBundle/Entity/StorageLocationCategory.php b/src/PartKeepr/StorageLocationBundle/Entity/StorageLocationCategory.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; @@ -40,13 +41,16 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn /** * @ORM\Column(type="text",nullable=true) * @Groups({"default"}) + * * @var string */ protected $categoryPath; /** - * Sets the parent category + * Sets the parent category. + * * @Groups({"default"}) + * * @param AbstractCategory|null $parent */ public function setParent(AbstractCategory $parent = null) @@ -55,7 +59,7 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn } /** - * Returns the parent category + * Returns the parent category. * * @return mixed */ @@ -65,7 +69,7 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn } /** - * Returns the storage locations + * Returns the storage locations. * * @return ArrayCollection */ @@ -75,7 +79,7 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn } /** - * Returns the children + * Returns the children. * * @return ArrayCollection */ @@ -85,7 +89,7 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn } /** - * Returns the category path + * Returns the category path. * * @return string */ @@ -108,7 +112,7 @@ class StorageLocationCategory extends AbstractCategory implements CategoryPathIn public function generateCategoryPath($pathSeparator) { if ($this->getParent() !== null) { - return $this->getParent()->generateCategoryPath($pathSeparator) . $pathSeparator . $this->getName(); + return $this->getParent()->generateCategoryPath($pathSeparator).$pathSeparator.$this->getName(); } else { return $this->getName(); } diff --git a/src/PartKeepr/StorageLocationBundle/Entity/StorageLocationImage.php b/src/PartKeepr/StorageLocationBundle/Entity/StorageLocationImage.php @@ -1,18 +1,20 @@ <?php + namespace PartKeepr\StorageLocationBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\ImageBundle\Entity\Image; /** - * Holds a storage location image + * Holds a storage location image. * * @ORM\Entity **/ class StorageLocationImage extends Image { /** - * The storage location object + * The storage location object. + * * @ORM\OneToOne(targetEntity="PartKeepr\StorageLocationBundle\Entity\StorageLocation",inversedBy="image") * * @var StorageLocation @@ -20,7 +22,7 @@ class StorageLocationImage extends Image private $storageLocation = null; /** - * Creates a new storage location image instance + * Creates a new storage location image instance. */ public function __construct() { @@ -28,7 +30,7 @@ class StorageLocationImage extends Image } /** - * Sets the storage location + * Sets the storage location. * * @param StorageLocation $storageLocation The storage location to set */ @@ -38,7 +40,7 @@ class StorageLocationImage extends Image } /** - * Returns the storage location + * Returns the storage location. * * @return StorageLocation the storage location */ diff --git a/src/PartKeepr/StorageLocationBundle/Listeners/CategoryPathListener.php b/src/PartKeepr/StorageLocationBundle/Listeners/CategoryPathListener.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle\Listeners; use Doctrine\ORM\EntityManager; @@ -9,7 +10,8 @@ use Symfony\Component\DependencyInjection\ContainerAware; class CategoryPathListener extends ContainerAware { - public function __construct (Container $container) { + public function __construct(Container $container) + { $this->setContainer($container); } @@ -45,7 +47,7 @@ class CategoryPathListener extends ContainerAware public function updateCategoryPaths(StorageLocationCategory $storageLocationCategory, OnFlushEventArgs $eventArgs) { $entityManager = $eventArgs->getEntityManager(); - $pathSeparator = $this->container->getParameter("partkeepr.category.path_separator"); + $pathSeparator = $this->container->getParameter('partkeepr.category.path_separator'); $storageLocationCategory->setCategoryPath($storageLocationCategory->generateCategoryPath($pathSeparator)); diff --git a/src/PartKeepr/StorageLocationBundle/PartKeeprStorageLocationBundle.php b/src/PartKeepr/StorageLocationBundle/PartKeeprStorageLocationBundle.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; diff --git a/src/PartKeepr/StorageLocationBundle/Tests/CategoryCreateTest.php b/src/PartKeepr/StorageLocationBundle/Tests/CategoryCreateTest.php @@ -1,12 +1,11 @@ <?php -namespace PartKeepr\StorageLocationBundle\Tests; +namespace PartKeepr\StorageLocationBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractCategoryCreateTest; class CategoryCreateTest extends AbstractCategoryCreateTest { - public function getResourceClass() { return 'PartKeepr\StorageLocationBundle\Entity\StorageLocationCategory'; @@ -19,6 +18,6 @@ class CategoryCreateTest extends AbstractCategoryCreateTest public function getReferencePrefix() { - return "storagelocationcategory"; + return 'storagelocationcategory'; } } diff --git a/src/PartKeepr/StorageLocationBundle/Tests/MoveActionTest.php b/src/PartKeepr/StorageLocationBundle/Tests/MoveActionTest.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\StorageLocationBundle\Tests; use PartKeepr\CategoryBundle\Tests\AbstractMoveCategoryTest; @@ -12,6 +13,6 @@ class MoveActionTest extends AbstractMoveCategoryTest public function getReferencePrefix() { - return "storagelocationcategory"; + return 'storagelocationcategory'; } } diff --git a/src/PartKeepr/TipOfTheDayBundle/Action/GetTipHistoryCollectionAction.php b/src/PartKeepr/TipOfTheDayBundle/Action/GetTipHistoryCollectionAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\TipOfTheDayBundle\Action; use Dunglas\ApiBundle\Action\ActionUtilTrait; @@ -29,13 +30,13 @@ class GetTipHistoryCollectionAction } /** - * Retrieves a filtered tip of the day history list. Filters by the currently logged in user by default + * Retrieves a filtered tip of the day history list. Filters by the currently logged in user by default. * * @param Request $request * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request) { @@ -44,11 +45,11 @@ class GetTipHistoryCollectionAction $collection = $this->dataProvider->getCollection($resourceType); $user = $this->userService->getUser(); - $resultCollection = array(); + $resultCollection = []; foreach ($collection as $item) { /** - * @var $item TipOfTheDayHistory + * @var TipOfTheDayHistory */ if ($item->getUser() == $user) { $resultCollection[] = $item; diff --git a/src/PartKeepr/TipOfTheDayBundle/Action/MarkTipReadAction.php b/src/PartKeepr/TipOfTheDayBundle/Action/MarkTipReadAction.php @@ -1,4 +1,5 @@ <?php + namespace PartKeepr\TipOfTheDayBundle\Action; use Doctrine\ORM\EntityManager; @@ -40,14 +41,14 @@ class MarkTipReadAction } /** - * Marks a specific tip as read + * Marks a specific tip as read. * * @param Request $request The request * @param int $id The ID of the system notice * - * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable - * * @throws RuntimeException + * + * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable */ public function __invoke(Request $request, $id) { @@ -55,7 +56,7 @@ class MarkTipReadAction $tip = $this->getItem($this->dataProvider, $resourceType, $id); - /** + /* * @var $tip TipOfTheDay */ $tipOfTheDayHistoryItem = new TipOfTheDayHistory(); diff --git a/