partkeepr

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

commit 146c7116d69c6e672d1f3e05c3b776fc1d6ed56d
parent e289be5390bddb29ba8fade5b2ff55a4fdc8f0da
Author: Timo A. Hummel <felicitus@felicitus.org>
Date:   Sat,  7 Nov 2015 00:10:34 +0100

Finally removed all legacy code from src/backend and src/frontend \o/

Diffstat:
Mapp/config/config_doctrine.yml | 5-----
Msrc/PartKeepr/AuthBundle/Entity/User.php | 2+-
Msrc/PartKeepr/AuthBundle/Entity/UserProvider.php | 2+-
Msrc/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php | 14++++----------
Msrc/PartKeepr/CategoryBundle/Entity/AbstractCategory.php | 2+-
Msrc/PartKeepr/CoreBundle/Entity/SystemNotice.php | 2+-
Msrc/PartKeepr/CoreBundle/Services/SystemService.php | 10----------
Msrc/PartKeepr/CronLoggerBundle/Entity/CronLogger.php | 2+-
Msrc/PartKeepr/DistributorBundle/Entity/Distributor.php | 2+-
Msrc/PartKeepr/FootprintBundle/Entity/Footprint.php | 2+-
Msrc/PartKeepr/ImageBundle/Entity/CachedImage.php | 2+-
Msrc/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php | 2+-
Msrc/PartKeepr/PartBundle/Entity/Part.php | 5++---
Msrc/PartKeepr/PartBundle/Entity/PartDistributor.php | 4++--
Msrc/PartKeepr/PartBundle/Entity/PartManufacturer.php | 2+-
Msrc/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php | 2+-
Msrc/PartKeepr/ProjectBundle/Entity/Project.php | 2+-
Msrc/PartKeepr/ProjectBundle/Entity/ProjectPart.php | 2+-
Msrc/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php | 2+-
Msrc/PartKeepr/StockBundle/Entity/StockEntry.php | 2+-
Msrc/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php | 2+-
Msrc/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDay.php | 2+-
Msrc/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDayHistory.php | 2+-
Msrc/PartKeepr/UnitBundle/Entity/Unit.php | 2+-
Msrc/PartKeepr/UploadedFileBundle/Entity/UploadedFile.php | 2+-
Dsrc/backend/PartKeepr/FulltextSearch/FulltextSearch.php | 95-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Logger/Logger.php | 122-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Manager/AbstractManager.php | 231-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Manager/Exceptions/EntityInUseException.php | 32--------------------------------
Dsrc/backend/PartKeepr/Manager/ManagerFilter.php | 201-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Manager/Sorter.php | 80-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Part/PartFulltextSearch.php | 29-----------------------------
Dsrc/backend/PartKeepr/PartKeepr.php | 280-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/AdminService.php | 14--------------
Dsrc/backend/PartKeepr/Service/Annotations/ApiType.php | 42------------------------------------------
Dsrc/backend/PartKeepr/Service/Annotations/ApiTypeOutputField.php | 56--------------------------------------------------------
Dsrc/backend/PartKeepr/Service/Annotations/ApiTypeOutputFields.php | 29-----------------------------
Dsrc/backend/PartKeepr/Service/Annotations/Service.php | 46----------------------------------------------
Dsrc/backend/PartKeepr/Service/Annotations/ServiceCall.php | 67-------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/Annotations/ServiceParameter.php | 68--------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/Annotations/ServiceReturnValue.php | 53-----------------------------------------------------
Dsrc/backend/PartKeepr/Service/AnonService.php | 6------
Dsrc/backend/PartKeepr/Service/Exceptions/ServiceException.php | 6------
Dsrc/backend/PartKeepr/Service/FilterExtractor.php | 38--------------------------------------
Dsrc/backend/PartKeepr/Service/RestfulService.php | 10----------
Dsrc/backend/PartKeepr/Service/Service.php | 109-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/ServiceCallReflector.php | 95-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/ServiceManager.php | 182-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/ServiceReflector.php | 114-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Service/TypeReflector.php | 91-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/AbstractSetup.php | 45---------------------------------------------
Dsrc/backend/PartKeepr/Setup/ConfigFileSetup.php | 66------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/FootprintSetup.php | 156-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/ManufacturerSetup.php | 56--------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/DistributorMigration.php | 34----------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/FootprintMigration.php | 43-------------------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/PartCategoryMigration.php | 50--------------------------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/PartDBMigration.php | 71-----------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/PartMigration.php | 131-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/Migration/PartDB/StorageLocationMigration.php | 51---------------------------------------------------
Dsrc/backend/PartKeepr/Setup/MiscSettingsSetup.php | 69---------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/PartCategorySetup.php | 28----------------------------
Dsrc/backend/PartKeepr/Setup/PartUnitSetup.php | 36------------------------------------
Dsrc/backend/PartKeepr/Setup/SchemaSetup.php | 35-----------------------------------
Dsrc/backend/PartKeepr/Setup/Setup.php | 177-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/SiPrefixSetup.php | 47-----------------------------------------------
Dsrc/backend/PartKeepr/Setup/UnitSetup.php | 62--------------------------------------------------------------
Dsrc/backend/PartKeepr/Setup/UserSetup.php | 32--------------------------------
Dsrc/backend/PartKeepr/Statistic/StatisticService.php | 149-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Statistic/StatisticSnapshot.php | 111-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Statistic/StatisticSnapshotManager.php | 37-------------------------------------
Dsrc/backend/PartKeepr/Statistic/StatisticSnapshotUnit.php | 97-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/User/UserService.php | 116-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/BaseEntity.php | 26--------------------------
Dsrc/backend/PartKeepr/Util/Configuration.php | 93-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/Deserializable.php | 11-----------
Dsrc/backend/PartKeepr/Util/ExtJSFile.php | 181-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/Minifier/Minifier.php | 79-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/Minifier/jsminMinifier.php | 53-----------------------------------------------------
Dsrc/backend/PartKeepr/Util/Minifier/yuiCompressorMinifier.php | 80-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/Serializable.php | 12------------
Dsrc/backend/PartKeepr/Util/SerializableException.php | 61-------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/SimpleObjectManager.php | 40----------------------------------------
Dsrc/backend/PartKeepr/Util/Singleton.php | 23-----------------------
Dsrc/backend/PartKeepr/Util/TablePrinter.php | 182-------------------------------------------------------------------------------
Dsrc/backend/PartKeepr/Util/UtilService.php | 14--------------
86 files changed, 28 insertions(+), 4700 deletions(-)

diff --git a/app/config/config_doctrine.yml b/app/config/config_doctrine.yml @@ -19,11 +19,6 @@ doctrine: connection: ~ auto_mapping: true mappings: - model: - type: annotation - dir: %kernel.root_dir%/../src/backend/PartKeepr/ - prefix: PartKeepr - is_bundle: false gedmo_tree: type: annotation prefix: Gedmo\Tree\Entity diff --git a/src/PartKeepr/AuthBundle/Entity/User.php b/src/PartKeepr/AuthBundle/Entity/User.php @@ -4,7 +4,7 @@ namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\DoctrineReflectionBundle\Annotation\VirtualField; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Security\Core\User\EquatableInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Serializer\Annotation\Groups; diff --git a/src/PartKeepr/AuthBundle/Entity/UserProvider.php b/src/PartKeepr/AuthBundle/Entity/UserProvider.php @@ -3,7 +3,7 @@ namespace PartKeepr\AuthBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php b/src/PartKeepr/AuthBundle/Exceptions/UserPreferenceNotFoundException.php @@ -1,21 +1,15 @@ <?php namespace PartKeepr\AuthBundle\Exceptions; -use PartKeepr\AuthBundle\Entity\User; -use PartKeepr\Util\SerializableException; +use PartKeepr\CoreBundle\Exceptions\TranslatableException; /** * Is thrown when the user has given wrong credentials. */ -class UserPreferenceNotFoundException extends SerializableException +class UserPreferenceNotFoundException extends TranslatableException { - public function __construct(User $user, $preferenceKey) + public function getMessageKey() { - $message = sprintf("User preference %s not found for user %s (%s)", - $preferenceKey, - $user->getUsername(), - $user->getId()); - - parent::__construct($message); + return "The requested user preference was not found"; } } diff --git a/src/PartKeepr/CategoryBundle/Entity/AbstractCategory.php b/src/PartKeepr/CategoryBundle/Entity/AbstractCategory.php @@ -4,7 +4,7 @@ namespace PartKeepr\CategoryBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/CoreBundle/Entity/SystemNotice.php b/src/PartKeepr/CoreBundle/Entity/SystemNotice.php @@ -3,7 +3,7 @@ namespace PartKeepr\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/CoreBundle/Services/SystemService.php b/src/PartKeepr/CoreBundle/Services/SystemService.php @@ -9,7 +9,6 @@ use Doctrine\ORM\Version as ORMVersion; use PartKeepr\CoreBundle\System\OperatingSystem; use PartKeepr\CoreBundle\System\SystemInformationRecord; use PartKeepr\CronLoggerBundle\Services\CronLoggerService; -use PartKeepr\Util\Configuration; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -102,15 +101,6 @@ class SystemService extends ContainerAware $aData[] = new SystemInformationRecord("PartKeepr Version", $this->versionService->getVersion(), "PartKeepr"); - foreach (Configuration::getOptions() as $key => $value) { - // Hide passwords - if ($key == "partkeepr.database.password" || $key == "partkeepr.migration.partdb.password") { - $value = "<hidden>"; - } - - $aData[] = new SystemInformationRecord($key, $value, "PartKeepr Configuration Information"); - } - return $aData; } diff --git a/src/PartKeepr/CronLoggerBundle/Entity/CronLogger.php b/src/PartKeepr/CronLoggerBundle/Entity/CronLogger.php @@ -2,7 +2,7 @@ namespace PartKeepr\CronLoggerBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; /** * Holds a project attachment diff --git a/src/PartKeepr/DistributorBundle/Entity/Distributor.php b/src/PartKeepr/DistributorBundle/Entity/Distributor.php @@ -3,7 +3,7 @@ namespace PartKeepr\DistributorBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/FootprintBundle/Entity/Footprint.php b/src/PartKeepr/FootprintBundle/Entity/Footprint.php @@ -4,7 +4,7 @@ namespace PartKeepr\FootprintBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; use PartKeepr\UploadedFileBundle\Annotation\UploadedFile; use Symfony\Component\Serializer\Annotation\Groups; diff --git a/src/PartKeepr/ImageBundle/Entity/CachedImage.php b/src/PartKeepr/ImageBundle/Entity/CachedImage.php @@ -3,7 +3,7 @@ namespace PartKeepr\ImageBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\UploadedFileBundle\Entity\UploadedFile; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; /** * Represents a cached image. Cached images are used for scale/resize diff --git a/src/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php b/src/PartKeepr/ManufacturerBundle/Entity/Manufacturer.php @@ -5,7 +5,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/PartBundle/Entity/Part.php b/src/PartKeepr/PartBundle/Entity/Part.php @@ -8,12 +8,11 @@ use PartKeepr\FootprintBundle\Entity\Footprint; use PartKeepr\PartBundle\Exceptions\CategoryNotAssignedException; use PartKeepr\PartBundle\Exceptions\MinStockLevelOutOfRangeException; use PartKeepr\PartBundle\Exceptions\StorageLocationNotAssignedException; -use PartKeepr\PartKeepr; use PartKeepr\ProjectBundle\Entity\ProjectPart; use PartKeepr\StockBundle\Entity\StockEntry; use PartKeepr\StorageLocationBundle\Entity\StorageLocation; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -624,7 +623,7 @@ class Part extends BaseEntity * * @param int $minStockLevel A minimum stock level, only values >= 0 are allowed. * - * @throws \PartKeepr\Util\Exceptions\OutOfRangeException If the passed stock level is not in range (>=0) + * @throws MinStockLevelOutOfRangeException If the passed stock level is not in range (>=0) */ public function setMinStockLevel($minStockLevel) { diff --git a/src/PartKeepr/PartBundle/Entity/PartDistributor.php b/src/PartKeepr/PartBundle/Entity/PartDistributor.php @@ -4,7 +4,7 @@ namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DistributorBundle\Entity\Distributor; use PartKeepr\PartBundle\Exceptions\PackagingUnitOutOfRangeException; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -81,7 +81,7 @@ class PartDistributor extends BaseEntity * * @param int $packagingUnit The amount of items in one package * - * @throws OutOfRangeException When the packaging unit is less than 1 + * @throws PackagingUnitOutOfRangeException When the packaging unit is less than 1 */ public function setPackagingUnit($packagingUnit) { diff --git a/src/PartKeepr/PartBundle/Entity/PartManufacturer.php b/src/PartKeepr/PartBundle/Entity/PartManufacturer.php @@ -3,7 +3,7 @@ namespace PartKeepr\PartBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\ManufacturerBundle\Entity\Manufacturer; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php b/src/PartKeepr/PartBundle/Entity/PartMeasurementUnit.php @@ -4,7 +4,7 @@ namespace PartKeepr\PartBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; diff --git a/src/PartKeepr/ProjectBundle/Entity/Project.php b/src/PartKeepr/ProjectBundle/Entity/Project.php @@ -6,7 +6,7 @@ use Doctrine\ORM\Mapping as ORM; use PartKeepr\AuthBundle\Entity\User; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\UploadedFileBundle\Annotation\UploadedFileCollection; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/ProjectBundle/Entity/ProjectPart.php b/src/PartKeepr/ProjectBundle/Entity/ProjectPart.php @@ -4,7 +4,7 @@ namespace PartKeepr\ProjectBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\PartBundle\Entity\Part; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php b/src/PartKeepr/SiPrefixBundle/Entity/SiPrefix.php @@ -3,7 +3,7 @@ namespace PartKeepr\SiPrefixBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; diff --git a/src/PartKeepr/StockBundle/Entity/StockEntry.php b/src/PartKeepr/StockBundle/Entity/StockEntry.php @@ -5,7 +5,7 @@ use Doctrine\ORM\Mapping as ORM; use PartKeepr\AuthBundle\Entity\User; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\PartBundle\Entity\Part; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php b/src/PartKeepr/StorageLocationBundle/Entity/StorageLocation.php @@ -3,7 +3,7 @@ namespace PartKeepr\StorageLocationBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use PartKeepr\UploadedFileBundle\Annotation\UploadedFile; use Symfony\Component\Serializer\Annotation\Groups; diff --git a/src/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDay.php b/src/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDay.php @@ -3,7 +3,7 @@ namespace PartKeepr\TipOfTheDayBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDayHistory.php b/src/PartKeepr/TipOfTheDayBundle/Entity/TipOfTheDayHistory.php @@ -4,7 +4,7 @@ namespace PartKeepr\TipOfTheDayBundle\Entity; use Doctrine\ORM\Mapping as ORM; use PartKeepr\AuthBundle\Entity\User; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; /** diff --git a/src/PartKeepr/UnitBundle/Entity/Unit.php b/src/PartKeepr/UnitBundle/Entity/Unit.php @@ -5,7 +5,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use PartKeepr\DoctrineReflectionBundle\Annotation\TargetService; use PartKeepr\SiPrefixBundle\Entity\SiPrefix; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; diff --git a/src/PartKeepr/UploadedFileBundle/Entity/UploadedFile.php b/src/PartKeepr/UploadedFileBundle/Entity/UploadedFile.php @@ -2,7 +2,7 @@ namespace PartKeepr\UploadedFileBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use PartKeepr\Util\BaseEntity; +use PartKeepr\CoreBundle\Entity\BaseEntity; use Ramsey\Uuid\Uuid; use Symfony\Component\Serializer\Annotation\Groups; diff --git a/src/backend/PartKeepr/FulltextSearch/FulltextSearch.php b/src/backend/PartKeepr/FulltextSearch/FulltextSearch.php @@ -1,94 +0,0 @@ -<?php -namespace PartKeepr\FulltextSearch; - -use PartKeepr\PartKeepr; - -abstract class FulltextSearch { - - /** - * Creates a new fulltext search based on the given query. - * - * The query can contain different query strings, separated by space. The query returns only results which contain - * all query strings in any fields. - * - * If the query is "100 ohm", it would only consider entities which have both "100" and "ohm", no matter which field - * the value is in. - * - * @param string $query The query to search for - */ - public function __construct ($query) { - $this->query = explode(" ", $query); - } - - /** - * Fires the query and returns the results. - * - * @param none - * @return array An array with all IDs which match the query - */ - public function query () { - return $this->fallbackSearch(); - } - - /** - * A fallback search in case no fulltext search engine is available. This directly queries the database, which is - * slow. - */ - protected function fallbackSearch () { - $qb = PartKeepr::getEM()->createQueryBuilder(); - - $qb ->select("q.id") - ->from($this->getEntityName(), "q") - ->where("1=1"); - - $dqlChunks = array(); - - foreach ($this->query as $id => $queryString) { - $partDqlChunks = array(); - foreach ($this->getFields() as $field) { - $partDqlChunks[] = "LOWER(q." . $field.") LIKE :filter".$id; - } - - $dqlChunks[] = "(".implode(" OR ", $partDqlChunks).")"; - - $qb->setParameter("filter".$id, "%".str_replace("%", "\\%", strtolower($queryString))."%"); - } - - $qb->andWhere(implode(" AND " ,$dqlChunks)); - - $query = $qb->getQuery(); - - - - $result = $query->getArrayResult(); - - if (count($result) > 0) { - $results = array(); - - foreach ($result as $value) { - $results[] = $value["id"]; - } - - return $results; - } else { - return array(0); - } - } - - /** - * Returns the FQDN name of the entity. This needs to be overridden in child classes. - * - * @param none - * @return string the FQDN of the entity to query, e.g. PartKeepr\PartBundle\Entity\Part - */ - abstract protected function getEntityName (); - - /** - * Returns the fields in which the fulltext search should search in. - * - * @param none - * @return array An array of field names, e.g. array("name", "description") - */ - abstract protected function getFields (); - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Logger/Logger.php b/src/backend/PartKeepr/Logger/Logger.php @@ -1,121 +0,0 @@ -<?php -namespace PartKeepr\Logger; - -/** - * This class implements a simple logging mechanism. - * - * Might be replaced with some more advanced logging framework, but it serves its purpose for now. - */ -use PartKeepr\Util\Configuration; - -class Logger { - /** - * Loglevel "debug" - * - * You want to use this loglevel for debugging messages. - * @var string - */ - const LOGLEVEL_DEBUG = "debug"; - - /** - * Loglevel "info" - * - * You want to use this loglevel for informational messages where the program flow can continue normally and no - * impacts occur. - * - * @var string - */ - const LOGLEVEL_INFO = "info"; - - /** - * Loglevel "warning" - * - * You want to use this loglevel for messages where program flow can continue normally, but a minor - * impact can occur. - * - * @var string - */ - const LOGLEVEL_WARNING = "warning"; - - /** - * Loglevel "error" - * - * You want to use this loglevel for messages where program flow could be interrupted and major impacts occur. - * - * @var string - */ - const LOGLEVEL_ERROR = "error"; - - /** - * Loglevel "critical" - * - * You want to use this loglevel for messages where program flow could be interrupted and major impacts occur. - * - * @var string - */ - const LOGLEVEL_CRITICAL = "critical"; - - /** - * Logs a message. - * - * @param string $message The message to log - * @param string $severity One of the Logger::LOGLEVEL_* constants - */ - public static function log ($message, $severity = Logger::LOGLEVEL_INFO) { - if (Configuration::getOption("partkeepr.logger.enable", false) === false) { - // No logging wanted - return; - } - - $logFormat = "[%-19s] [%-8s] %s"; - - $outputFile = Configuration::getOption("partkeepr.logger.outputfile", sys_get_temp_dir() . "/partkeepr.log"); - $fp = fopen($outputFile, "a"); - - $date = date("Y-m-d H:i:s"); - - fputs($fp, sprintf($logFormat, $date, $severity, $message)."\n"); - - fclose($fp); - } - - /** - * Logs a message with the Logger::LOGLEVEL_DEBUG severity. - * @param string $message - */ - public static function logDebug ($message) { - self::log($message, Logger::LOGLEVEL_DEBUG); - } - - /** - * Logs a message with the Logger::LOGLEVEL_INFO severity. - * @param string $message - */ - public static function logInfo ($message) { - self::log($message, Logger::LOGLEVEL_INFO); - } - - /** - * Logs a message with the Logger::LOGLEVEL_WARNING severity. - * @param string $message - */ - public static function logWarning ($message) { - self::log($message, Logger::LOGLEVEL_WARNING); - } - - /** - * Logs a message with the Logger::LOGLEVEL_ERROR severity. - * @param string $message - */ - public static function logError ($message) { - self::log($message, Logger::LOGLEVEL_ERROR); - } - - /** - * Logs a message with the Logger::LOGLEVEL_CRITICAL severity. - * @param string $message - */ - public static function logCritical ($message) { - self::log($message, Logger::LOGLEVEL_CRITICAL); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Manager/AbstractManager.php b/src/backend/PartKeepr/Manager/AbstractManager.php @@ -1,230 +0,0 @@ -<?php -namespace PartKeepr\Manager; - -use PartKeepr\Util\Singleton, - PartKeepr\PartKeepr, - Doctrine\ORM\QueryBuilder, - Doctrine\ORM\Query, - PartKeepr\Manager\Exceptions\EntityInUseException; - -/** - * The AbstractManager is a very basic helper which - * implements the mostly used operations on entities: - * - * - Create - * - Delete - * - List - * - */ -abstract class AbstractManager extends Singleton { - /** - * Returns the FQCN for the target entity to operate on. - * - * Needs to be implemented by the parent class. - * - * @return string The FQCN, e.g. PartKeepr\Part - */ - abstract public function getEntityName (); - - /** - * Returns all fields which need to appear in the getList ResultSet. - * - * This should include all fields required by the frontend. - * - * @return array An array of all fields which should be returned - */ - abstract public function getQueryFields (); - - /** - * Returns the default sort field - * - * @return string The default sort field - */ - abstract public function getDefaultSortField (); - - /** - * Loads an entity by id - * - * @param int $id The entity id - */ - public function getEntity ($id) { - return call_user_func($this->getEntityName()."::loadById", $id); - } - - /** - * Removes a specific entity from the system - * @param int $id - * @throws EntityInUseException Is thrown when the entity is in use - */ - public function deleteEntity ($id) { - $entity = $this->getEntity($id); - - try { - PartKeepr::getEM()->remove($entity); - PartKeepr::getEM()->flush(); - } catch (\PDOException $e) { - if ($e->getCode() == "23000") { - throw new EntityInUseException($entity); - } - } - } - - /** - * Creates a new entity from an array of parameters - * @param array $parameters An array which gets passed to the deserialize method - */ - public function createEntity ($parameters) { - $class = $this->getEntityName(); - $entity = new $class; - $entity->deserialize($parameters); - - PartKeepr::getEM()->persist($entity); - PartKeepr::getEM()->flush(); - - return $entity; - } - - /** - * Returns a list of entities. - * - * @param ManagerFilter $filter The filter settings for this query - */ - public function getList (ManagerFilter $filter) { - $qb = PartKeepr::getEM()->createQueryBuilder(); - - $qb->select("COUNT(q.id)")->from($this->getEntityName(),"q"); - - $this->applyFiltering($qb, $filter); - $this->applyCustomQuery($qb, $filter); - - $totalQuery = $qb->getQuery(); - - $this->applyResultFields($qb, $filter); - $this->applyPagination($qb, $filter); - $this->applySorting($qb, $filter); - - $query = $qb->getQuery(); - - return array("data" => $this->getResult($query), "totalCount" => $totalQuery->getSingleScalarResult()); - } - - /** - * Processes the result after it was retrieved. In the default configuration, it returns an array result, or - * if no query fields are specified, it tries to serialize all objects. - */ - protected function getResult (Query $query) { - if (count($this->getQueryFields()) == 0) { - $aSerializedResult = array(); - foreach ($query->getResult() as $result) { - $aSerializedResult[] = $result->serialize(); - } - - return $aSerializedResult; - } else { - return $query->getArrayResult(); - } - } - - /** - * Applies the result fields to the query. - * - * The result fields can be prefixed with the table alias or not; if not prefixed, it is assumed that we'll be - * using the specified entity FQCN. - * - * Note that the base name will be always "q", so avoid "q" as alias for joined tables. - * - * @param QueryBuilder $qb The query builder - * @param ManagerFilter $filter The query filter - */ - protected function applyResultFields (QueryBuilder $qb, ManagerFilter $filter) { - if (count($this->getQueryFields()) == 0) { - $qb->select("q"); - } else { - // Prepend a prefix to each field - $aQueryFields = array(); - foreach ($this->getQueryFields() as $field) { - - if (strpos($field, ".") === false) { - // The field is not prefixed, prepend the q. prefix - $aQueryFields[] = "q.".$field; - } else { - // Use as-is - $aQueryFields[] = $field; - } - } - - $qb->select($aQueryFields); - } - } - - /** - * Applies filtering to the query and calls back the custom filtering function, if required. - * - * @param QueryBuilder $qb The query builder - * @param ManagerFilter $filter The query filter - */ - protected function applyFiltering (QueryBuilder $qb, ManagerFilter $filter) { - if ($filter->getFilter() !== null && $filter->getFilterField() !== null) { - $aOrWhereFields = array(); - - if (is_array($filter->getFilterField())) { - foreach ($filter->getFilterField() as $field) { - $aOrWhereFields[] = "LOWER(q.".$field.") LIKE :filter"; - } - } else { - $aOrWhereFields[] = "LOWER(q.".$filter->getFilterField().") LIKE :filter"; - } - - foreach ($aOrWhereFields as $or) { - $qb->orWhere($or); - } - - $qb->setParameter("filter", "%".strtolower($filter->getFilter())."%"); - } - - if ($filter->getFilterCallback() !== null) { - call_user_func($filter->getFilterCallback(), $qb); - } - } - - - /** - * Applies a custom query to the QueryBuilder - * - * @param QueryBuilder $qb The query builder - * @param ManagerFilter $filter The query filter - */ - protected function applyCustomQuery (QueryBuilder $qb, ManagerFilter $filter) { - - } - - /** - * Applies pagination to the query - * - * @param QueryBuilder $qb The query builder - * @param ManagerFilter $filter The query filter - */ - protected function applyPagination (QueryBuilder $qb, ManagerFilter $filter) { - if ($filter->getStart() !== null && $filter->getLimit() !== null) { - $qb->setFirstResult($filter->getStart()); - } - - if ($filter->getLimit() !== null) { - $qb->setMaxResults($filter->getLimit()); - } - } - - /** - * Applies record sorting - * - * @param QueryBuilder $qb The query builder - * @param ManagerFilter $filter The query filter - */ - protected function applySorting (QueryBuilder $qb, ManagerFilter $filter) { - foreach ($filter->getSorters() as $sorter) { - if ($sorter->getSortField() !== null && $sorter->getSortField() != "q.") { - $qb->addOrderBy($sorter->getSortField(), $sorter->getSortDirection()); - } - } - } -} - \ No newline at end of file diff --git a/src/backend/PartKeepr/Manager/Exceptions/EntityInUseException.php b/src/backend/PartKeepr/Manager/Exceptions/EntityInUseException.php @@ -1,31 +0,0 @@ -<?php -namespace PartKeepr\Manager\Exceptions; - -/** - * This exception is thrown when an entity should be deleted, but is in use by other entities. - * @author felicitus - */ -class EntityInUseException extends \Exception { - - /** - * The entity - * @var BaseEntity - */ - private $entity; - - /** - * Constructs the exception - * @param BaseEntity $entity - */ - public function __construct (\PartKeepr\Util\BaseEntity $entity) { - parent::__construct(sprintf("Entity %s is referenced by other entities, can't delete", get_class($entity))); - $this->entity = $entity; - } - - /** - * Returns the entity which caused the error - */ - public function getEntity () { - return $this->entity; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Manager/ManagerFilter.php b/src/backend/PartKeepr/Manager/ManagerFilter.php @@ -1,200 +0,0 @@ -<?php -namespace PartKeepr\Manager; - -use PartKeepr\Service\Service; - -class ManagerFilter { - /** - * Specifies the record index at which to start - * @var integer - */ - protected $start = 0; - - /** - * Specifies the number of records to retrieve - * @var integer - */ - protected $limit = null; - - /** - * Specifies a string to filter for. Can either be a string - * or null if no filter is wanted - * @var string - */ - protected $filter = null; - - /** - * Specifies the field (or a list of fields) to apply the filter on - * @var mixed null if disabled, a string for a single field or an array of fields - */ - protected $filterField = null; - - /** - * Specifies the fields to sort by - * @var array - */ - protected $sorters = array(); - - /** - * A callback which is called when creating the filter - * @var function The callback - */ - protected $callback = null; - - /** - * Sets the start position - * @param int $start - */ - public function setStart ($start) { - $this->start = intval($start); - } - - /** - * Returns the start position - * @return int - */ - public function getStart () { - if ($this->start === null) { - return 0; - } else { - return $this->start; - } - } - - /** - * Sets the number of records to retrieve - * @param mixed $limit Either a positive integer, or null/-1 for no limit - */ - public function setLimit ($limit) { - if ($limit === null || $limit == -1) { - $this->limit = null; - } else { - $this->limit = intval($limit); - } - } - - /** - * Returns the number of records to retrieve - * @return int - */ - public function getLimit () { - return $this->limit; - } - - /** - * Sets the sorters for this filter. - * - * @param array $sorters An array of Sorter instances - */ - public function setSorters (array $sorters) { - // Make sure that each sorter is an instance of the Sorter class. - foreach ($sorters as $sorter) { - if (!($sorter instanceof Sorter)) { - throw new InvalidArgumentException("The passed sorters needs to be an array of Sorter instances"); - } - } - - $this->sorters = $sorters; - } - - /** - * Returns the sorters for this filter. - * @return array An array of Sorter instances - */ - public function getSorters () { - return $this->sorters; - } - - /** - * Sets the filter. Specify null if no filter is wanted. - * @param mixed $filter A string to filter for, or null to disable - */ - public function setFilter ($filter) { - $this->filter = $filter; - } - - /** - * Returns the filter. - * @return mixed Either a string to filter for, or null if disabled - */ - public function getFilter () { - return $this->filter; - } - - /** - * Sets the field(s) to filter for. - * - * If multiple fields are specified, they will be combined using an "OR" clause. - * - * @param mixed $field Either null to disable, a single string to specify a field, or an array of string fields - */ - public function setFilterField ($field) { - $this->filterField = $field; - } - - /** - * Returns the field(s) to filter for - * @return mixed See setFilterField - */ - public function getFilterField () { - return $this->filterField; - } - - /** - * Sets the filter callback - * @param function $callback A function which is called when creating a filter. The callback function receives the - * query builder as first argument. - */ - public function setFilterCallback ($callback) { - $this->callback = $callback; - } - - /** - * Returns the filter callback - * @return function The callback function - */ - public function getFilterCallback () { - return $this->callback; - } - - /** - * Constructs a new filter set. - * - * If a service is passed, the constructor automatically extracts the parameters from the service - * - * @todo Document which parameters we have - * - * @param Service $service A service to extract the information from, or null - */ - public function __construct (Service $service = null) { - if (is_object($service)) { - if ($service->hasParameter("start")) { - $this->setStart($service->getParameter("start", null)); - } - - if ($service->hasParameter("limit")) { - $this->setLimit($service->getParameter("limit", null)); - } - - if ($service->hasParameter("sort")) { - if (!is_array($service->getParameter("sort"))) { - $tmp = json_decode($service->getParameter("sort"), true); - } else { - $tmp = $service->getParameter("sort"); - } - - $aSorters = array(); - - foreach ($tmp as $key => $sortParam) { - $aSorters[] = new Sorter("q.".$sortParam["property"], $sortParam["direction"]); - } - - $this->setSorters($aSorters); - } - - if ($service->hasParameter("query")) { - $this->setFilter($service->getParameter("query")); - } - } - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Manager/Sorter.php b/src/backend/PartKeepr/Manager/Sorter.php @@ -1,79 +0,0 @@ -<?php -namespace PartKeepr\Manager; - -/** - * Represents a sorter, which is used with the ManagerFilter class. - * - * This allows the developer to specify multiple sorters. One sorter contains a sort field and a sort direction. - */ -class Sorter { - /** - * The field to sort by - * @var string - */ - private $sortField = null; - - /** - * The direction to sort by - * @var string - */ - private $sortDirection = null; - - /** - * Constructs a new sorter. - * - * @param string $field The field to sort by - * @param string $direction The direction, either "asc" or "desc" - */ - public function __construct ($field = null, $direction = null) { - if ($field !== null) { - $this->setSortField($field); - } - - if ($direction !== null) { - $this->setSortDirection($direction); - } - } - - /** - * Sets the sort field for this sorter - * @param string $field The field to sort by - */ - public function setSortField ($field) { - $this->sortField = $field; - } - - /** - * Sets the sort direction for this sorter - * @param string $direction Either "asc" or "desc" - */ - public function setSortDirection ($direction) { - switch (strtolower($direction)) { - case "desc": - case "d": - $this->sortDirection = "desc"; - break; - case "asc": - case "a": - default: - $this->sortDirection = "asc"; - break; - } - } - - /** - * Returns the sort field for this sorter - * @return string The field name - */ - public function getSortField () { - return $this->sortField; - } - - /** - * Returns the sort order for this sorter - * @return string Either "asc" or "desc" - */ - public function getSortDirection () { - return $this->sortDirection; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Part/PartFulltextSearch.php b/src/backend/PartKeepr/Part/PartFulltextSearch.php @@ -1,29 +0,0 @@ -<?php -namespace PartKeepr\Part; - -use PartKeepr\FulltextSearch\FulltextSearch; - -/** - * Implements the part fulltext search - */ -class PartFulltextSearch extends FulltextSearch { - /** - * Returns the FQDN of the part entity - * - * (non-PHPdoc) - * @see PartKeepr\FulltextSearch.FulltextSearch::getEntityName() - */ - protected function getEntityName () { - return 'PartKeepr\PartBundle\Entity\Part'; - } - - /** - * Returns the fields to be searched in - * - * (non-PHPdoc) - * @see PartKeepr\FulltextSearch.FulltextSearch::getFields() - */ - protected function getFields () { - return array("comment", "name", "description", "internalPartNumber"); - } -} diff --git a/src/backend/PartKeepr/PartKeepr.php b/src/backend/PartKeepr/PartKeepr.php @@ -1,280 +0,0 @@ -<?php -namespace PartKeepr; - -use PartKeepr\Util\Configuration as PartKeeprConfiguration; - - -class PartKeepr -{ - /** - * Initializes the PartKeepr system - * - * You *need* to call this method before doing anything else. - * - * An environment is used to load a different configuration file. - * Usually, you don't need to pass anything here. - * - * @param $environment string The environment to use, null otherwise. - */ - public static function initialize($environment = null) - { - self::initializeConfig($environment); - } - - /** - * Returns an array of all cronjobs which are required for proper execution of PartKeepr. - * - * @return Array The filenames of each cronjob which is required - */ - public static function getRequiredCronjobs() - { - return array( - "CreateStatisticSnapshot.php", - "UpdatePartCacheData.php", - "UpdateTipsOfTheDay.php", - "CheckForUpdates.php", - ); - } - - /** - * Initializes the configuration for a given environment. - * - * An environment is used to load a different configuration file. - * - * Usually, you don't need to pass anything here. - * - * - * @param $environment string The environment to use, null otherwise. - */ - public static function initializeConfig($environment = null) - { - if ($environment != null) { - $config = self::getRootDirectory()."/config-$environment.php"; - } else { - $config = self::getRootDirectory()."/config.php"; - } - - if (file_exists($config)) { - include($config); - } - - // Check if the files path is set. If not, fall back to <partkeepr-root>/data/ - if (PartKeeprConfiguration::getOption("partkeepr.files.path", null) === null) { - - PartKeeprConfiguration::setOption("partkeepr.files.path", - PartKeepr::getRootDirectory()."/data/"); - } - - // Check if the image path is set. If not, fall back to <configured-files-directory>/images/ - if (PartKeeprConfiguration::getOption("partkeepr.images.path", null) === null) { - - PartKeeprConfiguration::setOption("partkeepr.images.path", - PartKeeprConfiguration::getOption("partkeepr.files.path")."images/"); - } - - // Check if the image cache path is set. If not, fall back to <configured-images-directory>/images/ - if (PartKeeprConfiguration::getOption("partkeepr.images.cache", null) === null) { - - PartKeeprConfiguration::setOption("partkeepr.images.cache", - PartKeeprConfiguration::getOption("partkeepr.images.path")."cache/"); - - } - - } - - public static function getRootDirectory() - { - return dirname(dirname(dirname(__DIR__))); - } - - /** - * Returns the class metadata for all entity classes - * - * @return array an array of class metadata objects - */ - public static function getClassMetaData() - { - $classes = self::getEntityClasses(); - - $aClasses = array(); - - foreach ($classes as $class) { - $aClasses[] = PartKeepr::getEM()->getClassMetadata($class); - } - - return $aClasses; - } - - /** - * Returns a list of all classes we use for entities. - * - * @return array An array of strings with all class names - */ - public static function getEntityClasses() - { - return array( - 'PartKeepr\AuthBundle\Entity\User', - 'PartKeepr\Session\Session', - 'PartKeepr\EventNotification\Event', - 'PartKeepr\EventNotification\LastNotification', - 'PartKeepr\Footprint\Footprint', - 'PartKeepr\Footprint\FootprintImage', - 'PartKeepr\Footprint\FootprintAttachment', - 'PartKeepr\FootprintBundle\Entity\FootprintCategory', - 'PartKeepr\PartBundle\Entity\Part', - 'PartKeepr\PartBundle\Entity\PartUnit', - 'PartKeepr\PartBundle\Entity\PartManufacturer', - 'PartKeepr\PartBundle\Entity\PartDistributor', - 'PartKeepr\PartBundle\Entity\PartImage', - 'PartKeepr\PartBundle\Entity\PartAttachment', - 'PartKeepr\PartBundle\Entity\PartCategory', - 'PartKeepr\Printing\PageBasicLayout\PageBasicLayout', - 'PartKeepr\Printing\PrintingJob\PrintingJob', - 'PartKeepr\Printing\PrintingJobConfiguration\PrintingJobConfiguration', - 'PartKeepr\Project\Project', - 'PartKeepr\Project\ProjectPart', - 'PartKeepr\Project\ProjectAttachment', - 'PartKeepr\StorageLocationBundle\Entity\StorageLocation', - 'PartKeepr\StorageLocationBundle\Entity\StorageLocationImage', - 'PartKeepr\Stock\StockEntry', - 'PartKeepr\ManufacturerBundle\Entity\Manufacturer', - 'PartKeepr\ManufacturerBundle\Entity\ManufacturerICLogo', - 'PartKeepr\DistributorBundle\Entity\Distributor', - 'PartKeepr\ImageBundle\Entity\Image', - 'PartKeepr\ImageBundle\Entity\CachedImage', - 'PartKeepr\ImageBundle\Entity\TempImage', - 'PartKeepr\UploadedFileBundle\Entity\TempUploadedFile', - 'PartKeepr\Statistic\StatisticSnapshot', - 'PartKeepr\Statistic\StatisticSnapshotUnit', - 'PartKeepr\SiPrefixBundle\Entity\SiPrefix', - 'PartKeepr\Unit\Unit', - 'PartKeepr\PartBundle\Entity\PartParameter', - 'PartKeepr\TipOfTheDayBundle\Entity\TipOfTheDay', - 'PartKeepr\TipOfTheDayBundle\Entity\TipOfTheDayHistory', - 'PartKeepr\AuthBundle\Entity\UserPreference', - 'PartKeepr\CoreBundle\Entity\SystemNotice', - 'PartKeepr\CronLoggerBundle\Entity\CronLogger', - - ); - } - - /** - * Formats a message and applies internationalization. - * - * This method accepts sprintf-like parameters, which are appended after the $string parameter. - * - * @param $string string The string to internationalize - * - * @todo stub - */ - public static function i18n($string) - { - if (func_num_args() > 1) { - $args = func_get_args(); - array_shift($args); - - return vsprintf($string, $args); - } else { - return $string; - } - } - - /** - * Returns a new GUID. - * - * @return string The new GUID - */ - public static function createGUIDv4() - { - return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - - // 32 bits for "time_low" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), - - // 16 bits for "time_mid" - mt_rand(0, 0xffff), - - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 4 - mt_rand(0, 0x0fff) | 0x4000, - - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - mt_rand(0, 0x3fff) | 0x8000, - - // 48 bits for "node" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) - ); - } - - /** - * This is a re-implementation of gettype(). - * - * The PHP documentation states that the "gettype" return values will change in the future, so we need - * to make sure we don't get bitten by the change. - * - * @param mixed $var - * - * @return string The type - */ - public static function getType($var) - { - if (is_array($var)) { - return "array"; - } - if (is_bool($var)) { - return "boolean"; - } - if (is_float($var)) { - return "float"; - } - if (is_int($var)) { - return "integer"; - } - if (is_null($var)) { - return "NULL"; - } - if (is_numeric($var)) { - return "numeric"; - } - if (is_object($var)) { - return "object"; - } - if (is_resource($var)) { - return "resource"; - } - if (is_string($var)) { - return "string"; - } - - return "unknown type"; - } - - /** - * 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 static 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/backend/PartKeepr/Service/AdminService.php b/src/backend/PartKeepr/Service/AdminService.php @@ -1,14 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use PartKeepr\Session\SessionManager; - -class AdminService extends Service { - public function mayCall ($call) { - if (SessionManager::getCurrentSession()->getUser()->isAdmin()) { - return true; - } else { - return false; - } - } -} diff --git a/src/backend/PartKeepr/Service/Annotations/ApiType.php b/src/backend/PartKeepr/Service/Annotations/ApiType.php @@ -1,42 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a type. This is used by the TypeReflector to get information - * about the type. - * - * @see PartKeepr\Service\TypeReflector - * - * @Annotation - * @Target({"METHOD"}) - */ -class ApiType -{ - /** - * The description of the type - * @var string - */ - public $description; - - /** - * The documentation of the type - * @var string - */ - public $documentation; - - /** - * Returns the description of the type - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * Returns the documentation of the type - * @return string - */ - public function getDocumentation () { - return $this->documentation; - } -} diff --git a/src/backend/PartKeepr/Service/Annotations/ApiTypeOutputField.php b/src/backend/PartKeepr/Service/Annotations/ApiTypeOutputField.php @@ -1,56 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a single API output field. This is used by the TypeReflector to get information - * about the type. - * - * @see PartKeepr\Service\TypeReflector - * - * @Annotation - * @Target({"ANNOTATION"}) - */ -class ApiTypeOutputField -{ - /** - * The name of the field - * @var string - */ - public $name; - - /** - * The type of the field - * @var string - */ - public $type; - - /** - * The description of the field - * @var string - */ - public $description; - - /** - * Returns the name of the output field - * @return string - */ - public function getName () { - return $this->name; - } - - /** - * Returns the description of the output field - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * Returns the type of the output field - * @return string - */ - public function getType () { - return $this->type; - } -} diff --git a/src/backend/PartKeepr/Service/Annotations/ApiTypeOutputFields.php b/src/backend/PartKeepr/Service/Annotations/ApiTypeOutputFields.php @@ -1,29 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a list of type ApiTypeOutputField. This is used by the TypeReflector to get information - * about the type. - * - * @see PartKeepr\Service\TypeReflector - * - * @Annotation - * @Target({"METHOD"}) - */ -class ApiTypeOutputFields -{ - /** - * The output fields - * @var array<PartKeepr\Service\Annotations\ApiTypeOutputField> - */ - public $outputFields; - - /** - * Returns the output fields - * @return \PartKeepr\Service\Annotations\ApiTypeOutputField[] The output fields - */ - public function getOutputFields () { - return $this->outputFields; - } -} - diff --git a/src/backend/PartKeepr/Service/Annotations/Service.php b/src/backend/PartKeepr/Service/Annotations/Service.php @@ -1,45 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a service. This is used by the ServiceReflector to get information - * about the services. - * - * @see PartKeepr\Service\ServiceReflector - * - * @Annotation - * @Target({"CLASS"}) - */ -class Service -{ - /** - * The description of the service - * @var string - */ - public $description; - - /** - * Returns the description of the service - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * The documentation of the service - * - * @var string - */ - public $documentation; - - /** - * Returns the documentation of the service - * - * @return string - */ - public function getDocumentation() - { - return $this->documentation; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/Annotations/ServiceCall.php b/src/backend/PartKeepr/Service/Annotations/ServiceCall.php @@ -1,67 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a service call. - * @Annotation - * @Target({"METHOD"}) - */ -class ServiceCall -{ - /** - * The description of the call - * @var string - */ - public $description; - - /** - * The documentation of the call - * @var string - */ - public $documentation; - - /** - * The return values - * @var array<PartKeepr\Service\Annotations\ServiceReturnValue> - */ - public $returnValues; - - /** - * The parameters - * @var array<PartKeepr\Service\Annotations\ServiceParameter> - */ - public $parameters; - - /** - * Returns the description of this call - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * Returns the documentation for this call - * @return string - */ - public function getDocumentation () { - return $this->documentation; - } - - /** - * Returns the parameters for this service call - * @return \PartKeepr\Service\Annotations\ServiceParameter[] The service parameters - */ - public function getParameters () { - return $this->parameters; - } - - /** - * Returns the return values for this service call - * @return \PartKeepr\Service\Annotations\ServiceReturnValue[] The returned values - */ - public function getReturnValues () { - return $this->returnValues; - } -} - diff --git a/src/backend/PartKeepr/Service/Annotations/ServiceParameter.php b/src/backend/PartKeepr/Service/Annotations/ServiceParameter.php @@ -1,67 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a parameter to a service call -* @Annotation -* @Target({"ANNOTATION"}) -*/ -class ServiceParameter -{ - /** - * The name of the parameter - * @var string - */ - public $name; - - /** - * Defines if the parameter is required - * @var boolean - */ - public $required; - - /** - * The type of the parameter - * @var string - */ - public $type; - - /** - * The description of the parameter - * @var string - */ - public $description; - - /** - * Returns the name of the service parameter - * @return string - */ - public function getName () { - return $this->name; - } - - /** - * Returns if the parameter is required - * @return bool - */ - public function getRequiredFlag () { - return $this->required; - } - - /** - * Returns the description of the parameter - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * Returns the type of the parameter - * @return string - */ - public function getType () { - return $this->type; - } - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/Annotations/ServiceReturnValue.php b/src/backend/PartKeepr/Service/Annotations/ServiceReturnValue.php @@ -1,52 +0,0 @@ -<?php -namespace PartKeepr\Service\Annotations; - -/** - * Describes a single service return value - * - * @Annotation - * @Target({"ANNOTATION"}) - */ -class ServiceReturnValue -{ - /** - * The name of the return value - * @var string - */ - public $name; - - /** - * The description of the return value - * @var string */ - public $description; - - /** - * The type of the return value - * @var string - */ - public $type; - - /** - * Returns the description of the return value - * @return string - */ - public function getDescription () { - return $this->description; - } - - /** - * Returns the name of the return value - * @return string - */ - public function getName () { - return $this->name; - } - - /** - * Returns the type of the return value - * @return string - */ - public function getType () { - return $this->type; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/AnonService.php b/src/backend/PartKeepr/Service/AnonService.php @@ -1,6 +0,0 @@ -<?php -namespace PartKeepr\Service; - -class AnonService extends Service { - -} diff --git a/src/backend/PartKeepr/Service/Exceptions/ServiceException.php b/src/backend/PartKeepr/Service/Exceptions/ServiceException.php @@ -1,6 +0,0 @@ -<?php -namespace PartKeepr\Service\Exceptions; - -use PartKeepr\Util\SerializableException; - -class ServiceException extends SerializableException {} diff --git a/src/backend/PartKeepr/Service/FilterExtractor.php b/src/backend/PartKeepr/Service/FilterExtractor.php @@ -1,38 +0,0 @@ -<?php - -namespace PartKeepr\Service; - -use PartKeepr\Service\Service; - -/** - * This class can be used to extract the filter parameters from requests. - */ -class FilterExtractor{ - private $filters; - - public function __construct( Service $service ){ - $this->filters = array(); - - if ($service->hasParameter("filter")) { - $tmp = json_decode($service->getParameter("filter"), true); - - foreach ($tmp as $item) { - if ( array_key_exists("property", $item) - && array_key_exists("value", $item)) { - $this->filters[ $item['property'] ] = $item["value"]; - } - } - } - } - - public function get( $property ){ - return $this->filters[$property]; - } - - public function has( $property ){ - return array_key_exists( $property, $this->filters ); - } -} - -$filter = ""; - diff --git a/src/backend/PartKeepr/Service/RestfulService.php b/src/backend/PartKeepr/Service/RestfulService.php @@ -1,9 +0,0 @@ -<?php -namespace PartKeepr\Service; - -interface RestfulService { - public function get (); - public function create (); - public function update (); - public function destroy (); -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/Service.php b/src/backend/PartKeepr/Service/Service.php @@ -1,109 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use PartKeepr\AuthBundle\Entity\User; -use PartKeepr\Service\Exceptions\ServiceException; -use PartKeepr\Session\SessionManager; - -class Service { - private $params; - - public function __construct (Array $params) { - $this->params = $params; - } - - public function mayCall ($call) { - if (SessionManager::getCurrentSession()->getUser() === null) { - return false; - } else { - /* @todo: Implement permission checking */ - return true; - } - - - } - - protected function requireParameter ($name) { - if (!$this->hasParameter($name)) { - throw new ServiceException(sprintf("Parameter %s is required.", $name)); - } - } - - public function getParameter ($name, $default = null) { - if (!$this->hasParameter($name)) { - return $default; - } else { - return $this->params[$name]; - } - } - - /** - * Returns all parameters passed to the service - * @return array An array with all parameters (key=>value format) - */ - public function getParameters () { - return $this->params; - } - - /** - * Returns the current user for this session - * - * @return \PartKeepr\AuthBundle\Entity\User The user - */ - public function getUser () { - return SessionManager::getCurrentSession()->getUser(); - } - - /** - * Checks if the environment has an active, logged in user. - * - * @param none - * @return boolean True if a logged in user exists, false otherwise - */ - public function hasUser () { - if (!$this->hasSession()) { - return false; - } - - var_dump($this->getUser()); - if ($this->getUser() !== null) { - return true; - } else { - return false; - } - } - - /** - * Checks if there is an active session. - * - * @param none - * @return boolean true if an active session exists, false otherwise - */ - public function hasSession () { - return SessionManager::hasSession(); - } - - public function hasParameter ($name) { - if (array_key_exists($name, $this->params)) { - return true; - } else { - return false; - } - } - - public function hasHeader ($name) { - $targetName = "HTTP_".strtoupper($name); - - return array_key_exists($targetName, $_SERVER); - } - - public function getHeader ($name) { - $targetName = "HTTP_".strtoupper($name); - - if (array_key_exists($targetName, $_SERVER)) { - return $_SERVER[$targetName]; - } else { - throw new \Exception("Header ".$targetName." not found"); - } - } -} diff --git a/src/backend/PartKeepr/Service/ServiceCallReflector.php b/src/backend/PartKeepr/Service/ServiceCallReflector.php @@ -1,95 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use Doctrine\Common\Annotations\AnnotationRegistry, - PartKeepr\PartKeepr, - PartKeepr\Service\Service; - -/** - * Reflects on a specific service call - */ -class ServiceCallReflector { - - /** - * Holds the annotation reader - * @var \Doctrine\Common\Annotations\AnnotationReader - */ - private $reader; - - /** - * Holds the method to reflect on - * @var \ReflectionMethod - */ - private $reflectionMethod; - - /** - * Creates a new service call reflector - * - * @param \ReflectionMethod $reflectionMethod The method to reflect on - * @param \Doctrine\Common\Annotations\AnnotationReader $reader The - * @throws \Exception If the method is not reflectable - */ - public function __construct (\ReflectionMethod $reflectionMethod, \Doctrine\Common\Annotations\AnnotationReader $reader) { - if (!self::isServiceCall($reflectionMethod, $reader)) { - throw new \Exception("Given method is not a reflectable method"); - } - - $this->reader = $reader; - $this->reflectionMethod = $reflectionMethod; - } - - /** - * Returns the name of the method - * @return string The name - */ - public function getName () { - return $this->reflectionMethod->getName(); - } - - /** - * Returns the description of the given service call - * @return string The description - */ - public function getDescription () { - return $this->reader->getMethodAnnotation($this->reflectionMethod, "PartKeepr\Service\Annotations\ServiceCall")->getDescription(); - } - - /** - * Returns the documentation for the API call - * @return string The documentaton - */ - public function getDocumentation () { - return $this->reader->getMethodAnnotation($this->reflectionMethod, "PartKeepr\Service\Annotations\ServiceCall")->getDocumentation(); - } - - /** - * Returns the parameters of the API call - * @return \PartKeepr\Service\Annotations\ServiceParameter[] The service parameters - */ - public function getParameters () { - return $this->reader->getMethodAnnotation($this->reflectionMethod, "PartKeepr\Service\Annotations\ServiceCall")->getParameters(); - } - - /** - * Returns the returned values - * @return PartKeepr\Service\Annotations\ServiceReturnValue[] The returned values - */ - public function getReturnValues () { - return $this->reader->getMethodAnnotation($this->reflectionMethod, "PartKeepr\Service\Annotations\ServiceCall")->getReturnValues(); - } - - /** - * Returns if the given method is a ServiceCall - * @static - * @param \ReflectionMethod $reflectionMethod The method to reflect on - * @param \Doctrine\Common\Annotations\AnnotationReader $reader The annotation reader - * @return bool true if the method is a service call, false otherwise - */ - public static function isServiceCall (\ReflectionMethod $reflectionMethod, \Doctrine\Common\Annotations\AnnotationReader $reader ) { - if ($reader->getMethodAnnotation($reflectionMethod, "PartKeepr\Service\Annotations\ServiceCall") === null) { - return false; - } else { - return true; - } - } -} diff --git a/src/backend/PartKeepr/Service/ServiceManager.php b/src/backend/PartKeepr/Service/ServiceManager.php @@ -1,181 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use PartKeepr\AuthBundle\Entity\User; -use PartKeepr\AuthBundle\Entity\User\UserManager; -use PartKeepr\PartKeepr; -use PartKeepr\REST\Request; -use PartKeepr\Service\Exceptions\ServiceException; -use PartKeepr\Session\SessionManager; -use PartKeepr\Util\Singleton; - -class ServiceManager extends Singleton { - private $request = null; - private $service = null; - private $mimetype = "application/json"; - - /** - * Initializes the request and service variables - */ - public function initialize () { - $this->request = new Request(array('restful' => true)); - $this->service = $this->request->getService(); - - // Special case because of file uploads - if ($this->service instanceof \PartKeepr\TempFile\TempFileService) { - $this->mimetype = "text/html"; - } - } - /** - * Sends the response headers. - * - * Sends cache control headers as well as the mime type. - * - * @param $mimeType string The mimetype to send, defaults to application/json - */ - public function sendHeaders () { - header("Content-Type: ".$this->mimetype."; charset=UTF-8"); - header("Cache-Control: no-cache, must-revalidate"); - header("Access-Control-Allow-Origin: *"); - header("Access-Control-Allow-Headers: lang,call,service,X-Requested-With,X-PartKeepr-Locale,X-PartKeepr-Name,X-PartKeepr-Call"); - } - - /** - * Returns the effective call on a service which we need to process - * - * The following rules decide which call to make: - * - Use the "call" header, if set - * - Use the "call" parameter, if set - * - Use the action from a REST request (e.g. /controller/action/id) - * - Use the HTTP Method name, where: - * - "POST" calls "create" - * - "GET" calls "get" - * - "PUT" calls "update" - * - "DELETE" calls "destroy" - * - Any other HTTP verbs are mapped 1:1 - * - * @return string the method name to be called - */ - public function getCall () { - $call = null; - - if ($this->service->hasHeader("call")) { - $call = $this->service->getHeader("call"); - } elseif (array_key_exists("call", $_REQUEST) && $_REQUEST["call"] != "") { - $call = $_REQUEST["call"]; - } elseif ($this->request->action != "") { - $call = $this->request->action; - } else { - switch (strtoupper($this->request->getMethod())) { - case "POST": - $call = "create"; - break; - case "GET": - $call = "get"; - break; - case "PUT": - $call = "update"; - break; - case "DELETE": - $call = "destroy"; - break; - default: - $call = $this->request->getMethod(); - break; - } - } - - return $call; - } - - public function call () { - $call = $this->getCall(); - - $allowCall = true; - - if (!is_subclass_of($this->service, "PartKeepr\\Service\\AnonService")) { - $session = null; - $sessionid = false; - - $sessionid = $this->getSession($this->service); - - - if ($sessionid === null) - { - $session = SessionManager::getInstance()->startSession(); - throw new ServiceException("You called a non-anonymous service, but did not pass the 'session' parameter."); - } else { - $session = SessionManager::getInstance()->resumeSession($sessionid); - } - - if (!$this->service->mayCall($call)) { - $allowCall = false; - } - - // Update Seen flag of the current user. - if ($session !== null) { - $user = $session->getUser(); - if ($user !== null) { - $user->updateSeen(); - } - } - } - - if (!$allowCall) { - throw new ServiceException("Permission denied"); - } - - if (!method_exists($this->service, $call)) { - throw new \Exception(sprintf("The service %s doesn't implement %s", get_class($this->service), $call)); - } - $result = $this->service->$call(); - - PartKeepr::getEM()->flush(); - - return $result; - - } - - private function getSession ($service) { - if ($service->hasHeader("username") && $service->hasHeader("password") && !$service->hasHeader("session")) { - return $this->authenticateByUsername($service->getHeader("username"), $service->getHeader("password")); - } - - if (array_key_exists("username", $_REQUEST) && array_key_exists("password", $_REQUEST) && !array_key_exists("session", $_REQUEST)) { - return $this->authenticateByUsername($_REQUEST["username"], $_REQUEST["password"]); - } - - if ($service->hasHeader("session")) { - return $service->getHeader("session"); - } - - if (array_key_exists("session", $_REQUEST)) { - return $_REQUEST["session"]; - } - } - - private function authenticateByUsername ($username, $password) { - /* Build a temporary user */ - $user = new User; - $user->setRawUsername($username); - $user->setHashedPassword($password); - - $authenticatedUser = UserManager::getInstance()->authenticate($user); - - if ($authenticatedUser !== false) { - /* Start Session */ - $session = SessionManager::getInstance()->startSession($authenticatedUser); - - return $session->getSessionID(); - } else { - throw new InvalidLoginDataException(); - } - } - - public function getRegisteredServices () { - return array( - "PartKeepr\\Auth\\AuthService" - ); - } - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/ServiceReflector.php b/src/backend/PartKeepr/Service/ServiceReflector.php @@ -1,113 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use Doctrine\Common\Annotations\AnnotationRegistry, - PartKeepr\PartKeepr, - PartKeepr\Service\Service; - -/** - * Reflects a service. - */ -class ServiceReflector { - /** - * The class name to reflect on - * @var string - */ - private $className; - - /** - * The reflected class - * @var \ReflectionClass - */ - private $reflClass; - - /** - * The annotation reader - * @var \Doctrine\Common\Annotations\AnnotationReader - */ - private $reader; - - /** - * Creates a new service reflector - * - * @param $className string The FQCN of the service class to reflect - * @throws \Exception If the passed class name isn't a subclass of PartKeepr\Service\Service - */ - public function __construct ($className) { - $this->reflClass = new \ReflectionClass($className); - - if (!$this->reflClass->isSubclassOf("PartKeepr\\Service\\Service")) { - throw new \Exception(sprintf("%s isn't a subclass of PartKeepr\\Service\\Service, can't reflect", $className)); - } - $this->className = $className; - $this->reader = new \Doctrine\Common\Annotations\AnnotationReader(); - $this->registerAnnotationLoaders(); - } - - /** - * Returns the name of the service - * @return string The name of the service - */ - public function getName () { - return $this->reflClass->getShortName(); - } - - /** - * Returns the description of the service - * @return string The description of the service - */ - public function getDescription () { - return $this->reader->getClassAnnotation($this->reflClass, "PartKeepr\\Service\\Annotations\\Service")->getDescription(); - } - - /** - * Returns all calls for the service - * @return ServiceCallReflector[] An array of ServiceCallReflector objects - */ - public function getCalls () { - $calls = array(); - - foreach ($this->reflClass->getMethods() as $method) { - if (ServiceCallReflector::isServiceCall($method, $this->reader)) { - $calls[] = new ServiceCallReflector($method, $this->reader); - } - } - - return $calls; - } - - /** - * Returns a call by name - * @param $name The call name to retrieve - * @return null|ServiceCallReflector The call name - */ - public function getCall ($name) { - foreach ($this->getCalls() as $call) { - if ($call->getName() == $name) { - return $call; - } - } - - return null; - } - /** - * Register the annotation loader. - * @todo This will happen multiple times, needs a fix to do this only once - */ - public function registerAnnotationLoaders () { - AnnotationRegistry::registerLoader(function($class) { - $file = str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php"; - - $fullFile = PartKeepr::getRootDirectory(). "/src/backend/" . $file; - - if (file_exists($fullFile)) { - // file exists makes sure that the loader fails silently - require $fullFile; - return true; - - } - }); - - AnnotationRegistry::registerAutoloadNamespace('PartKeepr\Service\Annotations', PartKeepr::getRootDirectory() . "/src/backend/PartKeepr/Service/Annotations"); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Service/TypeReflector.php b/src/backend/PartKeepr/Service/TypeReflector.php @@ -1,90 +0,0 @@ -<?php -namespace PartKeepr\Service; - -use Doctrine\Common\Annotations\AnnotationRegistry, - PartKeepr\PartKeepr, - PartKeepr\Service\Service; - -/** - * Reflects a type. - */ -class TypeReflector { - private $className; - private $reflClass; - private $reader; - - /** - * Creates a new service reflector - * - * @param $className string The FQCN of the service class to reflect - */ - public function __construct ($className) { - $this->reflClass = new \ReflectionClass($className); - - $this->className = $className; - $this->reader = new \Doctrine\Common\Annotations\AnnotationReader(); - $this->reader->addNamespace('Doctrine\ORM\Mapping'); - $this->reader->addNamespace('PartKeepr\\Service\\Annotations'); - - $this->registerAnnotationLoaders(); - } - - /** - * Returns the name of the type - * - * @return string The name of the type - */ - public function getName () { - return $this->reflClass->getShortName(); - } - - /** - * Returns the description of the type - * @return string The description of the type - */ - public function getDescription () { - return $this->reader->getClassAnnotation($this->reflClass, "PartKeepr\\Service\\Annotations\\ApiType")->getDescription(); - } - - /** - * Returns the documentation of the type - * @return string The documentation of the type - */ - public function getDocumentation () { - return $this->reader->getClassAnnotation($this->reflClass, "PartKeepr\\Service\\Annotations\\ApiType")->getDocumentation(); - } - - /** - * Returns the output fields - * @return \PartKeepr\Service\Annotations\ApiTypeOutputField The output fields - */ - public function getOutputFields () { - $serializeReflMethod = $this->reflClass->getMethod("serialize"); - - $outputs = $this->reader->getMethodAnnotation($serializeReflMethod, "PartKeepr\\Service\\Annotations\\ApiTypeOutputFields"); - - return $outputs->getOutputFields(); - } - - /** - * Register the annotation loader. - * @todo This will happen multiple times, needs a fix to do this only once - */ - public function registerAnnotationLoaders () { - AnnotationRegistry::registerLoader(function($class) { - $file = str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php"; - - $fullFile = PartKeepr::getRootDirectory(). "/src/backend/" . $file; - - if (file_exists($fullFile)) { - // file exists makes sure that the loader fails silently - require $fullFile; - return true; - - } - }); - - AnnotationRegistry::registerAutoloadNamespace('PartKeepr\\Service\\Annotations', PartKeepr::getRootDirectory() . "/src/backend/PartKeepr/Service/Annotations"); - require_once('Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Setup/AbstractSetup.php b/src/backend/PartKeepr/Setup/AbstractSetup.php @@ -1,44 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use Doctrine\ORM\EntityManager; - -/** - * Represents a basic setup step - */ -abstract class AbstractSetup { - private $console; - - /** - * Represents the Doctrine Entity Manager - * @var Doctrine\ORM\EntityManager - */ - protected $entityManager; - - /** - * Represents all messages which are logged during setup - * @var array - */ - private $messages = array(); - - /** - * Constructs the setup step. - * @param EntityManager $em The entity manager - */ - public function __construct (EntityManager $em) { - $this->entityManager = $em; - } - - abstract public function run (); - - public function setConsole ($console) { - $this->console = $console; - } - - public function logMessage ($message) { - if ($this->console) { - echo "- ".$message."\n"; - } - $this->messages[] = $message; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Setup/ConfigFileSetup.php b/src/backend/PartKeepr/Setup/ConfigFileSetup.php @@ -1,65 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\Util\Configuration, - PartKeepr\PartKeepr, - PartKeepr\Util\SerializableException; - -/** - * Creates or returns a new config file - */ -class ConfigFileSetup extends AbstractSetup { - - /** - * (non-PHPdoc) - * @see PartKeepr\Setup.AbstractSetup::run() - */ - public function run () { - switch ($_REQUEST["mode"]) { - case "save": - $this->saveConfig(); - break; - case "display": - return $this->displayConfig(); - break; - } - - return null; - } - - /** - * Returns the configuration file as string, so that it can be displayed - * during setup. - * - * @param none - * @return array An array, where the "config" key contains the configuration. - */ - private function displayConfig () { - return array("config" => Configuration::dumpConfig()); - } - - /** - * Saves the configuration file. - * - * @throws SerializableException An exception which describes what has been going wrong - */ - private function saveConfig () { - $configFile = PartKeepr::getRootDirectory()."/config.php"; - - if (file_exists($configFile)) { - if (!is_writable($configFile)) { - $message = "The config.php file could not be written, because it already exists and the webserver has "; - $message .= "no write access to it."; - - throw new SerializableException($message, 10000); - } - } else { - if (!is_writable(PartKeepr::getRootDirectory())) { - $message = "The config.php file could not be written, because the webserver has no write access to it."; - - throw new SerializableException($message, 10001); - } - } - file_put_contents($configFile, Configuration::dumpConfig()); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Setup/FootprintSetup.php b/src/backend/PartKeepr/Setup/FootprintSetup.php @@ -1,156 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use \PartKeepr\FootprintBundle\Entity\FootprintManager, - \PartKeepr\FootprintBundle\Entity\FootprintCategoryManager, - \PartKeepr\FootprintBundle\Entity\FootprintCategory, - \PartKeepr\FootprintBundle\Entity\Footprint, - \PartKeepr\FootprintBundle\Entity\FootprintImage, - \PartKeepr\FootprintBundle\Entity\FootprintAttachment, - PartKeepr\PartKeepr, - PartKeepr\Setup\Setup; - -class FootprintSetup extends AbstractSetup { - /** - * Holds the migrated footprints - * @var array - */ - private static $migratedFootprints = array(); - - const FOOTPRINT_PATH = "../setup-data/footprints/"; - const FOOTPRINT_FILE = "../setup-data/footprints/footprints.yaml"; - - /** - * Creates the root node for the footprints - */ - public function setupRootNode () { - FootprintCategoryManager::getInstance()->ensureRootExists(); - } - - public function run () { - $this->setupRootNode(); - $this->importFootprintData(); - } - - /** - * Returns a footprint by it's partdb id - * @param int $id The footprint id from the old partdb - */ - public static function getFootprintForOldId ($id) { - return FootprintSetup::$migratedFootprints[$id]; - } - - /** - * Creates a node structure for the given path - * - * @param $path array The components of the path - * @param $node Node The parent node - */ - public function addFootprintPath (Array $path, $node) { - if (count($path) == 0) { - return $node; - } - $name = array_shift($path); - - $childNode = null; - - foreach ($node->getChildren() as $child) { - if ($child->getNode()->getName() == $name) { - $childNode = $child; - } - } - - if ($childNode === null) { - $category = new FootprintCategory(); - $category->setParent($node->getNode()->getId()); - $category->setName($name); - $childNode = FootprintCategoryManager::getInstance()->addCategory($category); - } - - return $this->addFootprintPath($path, $childNode); - } - - /** - * Checks if the specified footprint exists - * @param string $name The footprint name - */ - public function footprintExists ($name) { - $dql = "SELECT COUNT(fp) FROM PartKeepr\Footprint\Footprint fp WHERE fp.name = :name"; - $query = $this->entityManager->createQuery($dql); - $query->setParameter("name", $name); - - if ($query->getSingleScalarResult() == 0) { - return false; - } else { - return true; - } - } - - /** - * Imports the footprints - * @throws \Exception - */ - public function importFootprintData () { - $count = 0; - $skipped = 0; - - /* Import pre-defined footprints */ - $data = Setup::loadYAML(self::FOOTPRINT_FILE); - - foreach ($data as $footprintName => $footprintData) { - /* Check if the footprint with the name already exists. If yes, skip the import for the single footprint */ - if ($this->footprintExists($footprintName)) { - $skipped++; - continue; - } - $footprint = new Footprint(); - $footprint->setName($footprintName); - - if (array_key_exists("description", $footprintData)) { - $footprint->setDescription($footprintData["description"]); - } - - if (array_key_exists("category", $footprintData)) { - $footprintCategory = $this->addFootprintPath(explode("/", $footprintData["category"]), FootprintCategoryManager::getInstance()->getRootNode()); - $footprint->setCategory($footprintCategory->getNode()); - } - - if (array_key_exists("image", $footprintData)) { - $footprintImage = new FootprintImage(); - $footprintImage->setFootprint($footprint); - $footprintImage->replace(self::FOOTPRINT_PATH . $footprintData["image"]); - - $footprint->setImage($footprintImage); - } - - if (array_key_exists("attachments", $footprintData) && is_array($footprintData["attachments"])) { - foreach ($footprintData["attachments"] as $attachment) { - if (!is_array($attachment)) { - throw new \Exception("Error: The property 'attachments' of $footprintName is not an array!"); - } - if (array_key_exists("url", $attachment)) { - try { - $footprintAttachment = new FootprintAttachment(); - $footprintAttachment->setFootprint($footprint); - $footprintAttachment->replaceFromURL($attachment["url"]); - if (array_key_exists("description", $attachment)) { - $footprintAttachment->setDescription($attachment["description"]); - } - - $footprint->getAttachments()->add($footprintAttachment); - } catch (\Exception $e) { - //echo "error with url ".$attachment["url"]."\n"; - } - } - - } - } - - $this->entityManager->persist($footprint); - $count++; - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Imported %d footprints, skipped %d because they already existed", $count, $skipped)); - } -} diff --git a/src/backend/PartKeepr/Setup/ManufacturerSetup.php b/src/backend/PartKeepr/Setup/ManufacturerSetup.php @@ -1,56 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - PartKeepr\ManufacturerBundle\Entity\Manufacturer, - PartKeepr\Manufacturer\ManufacturerManager, - PartKeepr\ManufacturerBundle\Entity\ManufacturerICLogo, - PartKeepr\Setup\SiPrefixSetup; - -/** - * Sets up the manufacturers - */ -class ManufacturerSetup extends AbstractSetup { - - const MANUFACTURER_PATH = "../setup-data/manufacturers/"; - const MANUFACTURER_FILE = "../setup-data/manufacturers/manufacturers.yaml"; - - public function run () { - $this->setupManufacturers(); - } - - /** - * Sets up the manufacturers using the YAML file. - * @param $yaml string The path to the manufacturers YAML file - */ - public function setupManufacturers () { - $count=0; - $skipped=0; - $data = Setup::loadYAML(self::MANUFACTURER_FILE); - - foreach ($data as $mfgname => $logos) { - try { - ManufacturerManager::getInstance()->getManufacturerByName($mfgname); - $skipped++; - } catch (\Exception $e) { - $manufacturer = new Manufacturer(); - $manufacturer->setName($mfgname); - - $this->entityManager->persist($manufacturer); - - foreach ($logos as $logo) { - $mfglogo = new ManufacturerICLogo(); - $mfglogo->setManufacturer($manufacturer); - $mfglogo->replace(self::MANUFACTURER_PATH . "images/". $logo); - $mfglogo->setOriginalFilename($logo); - - $this->entityManager->persist($mfglogo); - } - $count++; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Imported %d Manufacturers, skipped %d because they already exist", $count, $skipped)); - } -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/DistributorMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/DistributorMigration.php @@ -1,34 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - PartKeepr\DistributorBundle\Entity\Distributor, - PartKeepr\Distributor\DistributorManager, - PartKeepr\Setup\AbstractSetup; - -class DistributorMigration extends AbstractSetup { - /** - * Migrates the existing distributors - */ - public function run () { - $count = 0; - $skipped = 0; - $r = mysql_query("SELECT * FROM suppliers"); - while ($supplier = mysql_fetch_assoc($r)) { - $name = PartDBMigration::convertText($supplier["name"]); - try { - $distributor = DistributorManager::getInstance()->getDistributorByName($name); - $skipped++; - } catch (\Exception $e) { - $distributor = new Distributor(); - $distributor->setName($name); - - $this->entityManager->persist($distributor); - $count++; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Migrated %d distributors, skipped %d because they already exist", $count, $skipped)); - } -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/FootprintMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/FootprintMigration.php @@ -1,43 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - \PartKeepr\FootprintBundle\Entity\Footprint, - \PartKeepr\FootprintBundle\Entity\FootprintManager, - \PartKeepr\FootprintBundle\Entity\FootprintCategoryManager, - PartKeepr\Setup\FootprintSetup; - -class FootprintMigration extends FootprintSetup { - /** - * Migrates the existing footprints - */ - public function run () { - $count = 0; - $skipped = 0; - - // Get or create node for the imported footprints - $footprintCategory = FootprintSetup::addFootprintPath(explode("/", "Imported Footprints"), FootprintCategoryManager::getInstance()->getRootNode()); - - $r = mysql_query("SELECT * FROM footprints"); - - while ($sFootprint = mysql_fetch_assoc($r)) { - $name = PartDBMigration::convertText($sFootprint["name"]); - - try { - FootprintManager::getInstance()->getFootprintByName($name); - $skipped++; - } catch (\Exception $e) { - $footprint = new Footprint(); - $footprint->setName($name); - - $footprint->setCategory($footprintCategory->getNode()); - - $this->entityManager->persist($footprint); - $count++; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Migrated %d footprints, skipped %d because they already exist", $count, $skipped)); - } -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/PartCategoryMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/PartCategoryMigration.php @@ -1,50 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - \PartKeepr\PartBundle\Entity\PartCategory, - \PartKeepr\PartBundle\Entity\PartCategoryManager, - PartKeepr\Setup\AbstractSetup; - -class PartCategoryMigration extends AbstractSetup { - private $categories = array(); - private static $migratedCategories = array(); - /** - * Migrates the old categories - */ - public function run () { - $this->addCategoryRecursive(0, array()); - - foreach ($this->categories as $oldid => $category) { - $newcategory = PartCategoryManager::getInstance()->createCategoryTreeByArray($category); - - self::$migratedCategories[$oldid] = $newcategory; - } - - } - - /** - * Creates the category tree, recursive - * @param array $aCategories the categories - * @param id $currentId The current ID to migrate - * @param Node $parent The parent node - */ - private function addCategoryRecursive ($parentId, $parents) { - $r = mysql_query("SELECT * FROM categories WHERE parentnode = ".intval($parentId)); - - while ($category = mysql_fetch_array($r)) { - $aCopy = $parents; - $aCopy[] = $category["name"]; - - $this->categories[$category["id"]] = $aCopy; - $this->addCategoryRecursive($category["id"], $aCopy); - } - } - - public static function getMigratedCategory ($id) { - if (!array_key_exists($id, self::$migratedCategories)) { - print_r(self::$migratedCategories); - } - return self::$migratedCategories[$id]; - } -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/PartDBMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/PartDBMigration.php @@ -1,71 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - PartKeepr\Util\Configuration as PartKeeprConfiguration; - -class PartDBMigration { - /** - * Specifies if setup runs in console mode. - * @var boolean - */ - private $console = false; - - /** - * Runs the setup with all steps - */ - public function run () { - $this->runStep("all"); - } - - /** - * Sets console mode. - * - * In this mode, messages are directly written to the console. - */ - public function setConsole () { - $this->console = true; - } - - /** - * Runs a specific setup step, or all steps. - * @param string $step - * @throws \Exception - */ - public function runStep ($step) { - $entityManager = PartKeepr::getEM(); - - $aSteps = array( - "distributor" => new DistributorMigration($entityManager), - "footprint" => new FootprintMigration($entityManager), - "partcategory" => new PartCategoryMigration($entityManager), - "storagelocation" => new StorageLocationMigration($entityManager), - "part" => new PartMigration($entityManager) - ); - - if ($step == "all") { - foreach ($aSteps as $step) { - $step->setConsole($this->console); - $step->run(); - } - } else { - if (array_key_exists($step, $aSteps)) { - $aSteps[$step]->run(); - } else { - throw new \Exception(sprintf("Migration step %s doesn't exist", $step)); - } - } - } - - /** - * Converts strange escpaes in the database to "regular" text. - * @param string $string The string to convert - * @return string The converted string - */ - public static function convertText ($string) { - $string = stripslashes($string); - $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); - $string = str_replace("&#937;", "Ω", $string); - return $string; - } -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/PartMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/PartMigration.php @@ -1,131 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - PartKeepr\PartBundle\Entity\Part, - PartKeepr\PartBundle\Entity\PartAttachment, - PartKeepr\PartBundle\Entity\PartDistributor, - PartKeepr\Part\PartManager, - PartKeepr\Stock\StockEntry, - PartKeepr\Distributor\DistributorManager, - \PartKeepr\PartBundle\Entity\PartCategoryManager, - \PartKeepr\FootprintBundle\Entity\FootprintManager, - PartKeepr\PartUnit\PartUnitManager, - PartKeepr\StorageLocation\StorageLocationManager, - PartKeepr\Setup\AbstractSetup; - -class PartMigration extends AbstractSetup { - /** - * Migrates the existing distributors - */ - public function run () { - $count = 0; - $skipped = 0; - $fc = 0; - - $r = mysql_query("SELECT * FROM parts"); - - while ($part = mysql_fetch_assoc($r)) { - $name = PartDBMigration::convertText($part["name"]); - - $oPart = new Part(); - $oPart->setName($name); - $oPart->setComment(PartDBMigration::convertText($part["comment"])); - - $oPart->setFootprint($this->getFootprintForPart($part["id"])); - $oPart->setReviewFlag(true); - $category = PartCategoryMigration::getMigratedCategory($part["id_category"]); - - if ($category === null) { - PartCategoryManager::getInstance()->getRootNode()->getNode(); - } else { - $oPart->setCategory($category); - } - - $oPart->setStorageLocation($this->getStorageLocationForPart($part["id"])); - $oPart->setMinStockLevel($part["mininstock"]); - $oPart->setPartUnit(PartUnitManager::getInstance()->getDefaultPartUnit()); - - $partDistributor = new PartDistributor(); - $partDistributor->setPart($oPart); - $partDistributor->setDistributor($this->getDistributorForPart($part["id"])); - $partDistributor->setOrderNumber($part["supplierpartnr"]); - $oPart->getDistributors()->add($partDistributor); - - - /* Add existing datasheets */ - $datasheetQuery = "SELECT datasheeturl FROM datasheets WHERE part_id = ".$part["id"]; - $r3 = mysql_query($datasheetQuery); - while ($res = mysql_fetch_assoc($r3)) { - try { - $attachment = new PartAttachment(); - $attachment->setPart($oPart); - $attachment->replaceFromURL($res["datasheeturl"]); - $attachment->setDescription(PartKeepr::i18n("Datasheet")); - $oPart->getAttachments()->add($attachment); - } catch (\Exception $e) { - Setup::progress(" - error with url ".$res["datasheeturl"].". Maybe the datasheet was not found."); - Setup::progress(" - The exception error was: ".$e->getMessage()); - } - } - - PartKeepr::getEM()->persist($oPart); - - $oStock = new StockEntry($oPart, $part["instock"]); - - $priceQuery = "SELECT AVG(preis) AS preis FROM preise WHERE part_id = ".$part["id"]; - - $r2 = mysql_query($priceQuery); - $res = mysql_fetch_assoc($r2); - - if ($res) { - if ($res["preis"] !== null) { - $oStock->setPrice(floatval($res["preis"])); - } - } - - PartKeepr::getEM()->persist($oStock); - - $fc++; - - // Flush every STEP_SIZE parts - if ($fc>PartMigration::STEP_SIZE) { - PartKeepr::getEM()->flush(); - $fc=0; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Migrated %d parts, skipped %d because they already exist", $count, $skipped)); - } - - private function getFootprintForPart ($oldid) { - $r = mysql_query("SELECT footprints.name FROM footprints, parts WHERE footprints.id = parts.id_footprint AND parts.id = ".intval($oldid)); - - $data = mysql_fetch_assoc($r); - - return FootprintManager::getInstance()->getFootprintByName(PartDBMigration::convertText($data["name"])); - } - - private function getStorageLocationForPart ($oldid) { - $r = mysql_query("SELECT storeloc.name FROM storeloc, parts WHERE storeloc.id = parts.id_storeloc AND parts.id = ".intval($oldid)); - - $data = mysql_fetch_assoc($r); - - return StorageLocationManager::getInstance()->getStorageLocationByName(PartDBMigration::convertText($data["name"])); - } - - private function getDistributorForPart ($oldid) { - $r = mysql_query("SELECT suppliers.name FROM suppliers, parts WHERE suppliers.id = parts.id_supplier AND parts.id = ".intval($oldid)); - - $data = mysql_fetch_assoc($r); - - return DistributorManager::getInstance()->getDistributorByName(PartDBMigration::convertText($data["name"])); - } - - /** - * Defines the size of the records which are held in memory unless we flush to the DB. - * @var int - */ - const STEP_SIZE = 100; -} diff --git a/src/backend/PartKeepr/Setup/Migration/PartDB/StorageLocationMigration.php b/src/backend/PartKeepr/Setup/Migration/PartDB/StorageLocationMigration.php @@ -1,51 +0,0 @@ -<?php -namespace PartKeepr\Setup\Migration\PartDB; - -use PartKeepr\PartKeepr, - PartKeepr\StorageLocationBundle\Entity\StorageLocation, - PartKeepr\StorageLocation\StorageLocationManager, - PartKeepr\Setup\AbstractSetup; - -class StorageLocationMigration extends AbstractSetup { - /** - * Holds the migrated storage locations - * @var array - */ - private static $migratedStorageLocations = array(); - - /** - * Migrates the storage locations - */ - public function run () { - $count = 0; - $skipped = 0; - - $r = mysql_query("SELECT * FROM storeloc"); - - while ($store = mysql_fetch_assoc($r)) { - $name = PartDBMigration::convertText($store["name"]); - try { - $storageLocation = StorageLocationManager::getInstance()->getStorageLocationByName($name); - $skipped++; - } catch (\Exception $e) { - $oStorageLocation = new StorageLocation(); - $oStorageLocation->setName($name); - - $this->entityManager->persist($oStorageLocation); - $count++; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Migrated %d storage locations, skipped %d because they already exist", $count, $skipped)); - - } - - /** - * Returns the storage location by id - * @param int $id - */ - public static function getMigratedStorageLocation ($id) { - return StorageLocationSetup::$migratedStorageLocations[$id]; - } -} diff --git a/src/backend/PartKeepr/Setup/MiscSettingsSetup.php b/src/backend/PartKeepr/Setup/MiscSettingsSetup.php @@ -1,69 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\CronLoggerBundle\Services\CronLoggerManager; -use PartKeepr\PartKeepr; - -/** - * Sets up misc stuff, which doesn't fit into other steps - */ -class MiscSettingsSetup extends AbstractSetup { - public function run () { - $this->markCronjobsAsRun(); - $this->clearAPCCache(); - $this->regenerateProxies(); - } - - /** - * Marks the cronjobs as run, so that the user doesn't get an error during the first day. - * - * This is necessary because if the user sets up the system and enters the cronjobs, there is a chance - * that no cronjob has been ran when he logs in the first time and thus gets confused. - */ - public function markCronjobsAsRun () { - foreach (PartKeepr::getRequiredCronjobs() as $cronjob) { - CronLoggerManager::getInstance()->markCronRun($cronjob); - } - } - - /** - * Clears the APC cache to push out old entries - */ - public function clearAPCCache () { - if (function_exists("apc_clear_cache")) { - apc_clear_cache(); - apc_clear_cache("user"); - } - } - - /** - * Re-generates all proxies. This is analog to doctrine orm:generate-proxies - * - * @throws \InvalidArgumentException - */ - public function regenerateProxies () { - $em = $this->entityManager; - - $metadatas = $em->getMetadataFactory()->getAllMetadata(); - $destPath = $em->getConfiguration()->getProxyDir(); - - if ( ! is_dir($destPath)) { - mkdir($destPath, 0777, true); - } - - $destPath = realpath($destPath); - - if ( ! file_exists($destPath)) { - throw new \InvalidArgumentException( - sprintf("Proxies destination directory '<info>%s</info>' does not exist.", $em->getConfiguration()->getProxyDir()) - ); - } else if ( ! is_writable($destPath)) { - throw new \InvalidArgumentException( - sprintf("Proxies destination directory '<info>%s</info>' does not have write permissions.", $destPath) - ); - } - - $em->getProxyFactory()->generateProxyClasses($metadatas, $destPath); - } - -} diff --git a/src/backend/PartKeepr/Setup/PartCategorySetup.php b/src/backend/PartKeepr/Setup/PartCategorySetup.php @@ -1,28 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - \PartKeepr\PartBundle\Entity\PartCategoryManager, - \PartKeepr\PartBundle\Entity\PartCategory; - -class PartCategorySetup extends AbstractSetup { - /** - * Sets up the root category node - */ - public function setupRootCategory () { - PartCategoryManager::getInstance()->ensureRootExists(); - } - - public function updateCategoryPathCache () { - PartCategoryManager::getInstance()->updateCategoryPaths( - PartCategoryManager::getInstance()->getRootNode() - ); - - PartKeepr::getEM()->flush(); - } - - public function run () { - $this->setupRootCategory(); - $this->updateCategoryPathCache(); - } -} diff --git a/src/backend/PartKeepr/Setup/PartUnitSetup.php b/src/backend/PartKeepr/Setup/PartUnitSetup.php @@ -1,36 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - PartKeepr\PartBundle\Entity\PartMeasurementUnit; - -class PartUnitSetup extends AbstractSetup { - /** - * Holds the default unit - * @var object - */ - private static $defaultUnit; - - /** - * Sets up the default part unit if none exists - */ - public function run () { - $dql = "SELECT COUNT(p) FROM PartKeepr\PartBundle\Entity\PartMeasurementUnit p WHERE p.is_default = :default"; - $query = $this->entityManager->createQuery($dql); - $query->setParameter("default", true); - - if ($query->getSingleScalarResult() == 0) { - $partUnit = new PartMeasurementUnit(); - $partUnit->setName(PartKeepr::i18n("Pieces")); - $partUnit->setShortName(PartKeepr::i18n("pcs")); - $partUnit->setIsDefault(true); - - $this->entityManager->persist($partUnit); - $this->entityManager->flush(); - - $this->logMessage("Added default part unit"); - } else { - $this->logMessage("Skipped adding default part unit, because a default part unit already exists"); - } - } -} diff --git a/src/backend/PartKeepr/Setup/SchemaSetup.php b/src/backend/PartKeepr/Setup/SchemaSetup.php @@ -1,34 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr; -/** - * Updates (or creates) the database schema - */ -class SchemaSetup extends AbstractSetup { - public function run () { - $tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager); - $classes = PartKeepr::getClassMetaData(); - $tool->updateSchema($classes, true); - $this->logMessage("Database Schema created/updated"); - } - - /** - * Checks if the specified database has UTF-8 encoding - * @param $connection The DBAL connection - * @param string $dbname - */ - public static function mysqlHasUTF8Encoding ($connection, $dbname) { - $statement = $connection->prepare("SELECT default_character_set_name FROM information_schema.SCHEMATA S WHERE schema_name = :schema"); - $statement->bindValue("schema", $dbname); - $statement->execute(); - - $encoding = $statement->fetchColumn(0); - - if ($encoding != "utf8") { - return false; - } else { - return true; - } - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Setup/Setup.php b/src/backend/PartKeepr/Setup/Setup.php @@ -1,176 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - PartKeepr\Util\Configuration as PartKeeprConfiguration; - -class Setup { - /** - * Specifies if setup runs in console mode. - * @var boolean - */ - private $console = false; - - /** - * Defines if the setup runs in verbose mode. - * @var boolean - */ - private static $verbose = false; - - /** - * Runs the migration with all steps - */ - public function run () { - $this->runStep("all"); - } - - /** - * Sets console mode. - * - * In this mode, messages are directly written to the console. - */ - public function setConsole () { - $this->console = true; - } - - /** - * Runs a specific setup step, or all steps. - * - * @param string $step The step to execute - * @throws \Exception - */ - public function runStep ($step) { - $entityManager = PartKeepr::getEM(); - - $aSteps = array( - "schema" => new SchemaSetup($entityManager), - "adminuser" => new UserSetup($entityManager), - "partunit" => new PartUnitSetup($entityManager), - "footprint" => new FootprintSetup($entityManager), - "partcategory" => new PartCategorySetup($entityManager), - "siprefix" => new SiPrefixSetup($entityManager), - "unit" => new UnitSetup($entityManager), - "manufacturer" => new ManufacturerSetup($entityManager), - "miscsettings" => new MiscSettingsSetup($entityManager) - ); - - $aActions = array( - "configfile" => new ConfigFileSetup($entityManager) - ); - if ($step == "all") { - foreach ($aSteps as $step) { - $step->setConsole($this->console); - $step->run(); - } - } else { - if (array_key_exists($step, $aSteps)) { - return $aSteps[$step]->run(); - } - - if (array_key_exists($step, $aActions)) { - return $aActions[$step]->run(); - } - - throw new \Exception(sprintf("Setup step %s doesn't exist", $step)); - } - } - - /** - * Tests for APC. Throws an exception if APC is missing or not active. - * @throws \Exception - */ - public function testAPC () { - if (!extension_loaded("apc")) { - throw new \Exception(PartKeepr::i18n("The extension 'apc' is not loaded. Make sure that it is installed (see http://php.net/manual/en/apc.installation.php) and that it is enabled (set apc.enabled=1 in your php.ini).")); - } - } - - /** - * Tests for suitable memory_limit settings - * @todo stub - */ - public function testMemoryLimit () { - //echo ini_get("memory_limit"); - } - - /** - * Sets the verbose flag - * @param boolean $verbose True if verbose output is wanted, false otherwise - */ - public static function setVerbose ($verbose) { - Setup::$verbose = $verbose; - } - - /** - * Outputs a progress message. - * - * @param string $string The string to output - * @param boolean $verbose True if the string should only be printed if verbosity is turned on - */ - public static function progress ($string, $verbose = false) { - if (!$verbose || ($verbose && Setup::$verbose)) { - echo $string."\n"; - } - - } - - /** - * Loads the given YAML file. Due to an API brach between Doctrine 2.0.5 and Doctrine 2.0.6, - * we need to work it around. - * @param string $file The path of the file to load - * @return array The parsed YAML file - */ - public static function loadYAML ($file) { - return \Symfony\Component\Yaml\Yaml::parse($file); - } - - /** - * Sets the database configuration array from $_REQUEST - */ - public static function setDatabaseConfigurationFromRequest () { - if (isset($_REQUEST["dbname"])) { - PartKeeprConfiguration::setOption("partkeepr.database.dbname", $_REQUEST["dbname"]); - } - - if (isset($_REQUEST["user"])) { - PartKeeprConfiguration::setOption("partkeepr.database.username", $_REQUEST["user"]); - } - if (isset($_REQUEST["password"])) { - PartKeeprConfiguration::setOption("partkeepr.database.password", $_REQUEST["password"]); - } - if (isset($_REQUEST["host"])) { - PartKeeprConfiguration::setOption("partkeepr.database.host", $_REQUEST["host"]); - } - - if (isset($_REQUEST['port'])) { - PartKeeprConfiguration::setOption("partkeepr.database.port", $_REQUEST["port"]); - } - - switch ($_REQUEST["driver"]) { - case "mysql": - PartKeeprConfiguration::setOption("partkeepr.database.driver","pdo_mysql"); - break; - case "pgsql": - PartKeeprConfiguration::setOption("partkeepr.database.driver","pdo_pgsql"); - break; - default: - throw new \Exception(sprintf("Invalid driver %s specified.", $_REQUEST["driver"])); - break; - } - } - - /** - * Runs some checks for the CLI setup - */ - public function runCLIChecks () { - - if (PartKeeprConfiguration::getOption("partkeepr.database.driver") == "pdo_mysql") { - $dbname = PartKeeprConfiguration::getOption("partkeepr.database.dbname"); - if (!SchemaSetup::mysqlHasUTF8Encoding(PartKeepr::getEM()->getConnection(), $dbname )) { - echo "Error: The database $dbname hasn't got the UTF-8 encoding. You need to set the database encoding to UTF-8. Aborting.\n"; - die; - } - } - - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Setup/SiPrefixSetup.php b/src/backend/PartKeepr/Setup/SiPrefixSetup.php @@ -1,47 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - PartKeepr\SiPrefixBundle\Entity\SiPrefix, - PartKeepr\SiPrefixBundle\Model\SiPrefixManager; - -class SiPrefixSetup extends AbstractSetup { - - const SIPREFIX_DATA_FILE = "../setup-data/siprefixes.yaml"; - - /** - * Stores the migrated si prefixes - * @var array - */ - private static $siPrefixes = array(); - - public function run () { - $this->setupSiPrefixes(); - } - - /** - * Sets up the SI prefixes - */ - public function setupSiPrefixes () { - $count = 0; - $skipped = 0; - - $data = Setup::loadYAML(self::SIPREFIX_DATA_FILE); - - foreach ($data as $prefixName => $prefixData) { - if (!SiPrefixManager::getInstance()->siPrefixExists($prefixName)) { - $prefix = new SiPrefix(); - $prefix->setPrefix($prefixName); - $prefix->setExponent($prefixData["exponent"]); - $prefix->setSymbol($prefixData["symbol"]); - $this->entityManager->persist($prefix); - $count++; - } else { - $skipped++; - } - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Imported %d Si Prefixes, skipped %d", $count, $skipped)); - } -} diff --git a/src/backend/PartKeepr/Setup/UnitSetup.php b/src/backend/PartKeepr/Setup/UnitSetup.php @@ -1,62 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\PartKeepr, - PartKeepr\UnitBundle\Entity\Unit, - PartKeepr\SiPrefixBundle\Model\SiPrefixManager, - PartKeepr\Unit\UnitManager, - PartKeepr\Setup\SiPrefixSetup; - -class UnitSetup extends AbstractSetup { - - const UNIT_DATA_FILE = "../setup-data/units.yaml"; - - - public function run () { - $this->setupUnits(); - } - /** - * Sets up the default units - * @throws \Exception - */ - public function setupUnits () { - $count = 0; - $skipped = 0; - $data = Setup::loadYAML(self::UNIT_DATA_FILE); - - $aUnits = array(); - - foreach ($data as $unitName => $unitData) { - if (UnitManager::getInstance()->unitExists($unitName)) { - $skipped++; - continue; - } - $unit = new Unit(); - $unit->setName($unitName); - $unit->setSymbol($unitData["symbol"]); - - 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 $prefix) { - - $siPrefix = SiPrefixManager::getInstance()->getSiPrefixBySymbol($prefix); - if ($siPrefix === false) { - throw new \Exception("Unable to find prefix ".$prefix); - } - $unit->getPrefixes()->add($siPrefix); - } - } - - PartKeepr::getEM()->persist($unit); - $count++; - } - - $this->entityManager->flush(); - $this->logMessage(sprintf("Imported %d Units, skipped %d because they already exist", $count, $skipped)); - } - - -} diff --git a/src/backend/PartKeepr/Setup/UserSetup.php b/src/backend/PartKeepr/Setup/UserSetup.php @@ -1,31 +0,0 @@ -<?php -namespace PartKeepr\Setup; - -use PartKeepr\AuthBundle\Entity\User; - -/** - * Creates a new admin user, but only if no admin user exists. - */ -class UserSetup extends AbstractSetup { - public function run () { - $dql = "SELECT COUNT(u) FROM PartKeepr\AuthBundle\Entity\User u WHERE u.username = :username OR u.admin = :admin"; - $query = $this->entityManager->createQuery($dql); - $query->setParameter("username", "admin"); - $query->setParameter("admin", true); - - if ($query->getSingleScalarResult() == 0) { - $user = new User(); - $user->setUsername("admin"); - $user->setPassword("admin"); - $user->setAdmin(true); - - $this->entityManager->persist($user); - $this->entityManager->flush(); - - $this->logMessage("Admin User created"); - } else { - $this->logMessage( "Skipped admin user creation, because an user named 'admin'". - "or another user with an admin flag already exists"); - } - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Statistic/StatisticService.php b/src/backend/PartKeepr/Statistic/StatisticService.php @@ -1,148 +0,0 @@ -<?php -namespace PartKeepr\Statistic; - -use PartKeepr\PartBundle\Entity\PartMeasurementUnit, - PartKeepr\Service\Service, - PartKeepr\PartKeepr, - PartKeepr\Part\PartManager, - \PartKeepr\PartBundle\Entity\PartCategoryManager, - PartKeepr\PartUnit\PartUnitManager; - -class StatisticService extends Service { - public function getCurrentStats () { - - $aData = array(); - $aData["partCount"] = PartManager::getInstance()->getPartCount(); - $aData["categoryCount"] = PartCategoryManager::getInstance()->getCategoryCount(); - $aData["totalPrice"] = PartManager::getInstance()->getTotalPrice(); - $aData["averagePrice"] = PartManager::getInstance()->getAveragePrice(); - $aData["partsWithPrice"] = PartManager::getInstance()->getPartCount(true); - $aData["partsWithoutPrice"] = $aData["partCount"] - $aData["partsWithPrice"]; - - $result = PartUnitManager::getInstance()->getUnitCounts(); - - $aUnits = array(); - - foreach ($result as $row) { - $aUnits[] = array( - "name" => PartMeasurementUnit::loadById($row["puid"])->getName(), - "stockLevel" => $row["stockLevel"]); - } - - $aData["units"] = $aUnits; - - return $aData; - } - - /** - * Returns the range of all recorded statistic snapshots. - */ - public function getStatisticRange () { - $dql = "SELECT MIN(sts.dateTime), MAX(sts.dateTime) FROM PartKeepr\Statistic\StatisticSnapshot sts"; - $query = PartKeepr::getEM()->createQuery($dql); - - $data = $query->getArrayResult(); - - return array("data" => array("start" => $data[0][1], "end" => $data[0][2])); - - } - /** - * Returns sampled statistics from the database. - * - * This call takes a start and an end time, and calculates a set of statistics - * for each interval. - * - * The sampleSize, which has a default of 50, specifies how many single statistic - * points in the given date interval will be returned. - * - * This function interpolates the statistics if there are not enough statistic samples available. - */ - public function getSampledStatistics () { - $fooStart = microtime(true); - - $this->requireParameter("startDateTime"); - $this->requireParameter("endDateTime"); - - - $start = \DateTime::createFromFormat("Y-m-d H:i:s", $this->getParameter("startDateTime")); - $end = \DateTime::createFromFormat("Y-m-d H:i:s", $this->getParameter("endDateTime")); - - if ($start->getTimestamp() > $end->getTimestamp()) { - // Swap both times - list($start, $end) = array($end, $start); - } - - if ($this->hasParameter("sampleSize")) { - $sampleSize = $this->getParameter("sampleSize"); - } else { - $sampleSize = 25; - } - - $intervalSize = intval(($end->getTimestamp() - $start->getTimestamp()) / $sampleSize); - - $queryStartTime = clone $start; - $queryEndTime = clone $start; - $queryEndTime->add(new \DateInterval("PT".$intervalSize."S")); - - $partUnitQuery = "SELECT pu FROM PartKeepr\PartBundle\Entity\PartUnit pu"; - $query = PartKeepr::getEM()->createQuery($partUnitQuery); - - $aPartUnits = $query->getResult(); - - $aRecords = array(); - - $dql = "SELECT AVG(sts.parts) AS parts, AVG(sts.categories) AS categories FROM PartKeepr\Statistic\StatisticSnapshot sts WHERE sts.dateTime >= :start AND sts.dateTime <= :end"; - $mainQuery = PartKeepr::getEM()->createQuery($dql); - - $dql = "SELECT AVG(stsu.stockLevel) AS stockLevel FROM PartKeepr\Statistic\StatisticSnapshotUnit stsu JOIN stsu.statisticSnapshot sts WHERE sts.dateTime >= :start AND sts.dateTime <= :end AND stsu.partUnit = :partUnit"; - $subQuery = PartKeepr::getEM()->createQuery($dql); - - for ($i=0;$i<$sampleSize;$i++) { - - - $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["categories"] !== null) { - $record["categories"] = floatval($record["categories"]); - } - - foreach ($aPartUnits as $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"]); - } else { - $record["units"][$partUnit->getName()] = null; - } - - } - - $record["start"] = $queryStartTime->format("Y-m-d H:i:s"); - - if ($record["parts"] !== null) { - $aRecords[] = $record; - } - - - $queryStartTime->add(new \DateInterval("PT".$intervalSize."S")); - $queryEndTime->add(new \DateInterval("PT".$intervalSize."S")); - } - - - return array("status" => "ok", "data" => $aRecords); - } - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Statistic/StatisticSnapshot.php b/src/backend/PartKeepr/Statistic/StatisticSnapshot.php @@ -1,110 +0,0 @@ -<?php -namespace PartKeepr\Statistic; - -use PartKeepr\PartKeepr, - Doctrine\ORM\Mapping as ORM; - -/** @ORM\Entity **/ -class StatisticSnapshot { - /** - * @ORM\Id @ORM\Column(type="integer") - * @ORM\GeneratedValue(strategy="AUTO") - * @var integer - */ - private $id; - - /** - * Defines the date when this snapshot has been taken - * @ORM\Column(type="datetime") - * @var DateTime - */ - private $dateTime; - - /** - * Defines the amount of different parts in the database - * @ORM\Column(type="integer") - * @var int - */ - private $parts; - - /** - * Defines the amount of categories - * @ORM\Column(type="integer") - * @var int - */ - private $categories; - - /** - * Holds all defined units in the database - * @ORM\OneToMany(targetEntity="PartKeepr\Statistic\StatisticSnapshotUnit",mappedBy="statisticSnapshot",cascade={"persist", "remove"}) - */ - private $units; - - /** - * Creates a new statistic snapshot - */ - public function __construct () { - $this->units = new \Doctrine\Common\Collections\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; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Statistic/StatisticSnapshotManager.php b/src/backend/PartKeepr/Statistic/StatisticSnapshotManager.php @@ -1,36 +0,0 @@ -<?php -namespace PartKeepr\Statistic; - -use PartKeepr\Part\PartManager; -use PartKeepr\PartBundle\Entity\PartCategoryManager; -use PartKeepr\PartBundle\Entity\PartMeasurementUnit; -use PartKeepr\PartKeepr; -use PartKeepr\Util\Singleton; - -class StatisticSnapshotManager extends Singleton { - public function createSnapshot () { - - $snapshot = new StatisticSnapshot(); - $snapshot->setParts(PartManager::getInstance()->getPartCount()); - $snapshot->setCategories(PartCategoryManager::getInstance()->getCategoryCount()); - - $result = PartUnitManager::getInstance()->getUnitCounts(); - - foreach ($result as $row) { - $snapshotUnit = new StatisticSnapshotUnit(); - $snapshotUnit->setPartUnit(PartMeasurementUnit::loadById($row["puid"])); - $snapshotUnit->setStatisticSnapshot($snapshot); - - if ($row["stockLevel"] !== null) { - $snapshotUnit->setStockLevel($row["stockLevel"]); - } else { - $snapshotUnit->setStockLevel(0); - } - - $snapshot->getUnits()->add($snapshotUnit); - } - - PartKeepr::getEM()->persist($snapshot); - PartKeepr::getEM()->flush(); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Statistic/StatisticSnapshotUnit.php b/src/backend/PartKeepr/Statistic/StatisticSnapshotUnit.php @@ -1,96 +0,0 @@ -<?php -namespace PartKeepr\Statistic; - -use Doctrine\ORM\Mapping as ORM; -use PartKeepr\PartBundle\Entity\PartMeasurementUnit; - - -/** @ORM\Entity **/ -class StatisticSnapshotUnit { - /** - * @ORM\Id @ORM\Column(type="integer") - * @ORM\GeneratedValue(strategy="AUTO") - * @var integer - */ - private $id; - - /** - * @ORM\ManyToOne(targetEntity="PartKeepr\Statistic\StatisticSnapshot",inversedBy="units") - * The statistic snapshot this entity belongs to - * @var StatisticSnapshot - */ - private $statisticSnapshot; - - /** - * @ORM\ManyToOne(targetEntity="PartKeepr\PartBundle\Entity\PartMeasurementUnit") - * The statistic snapshot this entity belongs to - * @var StatisticSnapshot - */ - private $partUnit; - - /** - * The stockLevel for the unit - * @ORM\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; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/User/UserService.php b/src/backend/PartKeepr/User/UserService.php @@ -1,115 +0,0 @@ -<?php -namespace PartKeepr\AuthBundle\Entity\User; - -use PartKeepr\AuthBundle\Entity\User; -use PartKeepr\Manager\ManagerFilter; -use PartKeepr\PartKeepr; -use PartKeepr\Service\FilterExtractor; -use PartKeepr\Service\RestfulService; -use PartKeepr\Service\Service; -use PartKeepr\Session\SessionManager; - -class UserService extends Service implements RestfulService { - - /** - * Implements the get() call for the RestfulService. - * - * If the "id" parameter is passed, try to return the user by id. If not, - * return a list. - * - * @see PartKeepr\Service.RestfulService::get() - */ - public function get () { - if ($this->hasParameter("id")) { - if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { - throw new \Exception("Permission denied"); - } - - return array("data" => UserManager::getInstance()->getUser($this->getParameter("id"))->serialize()); - } else { - $filter = new ManagerFilter($this); - $filter->setFilterCallback(array($this, "filterCallback")); - return UserManager::getInstance()->getList($filter); - } - } - - - public function filterCallback ($queryBuilder) { - $filter = new FilterExtractor($this); - - if ( $this->hasParameter("query") - && $query = $this->getParameter("query") ){ - - $queryBuilder->andWhere("LOWER(q.username) LIKE :query"); - $queryBuilder->setParameter("query", $query ); - } - - if ( $filter->has("lastSeenMax") - && $lastSeenMax = $filter->get('lastSeenMax') ){ - $queryBuilder->andWhere("q.lastSeen > :lastSeenMax"); - $queryBuilder->setParameter("lastSeenMax", new \DateTime('- '.$lastSeenMax.' seconds')); - } - - if( $filter->has('hideCurrentUser') - && $filter->get('hideCurrentUser') == '1'){ - $queryBuilder->andWhere("q.id != :currentUserId"); - $queryBuilder->setParameter("currentUserId", SessionManager::getCurrentSession()->getUser()->getId() ); - } - } - - /** - * Creates a new user. - * - * @see PartKeepr\Service.RestfulService::create() - */ - public function create () { - if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { - throw new \Exception("Permission denied"); - } - - $this->requireParameter("username"); - - $user = new User; - $user->deserialize($this->getParameters()); - - UserManager::getInstance()->createUser($user); - - return array("data" => $user->serialize()); - } - - /** - * Updates the user informations. - * @see PartKeepr\Service.RestfulService::update() - */ - public function update () { - if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { - throw new \Exception("Permission denied"); - } - - $this->requireParameter("id"); - $this->requireParameter("username"); - $user = UserManager::getInstance()->getUser($this->getParameter("id")); - - $user->deserialize($this->getParameters()); - PartKeepr::getEM()->flush(); - - return array("data" => $user->serialize()); - - } - - /** - * Deletes the user from the database. - * @see PartKeepr\Service.RestfulService::destroy() - */ - public function destroy () { - if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { - throw new \Exception("Permission denied"); - } - - $this->requireParameter("id"); - - UserManager::getInstance()->deleteUser($this->getParameter("id")); - - return array("data" => null); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/BaseEntity.php b/src/backend/PartKeepr/Util/BaseEntity.php @@ -1,25 +0,0 @@ -<?php -namespace PartKeepr\Util; - -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 diff --git a/src/backend/PartKeepr/Util/Configuration.php b/src/backend/PartKeepr/Util/Configuration.php @@ -1,92 +0,0 @@ -<?php -namespace PartKeepr\Util; - -use PartKeepr\PartKeepr; - -/** - * This class manages simple key -> value configurations within the system. - * - * This allows the user to configure certain aspects of the system in a central place. - * - * The convention is to use a dotted format, for example: - * - * flipbeat.cms.layoutrenderer - * - * @author felicitus - */ -class Configuration { - private static $options = array(); - - /** - * Sets the option to value. - * - * @param string $option The option to set - * @param string $value The value to set - */ - public static function setOption ($option, $value) { - Configuration::$options[$option] = $value; - } - - /** - * Returns the value of an option. The developer - * may additionally specify a default value, which - * is returned when no option was found. - * - * @param string $option The option to return - * @param string $default The default value if the option was not found - */ - public static function getOption ($option, $default = false) { - if (!array_key_exists($option, Configuration::$options)) { - return $default; - } - return Configuration::$options[$option]; - } - - /** - * Returns all configuration options - * - * @return array An array with key=>value assignments - */ - public static function getOptions () { - return Configuration::$options; - } - - /** - * Returns a configuration file, based on all configurations. - * - * @param none - * @return string A complete configuration file including namespace and use directives - */ - public static function dumpConfig () { - $config = <<<EOD -<?php -namespace PartKeepr; -use PartKeepr\Util\Configuration; - - -EOD; - foreach (Configuration::$options as $option => $value) { - switch (PartKeepr::getType($value)) { - case "string": - $config .= 'Configuration::setOption("'.$option.'", "'.$value.'");'."\n"; - break; - case "boolean": - $config .= 'Configuration::setOption("'.$option.'", '.($value === true ? 'true' : 'false').');'."\n"; - break; - case "integer": - case "numeric": - $config .= 'Configuration::setOption("'.$option.'", '.intval($value).');'."\n"; - break; - case "float": - $config .= 'Configuration::setOption("'.$option.'", '.floatval($value).');'."\n"; - break; - default: - break; - } - - } - - return $config; - } -} -?>- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/Deserializable.php b/src/backend/PartKeepr/Util/Deserializable.php @@ -1,10 +0,0 @@ -<?php -namespace PartKeepr\Util; - -interface Deserializable { - /** - * Deserializes the entity from an array format - * @param $parameters array The serialized form of the entity to deserialize - */ - public function deserialize (array $parameters); -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/ExtJSFile.php b/src/backend/PartKeepr/Util/ExtJSFile.php @@ -1,181 +0,0 @@ -<?php -namespace PartKeepr\Util; - -/** - * Represents an ExtJS file including references. - */ -class ExtJSFile { - /** - * The source code - * @var string - */ - private $source; - - /** - * Holds the class name - * @var string - */ - private $className; - - /** - * Holds all classes this class requires - * @var array - */ - private $requires = array(); - - /** - * Holds the filename - * @var string - */ - private $filename; - - /** - * Holds all classes which have a dependency to this class - * @var array - */ - private $childs = array(); - - /** - * Constructs a new ExtJSFile class. - * - * @param string $file The source file - */ - public function __construct ($file) { - $file = str_replace("//", "/", $file); - - $this->source = file_get_contents($file); - - if ($this->parseExtendDirective() != "") { - $this->requires[] = $this->parseExtendDirective(); - } - - $this->className = $this->parseClassName(); - - if ($this->requiresPartKeeprBase()) { - $this->requires[] = "PartKeepr"; - } - - $this->filename = $file; - - } - - /** - * Adds a child which depends to this class - * @param ExtJSFile $child - */ - public function addChild (ExtJSFile $child) { - $this->childs[] = $child; - } - - /** - * Returns the class names of all requirements for this class - * @return array An array with the requirement class names - */ - public function getRequires () { - return $this->requires; - } - - /** - * Returns the class name for this class - * @return string The class name - */ - public function getClassName () { - if ($this->className == "") { - return "FILE--".$this->getFilename(); - } else { - return $this->className; - } - } - - public function getFilename () { - return $this->filename; - } - - /** - * Parses the source and returns the "extend" directive. - * - * @return string The extend class name - */ - private function parseExtendDirective () { - $pattern = "/extend\s*:\s*[\"|'](.*)[\"|']/"; - - preg_match($pattern, $this->source, $results); - - // Remove the first element, which contains the RegExp - unset($results[0]); - - return array_pop($results); - } - - /** - * Parses the source and returns the class name. - * - * @return string The class name - */ - private function parseClassName () { - $pattern = "/Ext.define\\([\"|'](.*)[\"|']/"; - - preg_match($pattern, $this->source, $results); - - // Remove the first element, which contains the RegExp - unset($results[0]); - - return array_pop($results); - } - - /** - * Checks if the class needs the base PartKeepr class. - * @return boolean True if the class needs the base PartKeepr class, false otherwise - */ - private function requiresPartKeeprBase () { - if (strpos($this->source, "PartKeepr.getRESTProxy") !== false) { - return true; - } - - return false; - } - - /** - * Returns the JSB entries for this class and all sub classes - * @return string The JSB string with this class and all child classes - */ - public function getJSB () { - - $aData = array($this->getJSBEntry()); - - foreach ($this->childs as $child) { - $aData[] = $child->getJSB(); - } - - return implode(",\n", $aData); - } - - public function getArray () { - $aData = array($this->filename); - - foreach ($this->childs as $child) { - $aData = array_merge($aData, $child->getArray()); - } - - return $aData; - } - - /** - * Returns the JSB Entry for the class - * - * @return String A single JSB entry with PATH and NAME. - */ - private function getJSBEntry () { - $template = '{"path": "[PATH]","name": "[NAME]"}'; - - $path = dirname($this->filename); - $name = basename($this->filename); - - - $template = str_replace("[PATH]", $path."/", $template); - $template = str_replace("[NAME]", $name, $template); - - return $template; - } - -} diff --git a/src/backend/PartKeepr/Util/Minifier/Minifier.php b/src/backend/PartKeepr/Util/Minifier/Minifier.php @@ -1,78 +0,0 @@ -<?php -namespace PartKeepr\Util\Minifier; - -use Symfony\Component\Console; - -abstract class Minifier -{ - /** - * @var Console\Output\OutputInterface $output The output interface - */ - protected $output; - - /** - * @param Console\Output\OutputInterface $output The output interface from Sf2 - */ - public function __construct(Console\Output\OutputInterface $output = null) - { - if ($output !== null) { - $this->output = $output; - } - } - - /** - * Sets the output interface to a known value - * @param Console\Output\OutputInterface $output The output interface from Sf2 - */ - public function setOutput(Console\Output\OutputInterface $output) - { - $this->output = $output; - } - - /** - * Minifies the given source files into the output file. - * - * "Minify" means that whitespaces and newlines are stripped, which results in a smaller file. - * - * @abstract - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile - * @return mixed - */ - abstract public function minify(array $sourceFiles, $outputFile); - - /** - * Compresses the given source files into the output file. - * - * "Compress" means that everything that "Minify" does is applied, additionally local variables are compressed to - * save space. - * - * This is not supported across all minifier implementations. - * - * @abstract - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile - * @return mixed - */ - abstract public function compress(array $sourceFiles, $outputFile); - - /** - * Combines the given source files into the output file. - * - * No minification or compression is applied. - * - * @param array $sourceFiles - * @param $outputFile - * @return mixed - */ - public function combine(array $sourceFiles, $outputFile) - { - if (file_exists($outputFile) && filesize($outputFile) != 0) { - unlink($outputFile); - } - - foreach ($sourceFiles as $sourceFile) { - file_put_contents($outputFile, file_get_contents($sourceFile), FILE_APPEND); - } - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/Minifier/jsminMinifier.php b/src/backend/PartKeepr/Util/Minifier/jsminMinifier.php @@ -1,52 +0,0 @@ -<?php -namespace PartKeepr\Util\Minifier; - -use PartKeepr\PartKeepr; - -/** - * This class implements JS minifying via jsmin. - */ -class jsminMinifier extends Minifier { - const JSMIN_SCRIPT = "3rdparty/jsmin/jsmin.php"; - - /** - * Minifies the given source files into the output file. - * - * "Minify" means that whitespaces and newlines are stripped, which results in a smaller file. - * - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile - * @return mixed - */ - public function minify (array $sourceFiles, $outputFile) { - if (!class_exists("\\JSMin")) { - require_once(PartKeepr::getRootDirectory() . "/" . self::JSMIN_SCRIPT); - } - if (file_exists($outputFile)) { - unlink($outputFile); - } - - foreach ($sourceFiles as $sourceFile) { - $minifiedJS = \JSMin::minify(file_get_contents($sourceFile)); - file_put_contents($outputFile, $minifiedJS, FILE_APPEND); - } - } - - /** - * Compresses the given source files into the output file. - * - * "Compress" means that everything that "Minify" does is applied, additionally local variables are compressed to - * save space. - * - * This is not supported across all minifier implementations. - * - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile - * @return mixed - */ - public function compress (array $sourceFiles, $outputFile) { - $this->output->writeln("<error>The jsminMinifier doesn't support compress; using minify instead</error>"); - $this->minify($sourceFiles, $outputFile); - } - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/Minifier/yuiCompressorMinifier.php b/src/backend/PartKeepr/Util/Minifier/yuiCompressorMinifier.php @@ -1,79 +0,0 @@ -<?php -namespace PartKeepr\Util\Minifier; - -/** - * This class implements JS minifying via jsmin. - */ -class yuiCompressorMinifier extends Minifier { - /** - * Minifies the given source files into the output file. - * - * "Minify" means that whitespaces and newlines are stripped, which results in a smaller file. - * - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile The target file - * @return mixed - */ - public function minify (array $sourceFiles, $outputFile) { - $this->run($sourceFiles, $outputFile, array("--nomunge")); - } - - /** - * Compresses the given source files into the output file. - * - * "Compress" means that everything that "Minify" does is applied, additionally local variables are compressed to - * save space. - * - * This is not supported across all minifier implementations. - * - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile The target file - * @return mixed - */ - public function compress (array $sourceFiles, $outputFile) { - $this->run($sourceFiles, $outputFile); - } - - /** - * Runs the yui-compressor. - * - * Because yui-compressor needs a while to run, we merge the files into a single one prior compressing. - * - * @param array $sourceFiles An array of source files with absolute paths - * @param $outputFile The target file - * @param array $options Additional CLI options - */ - protected function run (array $sourceFiles, $outputFile, array $options = array()) { - $cli = array(); - $cli[] = self::getYuiCompressorPath(); - $cli[] = "--type js"; - - $cli = array_merge($cli, $options); - - $tmpFile = tempnam(sys_get_temp_dir(), "PK_COMPRESS_JS"); - - $this->combine($sourceFiles, $tmpFile); - - $cliOpts = implode(" ", $cli); - $execute = $cliOpts . " ".$tmpFile; - $data = shell_exec($execute); - file_put_contents($outputFile, $data); - } - - - /** - * Attempts to retrieve the yui-compressor path. We execute "which" for that purpose. - * - * @return bool|string The path of the yui-compressor binary, or false if no path was found - */ - public static function getYuiCompressorPath () { - $file = exec("which yui-compressor"); - - if (is_executable($file)) { - return $file; - } else { - return false; - } - } - -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/Serializable.php b/src/backend/PartKeepr/Util/Serializable.php @@ -1,11 +0,0 @@ -<?php -namespace PartKeepr\Util; - -interface Serializable { - /** - * Serializes the entity into an array format, which in turn can - * be used by json_encode. - * @return array The serialized form of the entity - */ - public function serialize (); -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/SerializableException.php b/src/backend/PartKeepr/Util/SerializableException.php @@ -1,60 +0,0 @@ -<?php -namespace PartKeepr\Util; - -class SerializableException extends \Exception { - protected $detailMessage = "No detail message has been entered."; - - /* @todo: stub */ - public function getDetail () { - return $this->detailMessage; - } - - public function setDetail ($message) { - $this->detailMessage = $message; - } - - public function serialize () { - return array( - "message" => $this->getMessage(), - "detail" => $this->getDetail(), - "exception" => get_class($this), - "code" => $this->getCode() - //"backtrace" => $this->getFormattedTrace() - ); - } - - public function getFormattedTrace () { - $items = $this->getTrace(); - - $message = ""; - - $args = array(); - - foreach ($items as $id => $item) { - foreach ($item["args"] as $itemData) { - switch (gettype($itemData)) { - case "object": - if (method_exists($itemData, "__toString")) { - $args[] = get_class($itemData) . "(".$itemData->__toString().")"; - } else { - $args[] = get_class($itemData); - } - break; - case "array": - $args[] = "array"; - break; - default: - $args[] = $itemData; - break; - } - } - - $message .= $item["file"].":".$item["line"]."\n"; - $message .= $item["function"] ."(".implode(",", $args).")"."\n\n"; - } - - return $message; - } - -} -?>- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/SimpleObjectManager.php b/src/backend/PartKeepr/Util/SimpleObjectManager.php @@ -1,39 +0,0 @@ -<?php -namespace PartKeepr\Util; - -use PartKeepr\PartKeepr, - PartKeepr\Util\Exceptions\ObjectNotFoundException, - PartKeepr\Util\Singleton; - -class SimpleObjectManager extends Singleton{ - /** - * Contains the object we are responsible for. - * @var string - */ - private $classType; - - protected function __construct ($classType) { - $this->classType = $classType; - } - - public function getObjectById ($id) { - $obj = PartKeepr::getEM()->find($classType, $id); - if ($obj) { - return $obj; - } else { - throw new ObjectNotFoundException($classType, $id); - } - } - - public function addObject ($obj) { - PartKeepr::getEM()->persist($obj); - PartKeepr::getEM()->flush(); - return $obj; - } - public function deleteObjectById ($id) { - $obj = $this->getPageBasicLayout($id); - - PartKeepr::getEM()->remove($obj); - PartKeepr::getEM()->flush(); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/Singleton.php b/src/backend/PartKeepr/Util/Singleton.php @@ -1,22 +0,0 @@ -<?php -namespace PartKeepr\Util; - -abstract class Singleton { - static $instance = null; - - private function __construct () { - - } - - /** - * Returns an instance of the current singleton - * @return $this - */ - public static function getInstance () { - if (!static::$instance instanceof static) { - static::$instance = new static; - } - - return static::$instance; - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/TablePrinter.php b/src/backend/PartKeepr/Util/TablePrinter.php @@ -1,181 +0,0 @@ -<?php -namespace PartKeepr\Util; - -use Symfony\Component\Console\Output\OutputInterface; - -/** - * TablePrinter. - * - * Original by Antoine Durieux, ported to a proper class by Felicitus - * - * Source: http://adurieux.blogspot.com/2011/10/table-printer-for-symfony2-console.html - */ -class TablePrinter -{ - /** - * Holds an instance of the OutputInterface - * @var null|\Symfony\Component\Console\Output\OutputInterface - */ - private $output = null; - - /** - * The header columns as simple array - * @var array - */ - private $header = array(); - - /** - * The body columns as nested array. - * @var array - */ - private $body = array(); - - /** - * Creates a new instance of the table printer - * - * @param \Symfony\Component\Console\Output\OutputInterface $output The output interface to use - */ - public function __construct (OutputInterface $output) { - $this->output = $output; - } - - /** - * Sets the header - * @param string[] $header The header columns to set - */ - public function setHeader (array $header) { - $this->header = $header; - } - - /** - * Sets the body - * @param array $body A nested array of rows, e.g. - * - * setBody( array( - * array("Row1Col1", "Row1Col2"), - * array("Row2Col1", "Row2Col2") - * )); - */ - public function setBody (array $body) { - $this->body = $body; - } - - /** - * This function performs the full print of the table - * - * @author Antoine Durieux - */ - public function output () - { - // --------------------------------------------------------------------- - // 1. Find column widths to use - // --------------------------------------------------------------------- - $columnWidths = $this->computeColumnWidths($this->body,$this->header); - - // --------------------------------------------------------------------- - // 2. Print header - // --------------------------------------------------------------------- - if(count($this->header) != 0) - { - $this->printConsole($this->printBlankLine($columnWidths)); - $this->printConsole($this->printLine($this->header,$columnWidths)); - } - - // --------------------------------------------------------------------- - // 3. Print body - // --------------------------------------------------------------------- - $this->printConsole($this->printBlankLine($columnWidths)); - foreach($this->body as $row) - { - $this->printConsole($this->printLine($row,$columnWidths)); - } - $this->printConsole($this->printBlankLine($columnWidths)); - } - - /** - * This function computes the sizes of the columns depending on the size of - * what they will contain. - * - * @author Antoine Durieux - * - */ - private function computeColumnWidths() - { - // In case we have no head - if(count($this->header) != 0) - { - $columnWidths = array_map('mb_strlen',$this->header); - } - else - { - $columnWidths = array_map('mb_strlen',$this->body[key($this->body)]); - } - foreach($this->body as $row) - { - foreach($row as $index => $value) - { - $columnWidths[$index] = max(mb_strlen($value),$columnWidths[$index]); - } - } - - return $columnWidths; - } - - /** - * private static function printBlankLine($columnWidths) - * - * This function returns a string that corresponds to a decorating line. - * - * @author Antoine Durieux - * - * @version 1.0 - * - * @param array $columnWidths The widths of the columns - * @return string The resulting string - */ - private function printBlankLine($columnWidths) - { - $line = '+'; - foreach(array_keys($columnWidths) as $index) - { - $line .= str_repeat('-',$columnWidths[$index]+2).'+'; - } - return $line; - } - - /** - * This function returns a string that corresponds to a regular line of the - * table. - * - * @author Antoine Durieux - * - * @version 1.0 - * - * @param array $line The line to be printed - * @param array $columnWidths The widths of the columns - * @return string The resulting string - */ - private function printLine($line,$columnWidths) - { - $string = '|'; - foreach($line as $index => $value) - { - $string .= ' '.$value.str_repeat(' ',$columnWidths[$index]-mb_strlen($value)).' |'; - } - return $string; - } - - /** - * This function prints a line in the console - * - * @author Antoine Durieux - * - * @version 1.0 - * - * @param string $string The string to print in the console - */ - public function printConsole($string) - { - $this->output->writeln($string); - } -}- \ No newline at end of file diff --git a/src/backend/PartKeepr/Util/UtilService.php b/src/backend/PartKeepr/Util/UtilService.php @@ -1,13 +0,0 @@ -<?php -namespace PartKeepr\Util; - -use PartKeepr\Service\AnonService; - -class UtilService extends AnonService { - public function clearCache () { - apc_clear_cache(); - apc_clear_cache("user"); - - return array("status" => "ok"); - } -}- \ No newline at end of file